├── .gitignore ├── CTCI ├── bin │ ├── ch10_scalability_memorylimits │ │ ├── ch10_3_test.txt │ │ ├── intro │ │ └── inverted_index │ ├── ch15_database │ │ └── intro │ ├── ch16_threads_locks │ │ └── intro │ ├── ch18_hard │ │ └── test │ ├── ch1_arrays_strings │ │ └── intro │ ├── ch2_linkedlist │ │ └── intro │ ├── ch3_stacks_queues │ │ └── intro │ ├── ch4_trees_graphs │ │ └── intro │ ├── ch5_bit_manipulation │ │ └── intro.txt │ ├── ch7_math_probability │ │ └── intro │ └── ch9_recursion_dynamic_programming │ │ └── intro └── src │ ├── ch10_scalability_memorylimits │ ├── ch10_1_QueryDataOnServer.java │ ├── ch10_2_LargeScaleGraphSearch.java │ ├── ch10_3_GenerateInteger.java │ ├── ch10_3_GenerateInteger2.java │ ├── ch10_3_test.txt │ ├── ch10_4_CheckDuplicatesInArray.java │ ├── ch10_5_WebCrawling.java │ ├── ch10_6_FindDuplicateURLs.java │ ├── ch10_7_CacheQuery.java │ ├── intro │ └── inverted_index │ ├── ch11_sorting_searching │ ├── BinarySearchClosest.java │ ├── CountInversionsInArray.java │ ├── CountingSort.java │ ├── InsertionSort.java │ ├── LongestIncreasingSubsequence.java │ ├── LongestIncreasingSubsequence2.java │ ├── MergeSort.java │ ├── QuickSelect.java │ ├── QuickSort.java │ ├── RadixSort.java │ ├── ch11_1_MergeSortedArrays.java │ ├── ch11_2_GroupAnagrams.java │ ├── ch11_3_SearchInRotatedArray.java │ ├── ch11_4_ExternalSort.java │ ├── ch11_5_SearchInArrayWithEmptyStrings.java │ ├── ch11_6_Search2DMatrix2.java │ ├── ch11_7_LongestIncreasingSubSequence3.java │ └── ch11_8_RankNumberInStream.java │ ├── ch15_database │ └── intro │ ├── ch16_threads_locks │ ├── ThreadAndProcess.java │ └── intro │ ├── ch17_moderate │ ├── ch17_10_EncodeXML.java │ ├── ch17_11_RandomNumber.java │ ├── ch17_12_TwoSum.java │ ├── ch17_13_FlattenBinaryTreeToLinkedList2.java │ ├── ch17_14_FindMinWordBreak.java │ ├── ch17_1_SwapInPlace.java │ ├── ch17_2_TicTacToeState.java │ ├── ch17_3_TrailingZerosInFactorial.java │ ├── ch17_4_FindMaxOfTwoNumbers.java │ ├── ch17_5_MasterMind.java │ ├── ch17_6_ShortestUnsortedSubsequence.java │ ├── ch17_7_DescribeInteger.java │ ├── ch17_8_MaximumSubarray.java │ └── ch17_9_WordCount.java │ ├── ch18_hard │ ├── FindMaxSubsquare2.java │ ├── FindMinDistanceOfTwoNumbers.java │ ├── ch18_10_WordLadder.java │ ├── ch18_11_FindMaxSubsqaure.java │ ├── ch18_12_FindMaxSubmatrixSum.java │ ├── ch18_1_BitAddOperation.java │ ├── ch18_2_ShuffleCards.java │ ├── ch18_3_GetRandomSetFromArray.java │ ├── ch18_4_CountTwo.java │ ├── ch18_5_FindMinDistanceOfWords.java │ ├── ch18_6_FIndKSmallestElementsInArray.java │ ├── ch18_7_LongestWord.java │ ├── ch18_8_SearchSrings.java │ ├── ch18_9_GetMedianOfStreamingArray.java │ └── test │ ├── ch1_arrays_strings │ ├── SquareMatrixMultiply.java │ ├── ch1_1_UniqueCharInString.java │ ├── ch1_2_ReverseString.java │ ├── ch1_3_IsStringPermutation.java │ ├── ch1_4_ReplaceSpaces.java │ ├── ch1_5_CompressString.java │ ├── ch1_6_RotateImage.java │ ├── ch1_7_SetMatrixZeros.java │ ├── ch1_8_RotationString.java │ └── intro │ ├── ch2_linkedlist │ ├── FindMedianOfSortedList.java │ ├── ListNode.java │ ├── ReverseLinkedList.java │ ├── ch2_1_RemoveDuplicatesFromUnsortedList.java │ ├── ch2_1_RemoveDuplicatesInList.java │ ├── ch2_2_FindNthNodeFromEndOfList.java │ ├── ch2_3_RemoveNodeFromList.java │ ├── ch2_4_PartitionList.java │ ├── ch2_5_AddTwoNumbers2.java │ ├── ch2_6_LinkedListCycle2.java │ ├── ch2_7_PalindromeList.java │ └── intro │ ├── ch3_stacks_queues │ ├── ImplementQueue.java │ ├── ImplementStack.java │ ├── Node.java │ ├── ch3_1_ImplementThreeStacksUsingOneArray.java │ ├── ch3_2_ImplementStackWithMinValues.java │ ├── ch3_3_ImplementSetOfStacks.java │ ├── ch3_4_TowerOfHanoi.java │ ├── ch3_5_ImplementQueueUsingTwoStacks.java │ ├── ch3_6_SortStack.java │ ├── ch3_7_AnimalQueue.java │ └── intro │ ├── ch4_trees_graphs │ ├── FindLCAInBST.java │ ├── FindPathsOfTargetSum2.java │ ├── TreeNode.java │ ├── ch4_1_BalancedBinaryTree.java │ ├── ch4_2_GraphTraversal.java │ ├── ch4_3_ConvertSortedArrayToBST.java │ ├── ch4_4_BinaryTreeLevelOrderTraversal.java │ ├── ch4_5_ValidateBST.java │ ├── ch4_6_FindInorderSuccessorOfBST.java │ ├── ch4_7_FindLCAInBinaryTree.java │ ├── ch4_8_IsSubTree.java │ ├── ch4_9_FindPathsOfTargetSum.java │ └── intro │ ├── ch5_bit_manipulation │ ├── ch5_1_InsertBitRange.java │ ├── ch5_2_BaseConversion2.java │ ├── ch5_3_NumberSequence.java │ ├── ch5_4_EvaluateExpression.java │ ├── ch5_5_HammingDistanceInBinaryFormat.java │ ├── ch5_6_SwapBits.java │ ├── ch5_7_FindMissingIntegerUsingBitManipulation.java │ ├── ch5_8_DrawHorizontalLine.java │ └── intro.txt │ ├── ch6_brainteasers │ ├── ch6_1_PillWeight.java │ ├── ch6_2_FillBoardWithDominos.java │ ├── ch6_3_PourWater.java │ ├── ch6_4_BlueEyes.java │ ├── ch6_5_MinimumDrops.java │ └── ch6_6_ToggleLockers.java │ ├── ch7_math_probability │ ├── BaseConversion.java │ ├── IsPrimeNumber.java │ ├── Line.java │ ├── Point.java │ ├── ch7_1_BasketballShot.java │ ├── ch7_2_AntCollision.java │ ├── ch7_3_LineIntersection.java │ ├── ch7_4_MultiplyTwoIntegers.java │ ├── ch7_5_CutSquares.java │ ├── ch7_6_MaxPointsOnALine.java │ ├── ch7_7_GetKthMagicNumber.java │ └── intro │ ├── ch8_ood │ ├── CallHandler.java │ ├── ch8_1_BlackJack.java │ ├── ch8_2_HandleCalls.java │ ├── ch8_3_JukeBox.java │ ├── ch8_4_ParkingLot.java │ ├── ch8_5_OnlineReaderSystem.java │ └── ch8_9.java │ └── ch9_recursion_dynamic_programming │ ├── ch9_10_LongestIncreasingSubsequence4.java │ ├── ch9_1_ClimbingStairs.java │ ├── ch9_2_UniquePaths.java │ ├── ch9_3_MagicIndex.java │ ├── ch9_4_Subsets.java │ ├── ch9_5_StringPermutations.java │ ├── ch9_6_GenerateParentheses.java │ ├── ch9_7_PaintFill.java │ ├── ch9_8_CoinChange.java │ ├── ch9_9_11_EvaluateBooleanExpression.java │ ├── ch9_9_8Queens.java │ └── intro ├── Company ├── bin │ ├── amazon │ │ └── others │ │ │ ├── Concept_GraphSearch │ │ │ ├── Concept_HashTable │ │ │ ├── Shell_GrepIPAddress │ │ │ └── Shell_GrepPhoneNumber │ ├── facebook │ │ └── Balances_testcases │ │ │ ├── input000.txt │ │ │ ├── input001.txt │ │ │ ├── output000.txt │ │ │ └── output001.txt │ └── groupon │ │ └── others │ │ └── BrainTeaser_25Horses └── src │ ├── amazon │ ├── AverageScore.java │ ├── BitAddOperation.java │ ├── BitDivideOperation.java │ ├── BitMinusOperation.java │ ├── BitMultiplyOperation.java │ ├── CoinChange.java │ ├── CountBitOne.java │ ├── CreateMirrorTree.java │ ├── CubeRoot.java │ ├── DeserializePreorderArrayOfBST.java │ ├── DiameterOfBinaryTree.java │ ├── DistanceOfTwoNodesInBST.java │ ├── FindConsecutiveRange.java │ ├── FindKthLargestInArray.java │ ├── FindMissingInteger.java │ ├── FindMissingTermInArithmeticProgression.java │ ├── FindOneMissingInteger.java │ ├── FindTwoMissingIntegers.java │ ├── FindWordsInBorad.java │ ├── IntersectionOfTwoSortedArray.java │ ├── IsMirrorTree.java │ ├── IsSumTree.java │ ├── KDistanceNeighborsInBinaryTree.java │ ├── KNearestNeighbors.java │ ├── MinValueOnMinSumPath.java │ ├── MinimumCoinChange.java │ ├── PythagoreanTriple.java │ ├── RandomNumber.java │ ├── ReservoirSampleing.java │ ├── SerializationOfBinaryTree.java │ └── others │ │ ├── Concept_GraphSearch │ │ ├── Concept_HashTable │ │ ├── Shell_GrepIPAddress │ │ └── Shell_GrepPhoneNumber │ ├── facebook │ ├── ArrayProduct.java │ ├── Balances.java │ ├── Balances_testcases │ │ ├── input000.txt │ │ ├── input001.txt │ │ ├── output000.txt │ │ └── output001.txt │ ├── Bar.java │ ├── Bar_testcases │ │ ├── input000.txt │ │ └── output000.txt │ ├── BeautifulNumberGame.java │ ├── CelebrityProblem.java │ ├── Codec.java │ ├── ConvertExcelColumnNumber.java │ ├── FindMinMaxInArrayWithLeastComparison.java │ ├── FindSquaresInPlainOfPoints.java │ ├── FlattenLinkedList.java │ ├── GraphTraversal.java │ ├── ImplementLog2.java │ ├── ImplementReadKCharacters.java │ ├── ImplementReadLine.java │ ├── InterleaveLinkedList.java │ ├── IntervalScheduling.java │ ├── IsBipartiteGraph.java │ ├── JumpRiver.java │ ├── KPalindrome.java │ ├── LargestAreaOfOnesInMatrix.java │ ├── LetterCombinationsOfAPhoneNumber2.java │ ├── LineSegmentIntersection.java │ ├── LongestCommonSubString.java │ ├── LongestCommonSubsequence.java │ ├── MinEggDrops.java │ ├── MinimumSwapsToSortArray.java │ ├── MonitorServerPerformance.java │ ├── MultiplyTwoBigIntegers.java │ ├── MultiplyTwoLinkedList.java │ ├── NumberOfPalindromicSubstrings.java │ ├── PrintBinaryTreeInVerticalOrder.java │ ├── RestructArray.java │ ├── ReversePolishNotation.java │ ├── SearchPivotInRotatedArray.java │ ├── SerializeAndDeserializeStrings.java │ ├── SinkZerosInBinaryTree.java │ ├── SquareRootWithPrecision.java │ ├── SumOfContinuousSubsequence.java │ ├── SumOfHammingDistance.java │ ├── TrimBinarySearchTree.java │ ├── WeightedIntervalScheduling.java │ ├── test11.txt │ ├── test12.txt │ ├── test13.txt │ ├── test21.txt │ ├── test22.txt │ ├── test23.txt │ ├── test31.txt │ ├── test32.txt │ ├── test33.txt │ ├── test41.txt │ ├── test42.txt │ └── test43.txt │ ├── google │ ├── AnagramSubstring.java │ ├── ArrayPartitionSum.java │ ├── BitCombinations.java │ ├── BoundaryTraversalOfBinaryTree.java │ ├── BuildTreeFromNodePairs.java │ ├── DecimalDivision.java │ ├── FindCloestToMeanOfStreamingData.java │ ├── FindHNumber.java │ ├── FindLocalMinima.java │ ├── FmailyTree.java │ ├── GetDecimalZipOfTwoIntegers.java │ ├── ImplementIterator.java │ ├── JavaPassByValue.java │ ├── KthElementInBST.java │ ├── LongestSubstringOfKDistinctCharacters.java │ ├── MajorityElement.java │ ├── MatrixDiagonalSum.java │ ├── MaxProductOfTwoDifferentWords.java │ ├── MergeQuardTrees.java │ ├── MinNumberOfSquareSum.java │ ├── NumberOfValidParenthesis.java │ ├── OptimalMeetingPoint.java │ ├── ReverseStackUsingRecursion.java │ ├── ReverseUTF8.java │ ├── RotateArray.java │ ├── RunLengthEncoding.java │ ├── ScheduleMeetingsInMinimumRooms.java │ ├── ShuffleArrayInMagicOrder.java │ ├── SodaWaterMachine.java │ ├── StringPermutations2.java │ ├── TrappingRainWater2.java │ ├── ValidateBSTWithDuplicates.java │ ├── WeightedRandomGenerator.java │ └── YoungTableau.java │ ├── groupon │ ├── FillBoardWithWords.java │ ├── FindInorderPredecessorInBST.java │ ├── MedianOfStreamingData.java │ └── others │ │ └── BrainTeaser_25Horses │ ├── lib │ ├── ArrayGenerator.java │ ├── BST.java │ ├── BSTTests.java │ ├── BinaryHeap.java │ ├── BinaryHeapTests.java │ ├── DoublyListNode.java │ ├── HashMap.java │ ├── HashMapTests.java │ ├── Interval.java │ ├── LineSegment.java │ ├── ListNode.java │ ├── Point.java │ ├── TestSegmentTree.java │ ├── TreeNode.java │ ├── Trie.java │ └── TrieTests.java │ ├── linkedin │ ├── PaintHouse.java │ ├── RangeQueryInStreamingData.java │ ├── ReversePolishNotation.java │ └── TrieTest2.java │ ├── microsoft │ ├── InterleavingArray.java │ ├── InterleavingArray2.java │ ├── MirrorImage.java │ ├── NextPrimeNumber.java │ ├── PrimeNumberGenerator.java │ └── RandomNumberWithProbability.java │ ├── redfin │ └── FibonacciValue.java │ ├── rocketfuel │ ├── EditDistance2.java │ ├── Laser.java │ └── RacerRater.java │ ├── slideshare │ ├── BattleshipShoot.java │ ├── EquilibriumIndexOfArray.java │ ├── FactorialSum.java │ ├── FizzBuzz.java │ └── TicTacToeState.java │ ├── square │ └── ThiefProblem.java │ ├── twitter │ ├── AnagramOfPalindrome.java │ ├── BestTimeToBuyAndSellStocks4.java │ ├── CountBinaryTreesConstructedFromPreorderSequence.java │ ├── CountOneInBitExpression.java │ ├── EquilibriumIndexOfMatrix.java │ ├── EvenPairsInArray.java │ ├── FindPathsOfTargetSum3.java │ ├── InfixNotationEvaluation.java │ ├── KthSmallestInTwoSortedArrays.java │ ├── LargestMagicSet.java │ ├── LongestIncreasingSubarray.java │ ├── MapReduceMedian.java │ ├── MaximumBinaryGap.java │ ├── OutOfOrderScore.java │ ├── SearchNamesInTweets.java │ ├── ShortestAdditionChain.java │ └── URLShortening.java │ ├── yahoo │ ├── ImplementIterator2.java │ ├── ImplementStrstr2.java │ ├── KHighestStocks.java │ ├── MaxDistanceInversion.java │ ├── MaximumSubsequenceSum.java │ ├── NextPermutation2.java │ ├── NextPermutation3.java │ ├── RangeQueryInStreamingData.java │ └── SortStackUsingRecursion.java │ └── zillow │ ├── FirstUniqueCharInString.java │ ├── InsertAndDeleteInTrinaryTree.java │ └── StringToLong.java ├── KnowledgeBase ├── myNotes.md └── root.md ├── LeetCode Question Difficulty Distribution.pdf ├── LeetCode ├── 2sum.java ├── 3Sum.java ├── 3SumClosest.java ├── 4Sum.java ├── AddBinary.java ├── AddTwoNumbers.java ├── Anagrams.java ├── BalancedBinaryTree.java ├── BestTimeToBuyAndSellStock.java ├── BestTimeToBuyAndSellStock2.java ├── BestTimeToBuyAndSellStock3.java ├── BinaryTreeInorderTraversal.java ├── BinaryTreeLevelOrderTraversal.java ├── BinaryTreeLevelOrderTraversal2.java ├── BinaryTreeMaximumPathSum.java ├── BinaryTreePostorderTraversal.java ├── BinaryTreePreorderTraversal.java ├── BinaryTreeZigZagLevelOrderTraversal.java ├── Candy.java ├── ClimbingStairs.java ├── CloneGraph.java ├── CombinationSum.java ├── CombinationSum2.java ├── Combinations.java ├── ConstructBTFromPostorderAndInorderTraversal.java ├── ConstructBTFromPreorderAndInorderTraversal.java ├── ContainerWithMostWater.java ├── ConvertSortedArrayToBST.java ├── ConvertSortedListToBST.java ├── CopyListWithRandomPointer.java ├── CountAndSay.java ├── DecodeWays.java ├── DistinctSubsequence.java ├── DivideTwoIntegers.java ├── EditDistance.java ├── EvaluateReversePolishNotation.java ├── FirstMissingPositive.java ├── FlattenBinaryTreeToLinkedList.java ├── GasStation.java ├── GenerateParenthesis.java ├── GrayCode.java ├── ImplementstrStr().java ├── InsertInterval.java ├── InsertionSortList.java ├── IntegerToRoman.java ├── InterleavingString.java ├── JumpGame.java ├── JumpGame2.java ├── LRUCache.java ├── LargestRectangleInHistogram.java ├── LengthOfLastWord.java ├── LetterCombinationsOfAPhoneNumber.java ├── LinkedListCycle.java ├── LinkedListCycle2.java ├── LongestCommonPrefix.java ├── LongestConsecutiveSequence.java ├── LongestPalindromicSubstring.java ├── LongestSubstringWithoutRepeatingCharacters.java ├── LongestValidParentheses.java ├── MaxPointsOnALine.java ├── MaximalRectangle.java ├── MaximumDepthOfBT.java ├── MaximumSubarray.java ├── MedianOfTwoSortedArrays.java ├── MergeIntervals.java ├── MergeKSortedList.java ├── MergeSortedArray.java ├── MergeTwoSortedList.java ├── MinimumDepthOfBT.java ├── MinimumPathSum.java ├── MinimumWindowSubstring.java ├── MultiplyStrings.java ├── NQueens.java ├── NQueens2.java ├── NextPermutation.java ├── PalindromeNumber.java ├── PalindromePartitioning.java ├── PalindromePartitioning2.java ├── PartitionList.java ├── Pascal'sTriangle.java ├── Pascal'sTriangle2.java ├── PathSum.java ├── PathSum2.java ├── PermutationSequence.java ├── Permutations.java ├── Permutations2.java ├── PlusOne.java ├── PopulatingNextRightPointersInEachNode.java ├── PopulatingNextRightPointersInEachNode2.java ├── Pow.java ├── RecoverBinarySearchTree.java ├── RegularExpressionMatching.java ├── RemoveDuplicatesFromSortedArray.java ├── RemoveDuplicatesFromSortedArray2.java ├── RemoveDuplicatesFromSortedList.java ├── RemoveDuplicatesFromSortedList2.java ├── RemoveElement.java ├── RemoveNthNodeFromEndOfList.java ├── ReorderList.java ├── RestoreIPAddresses.java ├── ReverseInteger.java ├── ReverseLinkedList2.java ├── ReverseNodesInKGroup.java ├── ReverseWordsInString.java ├── RomanToInteger.java ├── RotateImage.java ├── RotateList.java ├── SameTree.java ├── ScrambleString.java ├── Search2DMatrix.java ├── SearchForARange.java ├── SearchInRotatedSortedArray.java ├── SearchInRotatedSortedArray2.java ├── SearchInsertPosition.java ├── SetMatrixZero.java ├── SimplifyPath.java ├── SingleNumber.java ├── SingleNumber2.java ├── SortColors.java ├── SortList.java ├── SpiralMatrix.java ├── SpiralMatrix2.java ├── Sqrt.java ├── StringToInteger.java ├── Subsets.java ├── Subsets2.java ├── SubstringWithConcatenationOfAllWords.java ├── SudokuSolver.java ├── SumRootToLeafNumbers.java ├── SurroundedRegions.java ├── SwapNodesInPairs.java ├── SymmetricTree.java ├── TextJustification.java ├── TrappingRainWater.java ├── Triangle.java ├── UniqueBinarySearchTree.java ├── UniqueBinarySearchTree2.java ├── UniquePaths.java ├── UniquePaths2.java ├── ValidNumber.java ├── ValidPalindrome.java ├── ValidParenthesis.java ├── ValidSudoku.java ├── ValidateBinarySearchTree.java ├── WildcardMatching.java ├── WordBreak.java ├── WordBreak2.java ├── WordLadder.java ├── WordLadder2.java ├── WordSearch.java ├── ZigZagConversion.java └── mmm.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .DS_Store 3 | 4 | *.plist 5 | 6 | *.zip 7 | 8 | *.jpg 9 | 10 | LeetCodeTracker.numbers/Metadata/DocumentIdentifier 11 | 12 | *.class 13 | 14 | CTCI/.classpath 15 | 16 | CTCI/.project 17 | 18 | CTCI/bin/ 19 | 20 | Company/.classpath 21 | 22 | Company/.project 23 | 24 | Company/bin/ 25 | 26 | *.pdf 27 | 28 | *.prefs 29 | -------------------------------------------------------------------------------- /CTCI/bin/ch10_scalability_memorylimits/intro: -------------------------------------------------------------------------------- 1 | A Typical System 2 | Hard Drive Space, Memory, Internet Transfer Latency 3 | 4 | Divide up lots of data 5 | <1> By order of Occurrence 6 | Ad: never use more machines than are necessary 7 | <2> By Hash Value 8 | the data is stored on machine #[ mod(hash(key), N) ]. N is the number of machines 9 | <3> By Actual Value 10 | store similar data on the same machines 11 | <4> Arbitrarily 12 | -------------------------------------------------------------------------------- /CTCI/bin/ch18_hard/test: -------------------------------------------------------------------------------- 1 | Julie Sussman, P.P.A., once at the 2 | -------------------------------------------------------------------------------- /CTCI/bin/ch2_linkedlist/intro: -------------------------------------------------------------------------------- 1 | singly linked list vs. doubly linked list 2 | 3 | The runner technique 4 | iterate through the linked list with two pointers simultaneously, with one ahead of the other -------------------------------------------------------------------------------- /CTCI/bin/ch3_stacks_queues/intro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/CTCI/bin/ch3_stacks_queues/intro -------------------------------------------------------------------------------- /CTCI/bin/ch4_trees_graphs/intro: -------------------------------------------------------------------------------- 1 | Binary Tree vs. Binary Search Tree 2 | BST: left < root < right 3 | 4 | Balanced vs. Unbalanced 5 | Balanced tree: 6 | depth of subtrees will not vary by more than a certain amount. 7 | it doesn't mean that the left and right subtrees are exactly the same size. 8 | 9 | Full and Complete: 10 | have exactly 2^n -1 nodes 11 | 12 | Binary tree traversal: 13 | in-order, pre-order, post-order 14 | 15 | Tree Balancing: 16 | Red-Black Trees and AVL Trees 17 | 18 | Trie: 19 | 20 | Graph Traversal: 21 | DFS 22 | BFS 23 | remember to mark the visited node to avoid cycle 24 | -------------------------------------------------------------------------------- /CTCI/bin/ch5_bit_manipulation/intro.txt: -------------------------------------------------------------------------------- 1 | Bit Manipulation 2 | 3 | Some tricks: 4 | ~0 is a sequence of 1s 5 | x & (~0 << n) clear the rightmost n bits of x 6 | x & (~x) is a sequence of 1s 7 | x ^ 0s = x 8 | x ^ 1s = ~x 9 | x ^ x = 0 10 | 11 | Get Bit 12 | int getBit(int num, int i){ 13 | return (num< Bottom Up: 8 | start with knowing how to solve the problem for a simple case. 9 | the key here is to think about how you can build the solution for one case off of the previous case 10 | <2> Top Down: 11 | think about how to divide the problem for case N into sub-problems. 12 | Be careful of overlap between the case. 13 | 14 | Dynamic Programming: 15 | Recursive with cache -------------------------------------------------------------------------------- /CTCI/src/ch10_scalability_memorylimits/ch10_1_QueryDataOnServer.java: -------------------------------------------------------------------------------- 1 | package ch10_scalability_memorylimits; 2 | 3 | public class ch10_1_QueryDataOnServer { 4 | /* 5 | * Imagine you are building some sort of service that will be called by up to 1000 client 6 | * applications to get simple end-of-day stock price information (open, close, high, low). You 7 | * may assume that you already have the data, and you can store it in any format you wish. How 8 | * would you design the client-facing service which provides the information to client 9 | * application? You are responsible for the development, rollout, and ongoing monitoring and 10 | * maintenance of the feed. Describe the different methods you considered and why you would 11 | * recommend your approach. Your service can use any technologies you wish, and can distribute 12 | * the information to the client applications in any mechanism you choose. 13 | */ 14 | 15 | // SOL1: 16 | // provide database access to the clients 17 | // PRO: easy to setup and integrate 18 | // DIS: security issue caused by client-access; client may get access to some data they 19 | // shouldn't access; server overhead 20 | 21 | // SOL2: 22 | // use JSON/XML file to transfer data to clients 23 | // PRO: readable for both human and machines; easy to scale(we can add more elements to the 24 | // existing files); easy for client-side backup; restrict client access to specific data 25 | } 26 | -------------------------------------------------------------------------------- /CTCI/src/ch10_scalability_memorylimits/ch10_5_WebCrawling.java: -------------------------------------------------------------------------------- 1 | package ch10_scalability_memorylimits; 2 | 3 | public class ch10_5_WebCrawling { 4 | /* 5 | * If you were designing a web crawler, how would you avoid getting into infinite loops? 6 | */ 7 | 8 | // <1> if we picture the web as a graph of links, the process of crawling is to do BFS. An 9 | // infinite 10 | // loop will occur when a cycle occurs. 11 | // <2> to avoid cycle, we need to mark the visited nodes. The problem is to choose the identifier 12 | // of one page. If we use URL, same domain with different parameters may be considered as 13 | // different pages, but they actually point to the same page; if we use page content, what if 14 | // there's 15 | // dynamic content on the page? 16 | // <3> to create the identifier by combining URL and page content 17 | // <4> the crawling process: 18 | // [1] we have a database to store a list of items which we need to crawl. On each iteration, we 19 | // select the highest priority page to crawl 20 | // [2] open up the page and create a signature of the page base on specific subsections of the 21 | // page and its URL 22 | // [3] query the database to see whether anything with this signature has been crawled recently. 23 | // [4] If something with this signature has been crawled, insert this page back into the database 24 | // at a low priority; otherwise, crawl the page and insert its links into the database 25 | 26 | } 27 | -------------------------------------------------------------------------------- /CTCI/src/ch10_scalability_memorylimits/ch10_6_FindDuplicateURLs.java: -------------------------------------------------------------------------------- 1 | package ch10_scalability_memorylimits; 2 | 3 | public class ch10_6_FindDuplicateURLs { 4 | /** 5 | * You have 10 billion URLs. How do you detect the duplicate documents? In this case, assume that 6 | * "duplicate" means that the URLs are identical 7 | */ 8 | 9 | // Assume each URL is an average of 100 characters, and each character is 4 bytes, then this list 10 | // of 10 billion URLs will take up about 4 TB. 11 | 12 | // It's trivial if we have enough memory, we can use a map to mark the appeared URLs 13 | 14 | // SOL1: one computer with enough disk space 15 | // <1> split the URLs into 4000 chunks of 1GB each. Each URL u will be stored into a file named 16 | // .txt where x = hash(u)%4000. 17 | // <2> traverse each file using hashmap 18 | 19 | // SOL2: multiple machines 20 | // <1> rather than split the URLs into separate files, we split them into multiple machines 21 | // <2> find duplicates on each machine and send back the results 22 | // PRO: parallel, high efficiency 23 | // DIS: complexity of the system, other machines may not be reliable 24 | } 25 | -------------------------------------------------------------------------------- /CTCI/src/ch10_scalability_memorylimits/intro: -------------------------------------------------------------------------------- 1 | A Typical System 2 | Hard Drive Space, Memory, Internet Transfer Latency 3 | 4 | Divide up lots of data 5 | <1> By order of Occurrence 6 | Ad: never use more machines than are necessary 7 | <2> By Hash Value 8 | the data is stored on machine #[ mod(hash(key), N) ]. N is the number of machines 9 | <3> By Actual Value 10 | store similar data on the same machines 11 | <4> Arbitrarily 12 | -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/BinarySearchClosest.java: -------------------------------------------------------------------------------- 1 | package ch11_sorting_searching; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | public class BinarySearchClosest { 8 | 9 | /** 10 | * Binary search a sorted array to find the closest element of the target 11 | */ 12 | 13 | // Basic binary search + choose between A[start] end A[end] 14 | // Remember to check the bound of start and end 15 | // time: O(lgn) 16 | public int binarySearchClosest(int[] arr, int target) { 17 | int start = 0, end = arr.length - 1; 18 | while (start <= end) { 19 | int mid = start + ((end - start) >> 1); 20 | if (arr[mid] < target) 21 | start = mid + 1; 22 | else if (arr[mid] > target) 23 | end = mid - 1; 24 | else 25 | return mid; 26 | } 27 | if (start >= arr.length) 28 | return end; // bound check 29 | else if (end < 0) 30 | return start; 31 | else { 32 | if (arr[start] - target < target - arr[end]) 33 | return start; 34 | else 35 | return end; 36 | } 37 | } 38 | 39 | @Test 40 | public void test() { 41 | int[] arr = new int[] { -1, 4, 5, 7, 10 }; 42 | System.out.println(Arrays.toString(arr)); 43 | System.out.println(binarySearchClosest(arr, 3)); 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package ch11_sorting_searching; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | public class InsertionSort { 8 | 9 | /** 10 | * Implement in place insertion sort 11 | */ 12 | 13 | // time: O(n^2); space: O(1) 14 | public void insertionSort(int[] arr) { 15 | if (arr == null || arr.length <= 1) 16 | return; 17 | for (int i = 1; i < arr.length; i++) { 18 | insert(arr, i); 19 | } 20 | } 21 | 22 | // traverse from the end of sorted sub-array, move elements while find insertion position 23 | // we can use binary search here to optimize the running time of searching for the insertion 24 | // position but we still have to move the right half elements, which takes O(n) 25 | // time: O(n) 26 | private void insert(int[] arr, int num_index) { 27 | int num = arr[num_index]; 28 | int i = num_index - 1; 29 | for (; i >= 0 && num < arr[i]; i--) 30 | arr[i + 1] = arr[i]; 31 | arr[i + 1] = num; 32 | } 33 | 34 | @Test 35 | public void test() { 36 | int[] arr = new int[] { 20, -3, -10, 30, 50 }; 37 | insertionSort(arr); 38 | System.out.println(Arrays.toString(arr)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/QuickSelect.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/CTCI/src/ch11_sorting_searching/QuickSelect.java -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/QuickSort.java: -------------------------------------------------------------------------------- 1 | package ch11_sorting_searching; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | public class QuickSort { 8 | 9 | /** 10 | * Quick-sort is a divide and conquer algorithm. 11 | * It divides a large list into two smaller sub-lists, 12 | * then recursively sort the sub-lists 13 | */ 14 | 15 | // from CLRS, easier to deal with index 16 | public void quickSort(int[] arr, int start, int end) { 17 | if (arr == null || arr.length <= 1 || start >= end) 18 | return; 19 | int pivot = partition(arr, start, end); 20 | quickSort(arr, start, pivot - 1); 21 | quickSort(arr, pivot + 1, end); 22 | } 23 | 24 | private int partition(int[] arr, int start, int end) { 25 | int pivot_value = arr[end]; // choose last element's value as pivot here 26 | int i = start, j = start; 27 | for (; j <= end - 1; j++) { 28 | if (arr[j] <= pivot_value) { 29 | swap(arr, i++, j); 30 | } 31 | } 32 | swap(arr, i, end); // put pivotValue into pivot position 33 | return i; 34 | } 35 | 36 | private void swap(int[] arr, int l, int r) { 37 | if (l == r) 38 | return; 39 | int tmp = arr[l]; 40 | arr[l] = arr[r]; 41 | arr[r] = tmp; 42 | } 43 | 44 | @Test 45 | public void test() { 46 | int[] arr = new int[] { 14, 8, 7, 2, 2, 3, 45, 44, 8, 2 }; 47 | quickSort(arr, 0, arr.length - 1); 48 | System.out.println(Arrays.toString(arr)); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/ch11_1_MergeSortedArrays.java: -------------------------------------------------------------------------------- 1 | package ch11_sorting_searching; 2 | 3 | public class ch11_1_MergeSortedArrays { 4 | 5 | /** 6 | * You're given two sorted arrays, A and B, where A has a large enough buffer at the end 7 | * to hold B. Write a method to merge B into A in sorted order. 8 | */ 9 | 10 | // Same to Leetcode/MergeSortedArray 11 | 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/ch11_2_GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | package ch11_sorting_searching; 2 | 3 | 4 | 5 | public class ch11_2_GroupAnagrams { 6 | 7 | /** 8 | * Write a method to sort an array of strings so that all the anagrams are next to each other 9 | * Group anagrams in a string array 10 | */ 11 | 12 | // Same to Leetcode/Anagrams 13 | 14 | } 15 | -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/ch11_3_SearchInRotatedArray.java: -------------------------------------------------------------------------------- 1 | package ch11_sorting_searching; 2 | 3 | public class ch11_3_SearchInRotatedArray { 4 | 5 | /** 6 | * Find the index of a target number in a rotated array 7 | * if there're repeated target numbers, return which index? 8 | */ 9 | 10 | // Same to Leetcode/SearchInRotatedArray 11 | 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch11_sorting_searching/ch11_4_ExternalSort.java: -------------------------------------------------------------------------------- 1 | package ch11_sorting_searching; 2 | 3 | public class ch11_4_ExternalSort { 4 | /** 5 | * Imagine you have a 20GB file with one string per line. Explain how you would sort the file. 6 | */ 7 | 8 | // split the file into several small blocks, each is below the maximum size of RAM. 9 | // read each block to RAM, heap sort, then write back to the disk 10 | // merge all the blocks, one by one. 11 | 12 | // This is known as external sort 13 | // http://en.wikipedia.org/wiki/External_sorting 14 | } 15 | -------------------------------------------------------------------------------- /CTCI/src/ch16_threads_locks/ThreadAndProcess.java: -------------------------------------------------------------------------------- 1 | package ch16_threads_locks; 2 | 3 | public class ThreadAndProcess { 4 | /* 5 | * What's the difference between thread and process 6 | */ 7 | // Process: 8 | // [1] Each process has its own resources, including memory space 9 | // [2] each process have at least one thread and may have multiple threads 10 | // Thread: 11 | // [1] thread is a light-weight process 12 | // [2] threads in the same process share resources 13 | } 14 | -------------------------------------------------------------------------------- /CTCI/src/ch17_moderate/ch17_11_RandomNumber.java: -------------------------------------------------------------------------------- 1 | package ch17_moderate; 2 | 3 | public class ch17_11_RandomNumber { 4 | 5 | /** 6 | * Generate random7, given random5 7 | */ 8 | 9 | // Same to Company/amazon/RandomNumber 10 | 11 | } 12 | -------------------------------------------------------------------------------- /CTCI/src/ch17_moderate/ch17_12_TwoSum.java: -------------------------------------------------------------------------------- 1 | package ch17_moderate; 2 | 3 | public class ch17_12_TwoSum { 4 | 5 | /** 6 | * 2sum 7 | */ 8 | 9 | // Same to Leetcode/2sum 10 | } 11 | -------------------------------------------------------------------------------- /CTCI/src/ch17_moderate/ch17_1_SwapInPlace.java: -------------------------------------------------------------------------------- 1 | package ch17_moderate; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | public class ch17_1_SwapInPlace { 8 | 9 | /** 10 | * Write a function to swap two numbers in place (that is, without temporary variable) 11 | */ 12 | 13 | 14 | public void swapInPlace(int[] nums) { 15 | nums[0] = nums[0] + nums[1]; 16 | nums[1] = nums[0] - nums[1]; 17 | nums[0] = nums[0] - nums[1]; 18 | } 19 | 20 | public void swapInPlace2(int[] nums) { 21 | nums[0] = nums[0] ^ nums[1]; 22 | nums[1] = nums[0] ^ nums[1]; 23 | nums[0] = nums[0] ^ nums[1]; 24 | } 25 | 26 | @Test 27 | public void test() { 28 | int[] nums = new int[] { 3, 4 }; 29 | System.out.println(Arrays.toString(nums)); 30 | swapInPlace(nums); 31 | System.out.println(Arrays.toString(nums)); 32 | swapInPlace2(nums); 33 | System.out.println(Arrays.toString(nums)); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /CTCI/src/ch17_moderate/ch17_2_TicTacToeState.java: -------------------------------------------------------------------------------- 1 | package ch17_moderate; 2 | 3 | public class ch17_2_TicTacToeState { 4 | 5 | /** 6 | * Design an algorithm to figure out if someone has win a game of tic-tac-toe 7 | */ 8 | 9 | // similar to TicTacToeState(Company/slideshare) 10 | // Note" 11 | // consider one more point: How to improve the performance if we have to check state 12 | // in each step? 13 | 14 | // if the board is small (typical size is 3), we can store the all board states (3^9) in a map 15 | // the key is unique, representing the state of all cells in board, value is the result of the 16 | // board 17 | // one key for example, 3^0*c1 + 3^1*c2 + 3^2*c3+ ... 18 | 19 | } 20 | -------------------------------------------------------------------------------- /CTCI/src/ch17_moderate/ch17_4_FindMaxOfTwoNumbers.java: -------------------------------------------------------------------------------- 1 | package ch17_moderate; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch17_4_FindMaxOfTwoNumbers { 6 | 7 | /** 8 | * Write a method which finds the maximum of two numbers. You should not use if-else or any other 9 | * comparison operator. 10 | */ 11 | 12 | // <1> avoid comparison, check sign bit of a-b 13 | // <2> avoid if-else, use a*x+b*(~x), x=1 or x=0 14 | // <3> avoid overflow 15 | public int findMaxOfTwoNumbers(int a, int b) { 16 | int c = a - b; 17 | int sa = sign(a), sb = sign(b), sc = sign(c); 18 | int differentSign = sa ^ sb; // if a,b have different signs, differentSign=1 19 | // There're two cases max is B 20 | // [1] a,b different in signs, a is negative 21 | // [2] a,b same in signs, c is negative 22 | int maxIsB = differentSign * sa + flip(differentSign) * sc; 23 | return flip(maxIsB) * a + maxIsB * b; 24 | } 25 | 26 | // return the most significant bit of num 27 | private int sign(int num) { 28 | return (num >> 31) & 1; 29 | } 30 | 31 | // flip one bit 32 | private int flip(int num) { 33 | return num ^ 1; 34 | } 35 | 36 | @Test 37 | public void test() { 38 | int a = Integer.MAX_VALUE, b = Integer.MIN_VALUE; 39 | System.out.println(findMaxOfTwoNumbers(a, b)); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /CTCI/src/ch17_moderate/ch17_8_MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package ch17_moderate; 2 | 3 | public class ch17_8_MaximumSubarray { 4 | 5 | /** 6 | * You are given an array of integers (both positive an negative). 7 | * Find the contiguous sequence with the largest sum. Return sum. 8 | */ 9 | // Same to Leetcode/MaximumSubarray 10 | 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /CTCI/src/ch17_moderate/ch17_9_WordCount.java: -------------------------------------------------------------------------------- 1 | package ch17_moderate; 2 | 3 | public class ch17_9_WordCount { 4 | 5 | /** 6 | * Design a method to find the frequency of any given word in a book 7 | */ 8 | 9 | // use a map. consider two points: 10 | // <1> Capatilization 11 | // <2> Punctuation 12 | 13 | } 14 | -------------------------------------------------------------------------------- /CTCI/src/ch18_hard/ch18_10_WordLadder.java: -------------------------------------------------------------------------------- 1 | package ch18_hard; 2 | 3 | public class ch18_10_WordLadder { 4 | 5 | /** 6 | * Given two words of equal length that are in a dictionary, write a method to transform one word 7 | * into another word by changing only one letter at a time. The new word you get in each step 8 | * must be in the dictionary 9 | */ 10 | // LeetCode/WordLadder2 (store previous nodes to recover all the valid paths) 11 | 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch18_hard/ch18_1_BitAddOperation.java: -------------------------------------------------------------------------------- 1 | package ch18_hard; 2 | 3 | public class ch18_1_BitAddOperation { 4 | 5 | /** 6 | * Write a function that adds two numbers. You should not use + or any arithmetic operations 7 | */ 8 | 9 | // Same to Company/amazon -- BitAddOperation 10 | 11 | } 12 | -------------------------------------------------------------------------------- /CTCI/src/ch18_hard/ch18_6_FIndKSmallestElementsInArray.java: -------------------------------------------------------------------------------- 1 | package ch18_hard; 2 | 3 | public class ch18_6_FIndKSmallestElementsInArray { 4 | 5 | /** 6 | * Describe an algorithm to find the smallest one million numbers in one billion numbers. Assume 7 | * that the computer memory can hold all one billion numbers. 8 | */ 9 | /* 10 | * <1> sort, O(nlgn) 11 | * <2> maxHeap O(nlgm) 12 | * Traverse through the list, for each element, we insert it into the heap and delete the largest 13 | * element from the heap. 14 | * <3> quick select, average: O(n); worst: O(n^2) 15 | */ 16 | // Similar to Company/amazon/FindTheKthSmallestInArray 17 | 18 | } 19 | -------------------------------------------------------------------------------- /CTCI/src/ch18_hard/test: -------------------------------------------------------------------------------- 1 | Julie Sussman, P.P.A., once at the 2 | -------------------------------------------------------------------------------- /CTCI/src/ch1_arrays_strings/SquareMatrixMultiply.java: -------------------------------------------------------------------------------- 1 | package ch1_arrays_strings; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | public class SquareMatrixMultiply { 8 | 9 | /** 10 | * Given two square matrices of size N*N, get the multiplication matrix 11 | */ 12 | 13 | // There exists a solution using divide and conquer, with O(n^2.8) running time 14 | // refer to CLRS 15 | 16 | // Calculate based on the definition of matrix multiplication 17 | // time: O(n^3); space: O(n^2) 18 | public int[][] multiply(int[][] A, int B[][]) { 19 | int N = A.length; 20 | int[][] res = new int[N][N]; 21 | for (int i = 0; i < N; i++) { 22 | for (int j = 0; j < N; j++) { 23 | for (int k = 0; k < N; k++) { 24 | res[i][j] += A[i][k] * B[k][j]; 25 | } 26 | } 27 | } 28 | return res; 29 | } 30 | 31 | public void printMatrix(int[][] A) { 32 | for (int i = 0; i < A.length; i++) 33 | System.out.println(Arrays.toString(A[i])); 34 | System.out.println(""); 35 | } 36 | 37 | @Test 38 | public void test() { 39 | int[][] A = new int[][] { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 }, }; 40 | int[][] B = new int[][] { { 2, 2, 2 }, { 2, 2, 2 }, { 2, 2, 2 }, }; 41 | printMatrix(A); 42 | printMatrix(B); 43 | printMatrix(multiply(A, B)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /CTCI/src/ch1_arrays_strings/ch1_2_ReverseString.java: -------------------------------------------------------------------------------- 1 | package ch1_arrays_strings; 2 | 3 | public class ch1_2_ReverseString { 4 | 5 | /** 6 | * Implement a function void reverse(char* str) in C or C++ which 7 | * reverses a null-terminated string 8 | */ 9 | 10 | 11 | 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch1_arrays_strings/ch1_5_CompressString.java: -------------------------------------------------------------------------------- 1 | package ch1_arrays_strings; 2 | 3 | public class ch1_5_CompressString { 4 | 5 | /** 6 | * Implement a method to perform basic string compression using the counts 7 | * of repeated characters. For example, the string "aabcccccaaa" would become 8 | * a2b1c5a3. if the "compressed" string would not become smaller than the original 9 | * string, return the original string 10 | */ 11 | 12 | // Same to Company/google/RunLengthEncoding 13 | 14 | } 15 | -------------------------------------------------------------------------------- /CTCI/src/ch1_arrays_strings/ch1_6_RotateImage.java: -------------------------------------------------------------------------------- 1 | package ch1_arrays_strings; 2 | 3 | 4 | public class ch1_6_RotateImage { 5 | 6 | /** 7 | * Given an image represented by an N*N matrix, where each pixel in the image is 4 bytes 8 | * write a method to rotate the image by 90 degrees. Do this in place 9 | */ 10 | 11 | // Same to Leetcode/RotateImage 12 | 13 | } 14 | -------------------------------------------------------------------------------- /CTCI/src/ch1_arrays_strings/ch1_7_SetMatrixZeros.java: -------------------------------------------------------------------------------- 1 | package ch1_arrays_strings; 2 | 3 | 4 | public class ch1_7_SetMatrixZeros { 5 | 6 | /** 7 | * Write an algorithm such that if an element in an M * N matrix is 0, its entire 8 | * row and column are set to 0 9 | */ 10 | 11 | // Same to Leetcode/SetMatrixZeros 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch1_arrays_strings/ch1_8_RotationString.java: -------------------------------------------------------------------------------- 1 | package ch1_arrays_strings; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch1_8_RotationString { 6 | 7 | /** 8 | * Assume you have a method isSubstring which checks if one word 9 | * is a substring of another. Given two strings, s1 and s2, write code 10 | * to check if s2 is a rotation of s1 using only one call to isSubstring 11 | * e.g. "erbottlewat" is a rotation of "waterbottle" 12 | */ 13 | 14 | // The trick is that if one word A is a rotation of another one B, A should be 15 | // a substring of B+B. 16 | // time: O(n); space: O(n) 17 | public boolean isRotation(String s1, String s2) { 18 | if (s1 == null || s2 == null) 19 | return s1 == null && s2 == null; 20 | String s3 = s1 + s1; 21 | return isSubstring(s3, s2); 22 | } 23 | 24 | public boolean isSubstring(String s1, String s2) { 25 | for (int i = 0; i < s1.length() - s2.length(); i++) { 26 | int index = i; 27 | int j = 0; 28 | for (; j < s2.length(); j++) { 29 | if (s2.charAt(j) == s1.charAt(index)) 30 | index++; 31 | else 32 | break; 33 | } 34 | if (j == s2.length()) 35 | return true; 36 | } 37 | return false; 38 | } 39 | 40 | @Test 41 | public void test() { 42 | System.out.println(isRotation("abc", "bca")); 43 | System.out.println(isRotation("abc", "aca")); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/ListNode.java: -------------------------------------------------------------------------------- 1 | package ch2_linkedlist; 2 | 3 | public class ListNode { 4 | public int val; 5 | public ListNode next; 6 | 7 | public ListNode(int val){ 8 | this.val = val; 9 | next = null; 10 | } 11 | 12 | public ListNode(int[] arr){ 13 | // assert arr.length > 0 14 | ListNode node = buildList(arr); 15 | this.val = node.val; 16 | this.next = node.next; 17 | } 18 | 19 | public static ListNode buildList(int[] arr){ 20 | ListNode head = new ListNode(arr[0]); 21 | ListNode p = head; 22 | for (int i = 1; i < arr.length; i++){ 23 | p.next = new ListNode(arr[i]); 24 | p = p.next; 25 | } 26 | return head; 27 | } 28 | 29 | public String printList(){ 30 | StringBuilder sb = new StringBuilder(); 31 | sb.append(val); 32 | sb.append("-> "); 33 | ListNode p = this.next; 34 | while (p != null){ 35 | sb.append(p.val); 36 | sb.append("-> "); 37 | p = p.next; 38 | } 39 | sb.append("null"); 40 | return sb.toString(); 41 | } 42 | 43 | public String toString(){ 44 | return val+""; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/ch2_1_RemoveDuplicatesFromUnsortedList.java: -------------------------------------------------------------------------------- 1 | package ch2_linkedlist; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch2_1_RemoveDuplicatesFromUnsortedList { 6 | 7 | /** 8 | * Write code to remove duplicates from an unsorted linked list 9 | * e.g. [1,2,6,1,4,5,4] -> [1,2,6,4,5] 10 | * Note: use constant space 11 | */ 12 | 13 | // Maintain two pointers 14 | // time: O(n^2), space: O(1) 15 | public ListNode removeDuplicates(ListNode head) { 16 | if (head == null || head.next == null) 17 | return head; 18 | ListNode p = head; 19 | while (p != null) { 20 | ListNode pp = p; 21 | while (pp.next != null) { 22 | if (pp.next.val == p.val) { 23 | pp.next = pp.next.next; 24 | } else 25 | pp = pp.next; 26 | } 27 | p = p.next; 28 | } 29 | return head; 30 | } 31 | 32 | @Test 33 | public void test() { 34 | int[] arr = new int[] { 1, 2, 6, 1, 4, 5, 4 }; 35 | ListNode head = new ListNode(arr); 36 | System.out.println(head.printList()); 37 | System.out.println(removeDuplicates(head).printList()); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/ch2_1_RemoveDuplicatesInList.java: -------------------------------------------------------------------------------- 1 | package ch2_linkedlist; 2 | 3 | public class ch2_1_RemoveDuplicatesInList { 4 | 5 | /* 6 | * Write code to remove duplicates from an unsorted linked list 7 | * e.g. [1,2,6,1,4,5,4] -> [1,2,6,4,5] 8 | * Note: use constant space 9 | */ 10 | public static void main(String[] args) { 11 | int[] arr = new int[]{1,2,6,1,4,5,4}; 12 | ListNode head = new ListNode(arr); 13 | System.out.println(head.printList()); 14 | System.out.println(removeDuplicates(head).printList()); 15 | } 16 | 17 | // time: O(n^2), space: O(1) 18 | public static ListNode removeDuplicates(ListNode head){ 19 | if (head == null || head.next == null) 20 | return head; 21 | ListNode p = head; 22 | while (p != null){ 23 | ListNode pp = p; 24 | while (pp.next != null){ 25 | if (pp.next.val == p.val){ 26 | pp.next = pp.next.next; 27 | }else 28 | pp = pp.next; 29 | } 30 | p = p.next; 31 | } 32 | return head; 33 | } 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/ch2_2_FindNthNodeFromEndOfList.java: -------------------------------------------------------------------------------- 1 | package ch2_linkedlist; 2 | 3 | public class ch2_2_FindNthNodeFromEndOfList { 4 | 5 | /** 6 | * Implement an algorithm to find the kth to last element of a singly linked list 7 | * Note: assume k is always valid 8 | */ 9 | 10 | // same to Leetcode/RemoveNthNodeFromEndOfList 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/ch2_3_RemoveNodeFromList.java: -------------------------------------------------------------------------------- 1 | package ch2_linkedlist; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch2_3_RemoveNodeFromList { 6 | 7 | /** 8 | * Delete a node in the middle of a singly linked list, given only access to that node 9 | */ 10 | 11 | // copy the value of next node to current node 12 | // time: O(1), space: O(1) 13 | public ListNode deleteNode(ListNode node) { 14 | if (node == null || node.next == null) 15 | return null; 16 | node.val = node.next.val; 17 | node.next = node.next.next; 18 | return node; 19 | } 20 | 21 | @Test 22 | public void test() { 23 | int[] arr = new int[] { 5, 2, 5, 4, 5, 6, 2 }; 24 | ListNode head = new ListNode(arr); 25 | ListNode node = head.next.next.next; 26 | System.out.println(node.printList()); 27 | System.out.println(deleteNode(node).printList()); 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/ch2_4_PartitionList.java: -------------------------------------------------------------------------------- 1 | package ch2_linkedlist; 2 | 3 | 4 | public class ch2_4_PartitionList { 5 | 6 | /** 7 | * Partition a linked list around a value x, such that all 8 | * nodes less than x come before all nodes greater than or equal to x 9 | */ 10 | 11 | // Same to Leetcode/PartitionList 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/ch2_6_LinkedListCycle2.java: -------------------------------------------------------------------------------- 1 | package ch2_linkedlist; 2 | 3 | public class ch2_6_LinkedListCycle2 { 4 | 5 | /** 6 | * Given a circular linked list, returns the node at the beginning of the loop 7 | */ 8 | 9 | // Same to Leetcode/LinkedListCycle2 10 | 11 | } 12 | -------------------------------------------------------------------------------- /CTCI/src/ch2_linkedlist/intro: -------------------------------------------------------------------------------- 1 | singly linked list vs. doubly linked list 2 | 3 | The runner technique 4 | iterate through the linked list with two pointers simultaneously, with one ahead of the other -------------------------------------------------------------------------------- /CTCI/src/ch3_stacks_queues/ImplementStack.java: -------------------------------------------------------------------------------- 1 | package ch3_stacks_queues; 2 | 3 | import org.junit.Test; 4 | 5 | public class ImplementStack { 6 | 7 | /** 8 | * Implement the stack 9 | */ 10 | 11 | // Use LinkedList 12 | // Maintain top poniter 13 | class MyStack { 14 | private Node top; 15 | 16 | public MyStack() { 17 | top = null; 18 | } 19 | 20 | public Object pop() { 21 | if (top == null) 22 | throw new NullPointerException(); 23 | Object value = top.value; 24 | top = top.next; 25 | return value; 26 | } 27 | 28 | public void push(Object value) { 29 | Node tmp = new Node(value); 30 | tmp.next = top; 31 | top = tmp; 32 | } 33 | 34 | public Object peek() { 35 | return top.value; 36 | } 37 | 38 | public boolean isEmpty(){ 39 | return top==null; 40 | } 41 | 42 | public String toString(){ 43 | Node p = top; 44 | StringBuilder sb = new StringBuilder(); 45 | while (p!=null){ 46 | sb.append(p.value); 47 | p = p.next; 48 | } 49 | return sb.reverse().toString(); 50 | } 51 | } 52 | 53 | @Test 54 | public void test(){ 55 | MyStack st = new MyStack(); 56 | for (int i=0; i<10; i++){ 57 | st.push(i); 58 | System.out.println(st); 59 | } 60 | for (int i=0; i<10; i++){ 61 | st.pop(); 62 | System.out.println(st); 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /CTCI/src/ch3_stacks_queues/Node.java: -------------------------------------------------------------------------------- 1 | package ch3_stacks_queues; 2 | 3 | public class Node implements Comparable{ 4 | Object value; 5 | Node next; 6 | 7 | public Node(){ 8 | this.value = null; 9 | next = null; 10 | } 11 | public Node(Object value){ 12 | this.value = value; 13 | next = null; 14 | } 15 | 16 | public int compareTo(Object other_obj) { 17 | return compareTo(other_obj); 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /CTCI/src/ch3_stacks_queues/intro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/CTCI/src/ch3_stacks_queues/intro -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/FindLCAInBST.java: -------------------------------------------------------------------------------- 1 | package ch4_trees_graphs; 2 | 3 | import org.junit.Test; 4 | 5 | public class FindLCAInBST { 6 | /** 7 | * Given a binary search tree, find the lowest common ancestor of two given nodes 8 | */ 9 | 10 | // Note the following solution cannot handle the case that a or b is not in bst 11 | 12 | // if acurr, b>curr, go right 14 | // else, lca 15 | // time: O(n); space: O(1) 16 | public TreeNode findLCA(TreeNode root, int a, int b) { 17 | if (root == null) 18 | return null; 19 | while (root != null) { 20 | if (a > root.val && b > root.val) 21 | root = root.right; 22 | else if (a < root.val && b < root.val) 23 | root = root.left; 24 | else 25 | break; 26 | } 27 | return root; 28 | } 29 | 30 | @Test 31 | public void test() { 32 | int[] arr = new int[] { 1, 3, 5, 7, 9, 14, 23, 32 }; 33 | TreeNode root = new TreeNode(arr); 34 | int a = 3, b = 23; 35 | System.out.println(root.printTree()); 36 | System.out.println("Node a: " + a); 37 | System.out.println("Node b: " + b); 38 | System.out.println("First Common Ancestor: " + findLCA(root, a, b)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/ch4_1_BalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | package ch4_trees_graphs; 2 | 3 | public class ch4_1_BalancedBinaryTree { 4 | 5 | /** 6 | * Implement a function to check if a binary tree is balanced. 7 | * A balanced tree is defined to be a tree such that the heights 8 | * of the two subtrees of any node never differ by more than one. 9 | */ 10 | 11 | // Same to Leetcode/BalancedBinaryTree 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/ch4_2_GraphTraversal.java: -------------------------------------------------------------------------------- 1 | package ch4_trees_graphs; 2 | 3 | public class ch4_2_GraphTraversal { 4 | 5 | /** 6 | * Given a directed graph, design an algorithm to find out whether there is a route between two 7 | * nodes 8 | */ 9 | // start from one node and use DFS or BFS to search for the target node 10 | } 11 | -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/ch4_3_ConvertSortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | package ch4_trees_graphs; 2 | 3 | public class ch4_3_ConvertSortedArrayToBST { 4 | 5 | /** 6 | * Given a sorted (increasing order) array with unique integer elements, write an 7 | * algorithm to create a binary search tree with minimal height 8 | */ 9 | 10 | // Same to Leetcode/ConvertSortedArrayToBST 11 | 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/ch4_4_BinaryTreeLevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package ch4_trees_graphs; 2 | 3 | 4 | public class ch4_4_BinaryTreeLevelOrderTraversal { 5 | 6 | /** 7 | * Given a binary tree, design an algorithm which creates a 8 | * linked list of all the nodes at each depth 9 | */ 10 | 11 | // Same to Leetcode/BinaryTreeLevelOrderTraversal 12 | } 13 | -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/ch4_5_ValidateBST.java: -------------------------------------------------------------------------------- 1 | package ch4_trees_graphs; 2 | 3 | 4 | public class ch4_5_ValidateBST { 5 | 6 | /** 7 | * Implement a function to check if a binary tree is a binary search tree. 8 | */ 9 | 10 | // Same to Leetcode/ValidateBinarySearchTree 11 | 12 | 13 | } 14 | -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/ch4_8_IsSubTree.java: -------------------------------------------------------------------------------- 1 | package ch4_trees_graphs; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | import org.junit.Test; 7 | 8 | public class ch4_8_IsSubTree { 9 | 10 | /** 11 | * Two very large binary trees: T1 and T2, 12 | * create an algorithm to decide if T2 is a subtree of T1 13 | */ 14 | 15 | // BFS to find the node same to T2's root, then check if the two trees are same 16 | // time: O(n^2) 17 | public boolean isSubtree(TreeNode t1, TreeNode t2) { 18 | if (t1 == null || t2 == null) 19 | return t1 == null && t2 == null; 20 | Queue qu = new LinkedList(); 21 | qu.add(t1); 22 | while (!qu.isEmpty()) { 23 | TreeNode curr = qu.poll(); 24 | if (isSameTree(curr, t2)) 25 | return true; 26 | if (curr.left != null) 27 | qu.add(curr.left); 28 | if (curr.right != null) 29 | qu.add(curr.right); 30 | } 31 | return false; 32 | } 33 | 34 | private boolean isSameTree(TreeNode t1, TreeNode t2) { 35 | if (t1 == null || t2 == null) 36 | return t1 == null && t2 == null; 37 | return (t1.val == t2.val) && isSameTree(t1.left, t2.left) && isSameTree(t1.right, t2.right); 38 | } 39 | 40 | @Test 41 | public void test() { 42 | int[] arr1 = new int[] { 50, 3, 5, 7, 9, 14, 23, 32 }; 43 | int[] arr2 = new int[] { 50, 3, 5 }; 44 | TreeNode t1 = new TreeNode(arr1); 45 | TreeNode t2 = new TreeNode(arr2); 46 | System.out.println(isSubtree(t1, t2)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /CTCI/src/ch4_trees_graphs/intro: -------------------------------------------------------------------------------- 1 | Binary Tree vs. Binary Search Tree 2 | BST: left < root < right 3 | 4 | Balanced vs. Unbalanced 5 | Balanced tree: 6 | depth of subtrees will not vary by more than a certain amount. 7 | it doesn't mean that the left and right subtrees are exactly the same size. 8 | 9 | Full and Complete: 10 | have exactly 2^n -1 nodes 11 | 12 | Binary tree traversal: 13 | in-order, pre-order, post-order 14 | 15 | Tree Balancing: 16 | Red-Black Trees and AVL Trees 17 | 18 | Trie: 19 | 20 | Graph Traversal: 21 | DFS 22 | BFS 23 | remember to mark the visited node to avoid cycle 24 | -------------------------------------------------------------------------------- /CTCI/src/ch5_bit_manipulation/ch5_2_BaseConversion2.java: -------------------------------------------------------------------------------- 1 | package ch5_bit_manipulation; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch5_2_BaseConversion2 { 6 | 7 | /** 8 | * Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, 9 | * print the binary representation. If the number cannot be represented accurately 10 | * in binary with at most 32 characters, print "ERROR" 11 | */ 12 | 13 | // See CTCI/ch7/BaseConversion 14 | 15 | // know how to convert the fractional part of a decimal number to binary number 16 | // http://en.wikipedia.org/wiki/Binary_number 17 | public String doubleToBinaryString(double d) { 18 | if (d >= 1 || d <= 0) 19 | return "ERROR"; 20 | StringBuilder sb = new StringBuilder(); 21 | sb.append("."); // Remember to add '.' 22 | while (d > 0) { 23 | if (sb.length() >= 32) 24 | return "ERROR"; 25 | double r = d * 2; 26 | if (r >= 1) { 27 | sb.append("1"); 28 | d = r - 1; 29 | } else { 30 | sb.append("0"); 31 | d = r; 32 | } 33 | } 34 | return sb.toString(); 35 | } 36 | 37 | @Test 38 | public void test() { 39 | double d = 0.125; 40 | System.out.println(doubleToBinaryString(d)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /CTCI/src/ch5_bit_manipulation/ch5_4_EvaluateExpression.java: -------------------------------------------------------------------------------- 1 | package ch5_bit_manipulation; 2 | 3 | public class ch5_4_EvaluateExpression { 4 | 5 | /** 6 | * Explain what the following code does: ((n&(n-1))==0) 7 | */ 8 | // consider (A&B)==0 9 | // consider difference between A and A-1 10 | // e.g. n=abcde1000, n-1=abcde0111 11 | 12 | // solution: check if n is a power of 2 (or if n is 0) 13 | 14 | } 15 | -------------------------------------------------------------------------------- /CTCI/src/ch5_bit_manipulation/ch5_5_HammingDistanceInBinaryFormat.java: -------------------------------------------------------------------------------- 1 | package ch5_bit_manipulation; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch5_5_HammingDistanceInBinaryFormat { 6 | 7 | /** 8 | * Calculate the number of bits that will need to be changed in order to convert an integer X 9 | * into another integer Y. 10 | */ 11 | 12 | // Sol1: 13 | // count the edit distance digit by digit 14 | // time: O(32) 15 | public int bitConversion(int a, int b) { 16 | int count = 0; 17 | if (a == b) 18 | return 0; 19 | for (int i = 0; i < 32; i++) { 20 | int mask = 1 << i; 21 | if (((a & mask) > 0) != ((b & mask) > 0)) 22 | count++; 23 | } 24 | return count; 25 | } 26 | 27 | // Sol2 28 | // get the C = A^B, then count the '1's in C 29 | // time: O(k) 30 | public int bitConversion2(int a, int b) { 31 | int count = 0; 32 | int z = a ^ b; 33 | while (z != 0) { 34 | count += z & 1; 35 | z = z >> 1; 36 | } 37 | return count; 38 | } 39 | 40 | @Test 41 | public void test() { 42 | int a = 12, b = 16; 43 | System.out.println(Integer.toBinaryString(a)); 44 | System.out.println(Integer.toBinaryString(b)); 45 | System.out.println(bitConversion(a, b)); 46 | System.out.println(bitConversion2(a, b)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /CTCI/src/ch5_bit_manipulation/ch5_6_SwapBits.java: -------------------------------------------------------------------------------- 1 | package ch5_bit_manipulation; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch5_6_SwapBits { 6 | 7 | /** 8 | * Write a program to swap odd and even bits in an integer with as few instructions as possible 9 | */ 10 | 11 | /* Use mask number to get the odd bits and even bits, shift them to get new odd bits and even bits 12 | * <1> get all odd bits and right-shift by 1 13 | * <2> get all even bits and left-shift by 1 14 | * <3> a: 1010; 5:0101 15 | */ 16 | public int swapBits(int num) { 17 | return ((num & 0xaaaaaaaa) >> 1) | ((num & 0x55555555) << 1); 18 | } 19 | 20 | @Test 21 | public void test() { 22 | int num = 345; 23 | System.out.println(Integer.toBinaryString(num)); 24 | System.out.println(Integer.toBinaryString(swapBits(num))); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /CTCI/src/ch5_bit_manipulation/intro.txt: -------------------------------------------------------------------------------- 1 | Bit Manipulation 2 | 3 | Some tricks: 4 | ~0 is a sequence of 1s 5 | x & (~0 << n) clear the rightmost n bits of x 6 | x & (~x) is a sequence of 1s 7 | x ^ 0s = x 8 | x ^ 1s = ~x 9 | x ^ x = 0 10 | 11 | Get Bit 12 | int getBit(int num, int i){ 13 | return (num< take one pill from Bottle#1, two pills from Bottle#2, three pills from Bottle#3, and so 13 | // on. 14 | // <2> Weigh this mix of pills. If all pills were one gram each, the scale would reach 210 grams 15 | // ( 1 + 2 + 3 + ... + 20 = 21*20/2=210) 16 | // <3> Get the bottle number by formula: (weight - 210 grams)/0.1 grams 17 | } 18 | -------------------------------------------------------------------------------- /CTCI/src/ch6_brainteasers/ch6_2_FillBoardWithDominos.java: -------------------------------------------------------------------------------- 1 | package ch6_brainteasers; 2 | 3 | public class ch6_2_FillBoardWithDominos { 4 | 5 | /** 6 | * There is an 8*8 chess board in which two diagonally opposite corners have been cut off. You 7 | * are given 31 dominos, and a single domino can cover exactly two squares. Can you use the 31 8 | * dominos to cover the entire board? Prove your answer (by providing an example or showing why 9 | * it's impossible) 10 | */ 11 | 12 | // SOL 13 | // 31 dominos will take up 31 white squares and 31 black squares exactly. On this board, however, 14 | // we have 30 black squares and 32 white squares (the two squares that have been cut are black). 15 | // Hence, it's impossible (see CTCI book for the picture) 16 | } 17 | -------------------------------------------------------------------------------- /CTCI/src/ch6_brainteasers/ch6_3_PourWater.java: -------------------------------------------------------------------------------- 1 | package ch6_brainteasers; 2 | 3 | public class ch6_3_PourWater { 4 | 5 | /** 6 | * We have a five-quart jug, a three-quart jug, and an unlimited supply of water (but no 7 | * measuring cups). How would you come up with exactly four quarts of water? (Note that the jugs 8 | * are oddly shaped, such that filling up exactly "half" of the jug would be impossible) 9 | */ 10 | 11 | // SOL 12 | // <1> fill(5) 13 | // <2> pour(5, 3) pour from 5 to 3 until 3 is full or 5 is empty 14 | // <3> pour(5, 3) now #3 has 2 quarts 15 | // <4> fill(5) 16 | // <5> pour(5,3) now #3 has 3, 5 has 4 17 | } 18 | -------------------------------------------------------------------------------- /CTCI/src/ch6_brainteasers/ch6_4_BlueEyes.java: -------------------------------------------------------------------------------- 1 | package ch6_brainteasers; 2 | 3 | public class ch6_4_BlueEyes { 4 | 5 | /** 6 | * A bunch of people are living on an island, when a visitor comes with a strange order: all 7 | * blue-eyed people must leave the island as soon as possible. There will be a flight out at 8PM 8 | * every evening. Each person can see everyone else's eye color, but they do not know their own 9 | * (nor is anyone allowed to tell them). Additionally, they do not know how many people have blue 10 | * eyes, although they do know that at least one person does. How many days will it take the 11 | * blue-eyed people to leave? 12 | */ 13 | 14 | // SOL 15 | // use induction 16 | // analyze the case: 17 | // <1> exact 1 person has blue eyes. The blue will leave the first night 18 | // <2> exact 2 people have blue eyes. Both leave on the second night 19 | // <3> c people have blue eyes. It will take c nights for the blue-eyed people to leave. All will 20 | // leave on the same night. 21 | } 22 | -------------------------------------------------------------------------------- /CTCI/src/ch6_brainteasers/ch6_5_MinimumDrops.java: -------------------------------------------------------------------------------- 1 | package ch6_brainteasers; 2 | 3 | public class ch6_5_MinimumDrops { 4 | 5 | /** 6 | * There is a building of 100 floors. If an egg drops from the Nth floor or above, it will break. 7 | * If it's dropped from any floor below, it will not break. You're given two eggs. Find N, while 8 | * minimizing the number of drops for the worst case. 9 | */ 10 | 11 | // Load Balancing 12 | // if we drop Egg1 every 10 floors, best case total drops will be 1+9=10, worst case will be 13 | // 10+9=19. The worst case is 19. 14 | // [1] A perfectly load-balanced system would be one in which Drops(Egg1) + Drops(Egg2) is always 15 | // the same, regardless of where Egg1 breaks 16 | // [2] In this case, each time we add one more drop for Egg1, we should reduce one drop of Egg2 17 | // [3] Thus, Egg1 must start at floor X, then go up by X-1 floors, then X-2... until it gets to 18 | // 100 19 | 20 | } 21 | -------------------------------------------------------------------------------- /CTCI/src/ch6_brainteasers/ch6_6_ToggleLockers.java: -------------------------------------------------------------------------------- 1 | package ch6_brainteasers; 2 | 3 | public class ch6_6_ToggleLockers { 4 | 5 | /** 6 | * There're 100 closed lockers in a hallway. A man begins by opening all 100 lockers. Next, he 7 | * closes every second lockers. Then, on his third pass, he toggles every third locker (closes it 8 | * if it's open or opens it if it's closed). This process continues for 100 passes, such that on 9 | * each pass i, the man toggles every ith locker. After his 100th pass in the hallway, in which 10 | * he toggles only locker#100, how many lockers are open? 11 | */ 12 | 13 | // SOL: 14 | // <1> A door n is toggled once for each factor of n, including itself and 1. That is, door 15 is 15 | // toggled on rounds 1, 3, 5 and 15. 16 | // <2> A door is left open if the number of factors is odd. They're 1*1, 2*2 .. 10*10 17 | // <3> Thus, there're 10 lockers open at the end of this process 18 | } 19 | -------------------------------------------------------------------------------- /CTCI/src/ch7_math_probability/BaseConversion.java: -------------------------------------------------------------------------------- 1 | package ch7_math_probability; 2 | 3 | import org.junit.Test; 4 | 5 | public class BaseConversion { 6 | /** 7 | * Base conversion between base2 and base10. 8 | * Base2 is given as a string 9 | */ 10 | 11 | // time: O(n); space:O(1), n is length of s 12 | public int convert2To10(String s) { 13 | long res = 0; // in case of overflow 14 | char[] ss = s.toCharArray(); 15 | int pos = 0; 16 | for (int i = ss.length - 1; i >= 0; i--) { 17 | if (ss[i] == '1') 18 | res += Math.pow(2, pos); 19 | pos++; 20 | } 21 | return (int) res; 22 | } 23 | 24 | // time: O(lgN); space: O(lgN), N is the value of base10 number 25 | public String convert10To2(int num) { 26 | StringBuilder sb = new StringBuilder(); 27 | while (num > 0) { 28 | sb.append(num % 2); 29 | num /= 2; 30 | } 31 | return sb.reverse().toString(); 32 | } 33 | 34 | @Test 35 | public void test() { 36 | for (int i = 0; i < 100; i++) { 37 | String binary = Integer.toBinaryString(i); 38 | System.out.println(binary + ": " + convert10To2(i)); 39 | System.out.println(i + ": " + convert2To10(binary)); 40 | System.out.println(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /CTCI/src/ch7_math_probability/IsPrimeNumber.java: -------------------------------------------------------------------------------- 1 | package ch7_math_probability; 2 | 3 | import org.junit.Test; 4 | 5 | public class IsPrimeNumber { 6 | 7 | /** 8 | * Given an integer, check whether it's a prime number 9 | */ 10 | 11 | // Sol1 12 | // Check whether num has a factor in [2...num-1] 13 | // time: O(n); space: O(1) 14 | public boolean isPrime(int num) { 15 | if (num < 2) 16 | return false; 17 | for (int i = 2; i < num; i++) 18 | if (num % i == 0) 19 | return false; 20 | return true; 21 | } 22 | 23 | // Sol2, narrow down the search space for factors from two perspectives 24 | // [1] all the even numbers can be omitted after we check num%2 25 | // [2] The sqrt would be sufficient, because for every number A which divides N evenly, there is 26 | // a complement B, where A*B=N. If A>sqrt, then B P2 => p > 3(1-p)p^2 + p^3 => (2p-1)(p-1) > 0 => p < 0.5 16 | // if p=0, p=0.5, p=1, the probability of winning two games are the same 17 | } 18 | -------------------------------------------------------------------------------- /CTCI/src/ch7_math_probability/ch7_2_AntCollision.java: -------------------------------------------------------------------------------- 1 | package ch7_math_probability; 2 | 3 | public class ch7_2_AntCollision { 4 | 5 | /** 6 | * There are three ants on different vertices of a triangle. What is the probability 7 | * of collision (between any two or all of them) if they start walking on the sides 8 | * of the triangle? Assume that each ant randomly picks a direction, with either 9 | * direction equally likely to be chosen, and that they walk at the same speed 10 | */ 11 | // FOLLOW UP 12 | // find the probability of collision with n ants on an n-vertex polygon 13 | 14 | 15 | // P(no collision) = 2*(1/2)^3 = 1/4 16 | // P(collision) = 1 - P (no collision) = 3/4 17 | 18 | // Followup 19 | // P = 1- 2/2^n 20 | } 21 | -------------------------------------------------------------------------------- /CTCI/src/ch7_math_probability/ch7_3_LineIntersection.java: -------------------------------------------------------------------------------- 1 | package ch7_math_probability; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch7_3_LineIntersection { 6 | 7 | /** 8 | * Given two lines on Cartesian plane, determine whether the two lines would intersect 9 | */ 10 | 11 | // [1] If two lines have different slopes, they will intersect 12 | // [2] The issue is that the slope is of double type, we may encounter precise loss issue 13 | // [3] Use epsilon to check equality 14 | public class Line { 15 | // understand limitations of floating point representation. Never check 16 | // for equality with ==. Instead, check if the difference is less than an epsilon value 17 | double epsilon = 0.0000001; 18 | double slope; 19 | double yintercept; 20 | 21 | public Line(double s, double y) { 22 | slope = s; 23 | yintercept = y; 24 | } 25 | 26 | public boolean intersect(Line l2) { 27 | return Math.abs(this.slope - l2.slope) > epsilon || Math.abs(this.yintercept - l2.yintercept) < epsilon; 28 | } 29 | } 30 | 31 | @Test 32 | public void test() { 33 | Line l1 = new Line(0.1, 5); 34 | Line l2 = new Line(0.1, 6); 35 | System.out.println(l1.intersect(l2)); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /CTCI/src/ch7_math_probability/ch7_4_MultiplyTwoIntegers.java: -------------------------------------------------------------------------------- 1 | package ch7_math_probability; 2 | 3 | import java.util.ArrayList; 4 | 5 | import org.junit.Test; 6 | 7 | public class ch7_4_MultiplyTwoIntegers { 8 | 9 | /** 10 | * Write methods to implement the multiply, subtract, and divide operations 11 | * for integers. Use only add operator 12 | */ 13 | 14 | // [1] Double num1 lg(num2) times and cache the temporary values 15 | // [2] Take care of signs 16 | // time: O(lgm), m is the value of num2 17 | public long multiply(int num1, int num2) { 18 | if (num1 == 0 || num2 == 0) 19 | return 0; 20 | int a = Math.abs(num1); 21 | int b = Math.abs(num2); 22 | if (a < b) 23 | return multiply(num2, num1); // algorithm is faster if a > b 24 | ArrayList values = new ArrayList(); 25 | int index = 0; 26 | while ((1 << index) <= b) { 27 | values.add(a); 28 | a = a << 1; 29 | index++; 30 | } 31 | index--; 32 | long mul = 0; 33 | while (b > 0) { 34 | if (b - (1 << index) >= 0) { 35 | mul += values.get(index); 36 | b -= (1 << index); 37 | } else 38 | index--; 39 | } 40 | return (num1 > 0) ^ (num2 > 0) ? -mul : mul; 41 | } 42 | 43 | // subtract, add num1 + neg(num2) 44 | // divide, see Leetcode -- DivideTwoIntegers, similar to multiply 45 | 46 | @Test 47 | public void test() { 48 | System.out.println(multiply(10, -21)); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /CTCI/src/ch7_math_probability/ch7_6_MaxPointsOnALine.java: -------------------------------------------------------------------------------- 1 | package ch7_math_probability; 2 | 3 | 4 | public class ch7_6_MaxPointsOnALine { 5 | /** 6 | * Given a two-dimensional graph with points on it, 7 | * find a line which passes the most number of points 8 | */ 9 | // Same to Leetcode/MaxPointsOnALine 10 | } 11 | -------------------------------------------------------------------------------- /CTCI/src/ch7_math_probability/intro: -------------------------------------------------------------------------------- 1 | Prime Numbers: 2 | every positive integers can be decomposed into a product of primes 3 | 84 = 2^2 * 3^1 * 5^0 * 7^1 * 11^0 ... 4 | That's why they're called prime numbers 5 | 6 | Probability: 7 | P (A^B) = P (A|B) * P(B) 8 | P (A | B) = P(A) + P(B) - P(A^B) 9 | Independent events: if one happening, tells nothing about the other happening 10 | Mutually Exclusive events: if one happening, then the other cannot happening 11 | 12 | -------------------------------------------------------------------------------- /CTCI/src/ch8_ood/ch8_5_OnlineReaderSystem.java: -------------------------------------------------------------------------------- 1 | package ch8_ood; 2 | 3 | import java.util.List; 4 | 5 | public class ch8_5_OnlineReaderSystem { 6 | /* 7 | * Design the data structure for an online book reader system 8 | */ 9 | 10 | // Models: Book, User; Controller, UserManager, BookManager; View, display the UI 11 | public class OnlineReaderSystem { 12 | private UserManager mUserManager; 13 | private BookManager mBookManager; 14 | private ReadingView mReadingView; 15 | } 16 | 17 | public class UserManager { 18 | private List users; 19 | 20 | public void registerUser(){ 21 | 22 | } 23 | 24 | public void loginUser(){ 25 | 26 | } 27 | } 28 | 29 | public class BookManager { 30 | private List books; 31 | 32 | // findBookByAuthor/findBookByData and other searches 33 | public Book findBookByName(String name) { 34 | Book b = null; 35 | return b; 36 | } 37 | 38 | public void add(){ 39 | 40 | } 41 | } 42 | 43 | public class ReadingView{ 44 | private User user; 45 | private Book book; 46 | } 47 | 48 | public class User { 49 | 50 | } 51 | 52 | public class Book { 53 | 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /CTCI/src/ch8_ood/ch8_9.java: -------------------------------------------------------------------------------- 1 | package ch8_ood; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * 7 | * Explain the data structure and algorithms 8 | * that you would use to design an in-memory file system. 9 | * 10 | */ 11 | 12 | // use tree structure, like tire implementation 13 | public class ch8_9 { 14 | public abstract class Node{ 15 | protected Node parent; 16 | protected long created; 17 | protected long lastUpdated; 18 | protected long lastAccessed; 19 | protected String name; 20 | protected Map children; 21 | protected Type type; 22 | 23 | public Node(){} 24 | 25 | public abstract int size(); 26 | 27 | public abstract boolean has(String filename); 28 | 29 | public abstract boolean remove(String filename); 30 | 31 | public abstract boolean create(String filename); 32 | 33 | // soft link file src and dst 34 | // find the node and put the filenam-node pair into the map 35 | public abstract boolean link(String src, String dst); 36 | } 37 | 38 | public enum Type{ 39 | Directory, File 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /CTCI/src/ch9_recursion_dynamic_programming/ch9_10_LongestIncreasingSubsequence4.java: -------------------------------------------------------------------------------- 1 | package ch9_recursion_dynamic_programming; 2 | 3 | public class ch9_10_LongestIncreasingSubsequence4 { 4 | 5 | /** 6 | * A stack of n boxes, with widths wi, heights hi, and depth di. The boxes cannot be rotated 7 | * and can only be stacked on top of one another if each box in the stack is strictly larger 8 | * than the box above it in width, height, and depth. 9 | * Find the tallest stack possible 10 | */ 11 | 12 | // complicated version of longest increasing subsequence 13 | // 1. sort width first 14 | // 2. get LIS of height 15 | // 3. get LIS of depth from 2 16 | } 17 | -------------------------------------------------------------------------------- /CTCI/src/ch9_recursion_dynamic_programming/ch9_1_ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package ch9_recursion_dynamic_programming; 2 | 3 | import org.junit.Test; 4 | 5 | public class ch9_1_ClimbingStairs { 6 | 7 | /** 8 | * Climbing stairs. 1/2/3 steps each time 9 | */ 10 | 11 | // Dynamic Programming 12 | public int climbingStairs(int n) { 13 | int[] mem = new int[n + 1]; 14 | mem[0] = 0; 15 | mem[1] = 1; 16 | mem[2] = 2; 17 | mem[3] = 4; 18 | for (int i = 4; i <= n; i++) { 19 | mem[i] = mem[i - 1] + mem[i - 2] + mem[i - 3]; 20 | } 21 | return mem[n]; 22 | } 23 | 24 | @Test 25 | public void test() { 26 | int num = 30; 27 | System.out.println(num); 28 | System.out.println(climbingStairs(num)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /CTCI/src/ch9_recursion_dynamic_programming/ch9_4_Subsets.java: -------------------------------------------------------------------------------- 1 | package ch9_recursion_dynamic_programming; 2 | 3 | 4 | public class ch9_4_Subsets { 5 | 6 | /** 7 | * Write a method to return all subsets of a set 8 | */ 9 | // Same to Leetcode/Subsets 10 | } 11 | -------------------------------------------------------------------------------- /CTCI/src/ch9_recursion_dynamic_programming/ch9_6_GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | package ch9_recursion_dynamic_programming; 2 | 3 | 4 | public class ch9_6_GenerateParentheses { 5 | 6 | /** 7 | * Implement an algorithm to print all valid combinations of n-pairs of parentheses 8 | */ 9 | // Same to Leetcode/GenerateParentheses 10 | 11 | } 12 | -------------------------------------------------------------------------------- /CTCI/src/ch9_recursion_dynamic_programming/ch9_8_CoinChange.java: -------------------------------------------------------------------------------- 1 | package ch9_recursion_dynamic_programming; 2 | 3 | public class ch9_8_CoinChange { 4 | 5 | /** 6 | * Given an infinite number of quarters (20 cents), dimes(10 cents), nickels(5 cents) 7 | * and pennies (1 cent), write code to calculate the number of ways of representing n cents 8 | */ 9 | // Same to Company/amazon/CoinChange 10 | 11 | } 12 | -------------------------------------------------------------------------------- /CTCI/src/ch9_recursion_dynamic_programming/ch9_9_8Queens.java: -------------------------------------------------------------------------------- 1 | package ch9_recursion_dynamic_programming; 2 | 3 | 4 | public class ch9_9_8Queens { 5 | 6 | /** 7 | * 8 Queens 8 | */ 9 | // Same to Leetcode/NQueens 10 | } 11 | -------------------------------------------------------------------------------- /CTCI/src/ch9_recursion_dynamic_programming/intro: -------------------------------------------------------------------------------- 1 | Questions can be solved: 2 | when you solve the problem like "find nth number..." or "implement a method to compute all...", it's likely 3 | that this is a recursive problem 4 | 5 | Approach: 6 | Base case + Build 7 | <1> Bottom Up: 8 | start with knowing how to solve the problem for a simple case. 9 | the key here is to think about how you can build the solution for one case off of the previous case 10 | <2> Top Down: 11 | think about how to divide the problem for case N into sub-problems. 12 | Be careful of overlap between the case. 13 | 14 | Dynamic Programming: 15 | Recursive with cache -------------------------------------------------------------------------------- /Company/bin/amazon/others/Concept_GraphSearch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/bin/amazon/others/Concept_GraphSearch -------------------------------------------------------------------------------- /Company/bin/amazon/others/Concept_HashTable: -------------------------------------------------------------------------------- 1 | 1. Explain how to solve the collisions in a hash table. 2 | Collision happens when two value has the same key, although they have different hash codes. 3 | Collision is solved by using a LinkedList to store the values with the same key 4 | 5 | 2. Time complexity of put a pair into the map. Best? Worst? Average? 6 | Best: 7 | O(1). use hash code to find the bucket index 8 | Worst: 9 | the 'put' triggers the resize of the hash table. In this case, a new bucket table 10 | is created. It doubles the size of the original table and need to copy all data of the original 11 | table, hence O(n) 12 | Average: 13 | O(1). Good hash table design improves the performance by choosing proper 14 | initial capacity and load factor. Initial capacity is the initial length of the table bucket, 15 | load factor decides when to resize the table bucket. Higher value of load factor decreases 16 | -------------------------------------------------------------------------------- /Company/bin/amazon/others/Shell_GrepIPAddress: -------------------------------------------------------------------------------- 1 | Q: 2 | Write Linux commands to find all the IP address in the current directory 3 | 4 | 192.168.1.1 5 | 6 | 7 | A: 8 | range: 0-255 9 | some special cases: 10 | 03.1.1.1 11 | 12 | grep -r '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$' . -------------------------------------------------------------------------------- /Company/bin/amazon/others/Shell_GrepPhoneNumber: -------------------------------------------------------------------------------- 1 | Q: 2 | Write Linux commands to find all the phone numbers in the current directory 3 | 4 | A: 5 | depends on the format of the phone number 6 | we use (000)000-0000 as example 7 | 8 | grep -r '^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$' . 9 | 10 | To search a single file 'foo' 11 | grep -r '^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$' 'foo' 12 | 13 | To search all the files on the computer 14 | grep -r '^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$' / 15 | -------------------------------------------------------------------------------- /Company/bin/facebook/Balances_testcases/input000.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 3 3 | 0 5 4 | 0 5 | 0 6 | 0 7 | 0 8 | 0 9 | 1 4 10 | 7 11 | 0 12 | 0 2 3 13 | 6 1 14 | -------------------------------------------------------------------------------- /Company/bin/facebook/Balances_testcases/input001.txt: -------------------------------------------------------------------------------- 1 | 22 2 | 0 1 2 3 | 2 3 4 5 4 | 0 11 9 5 | 0 10 6 | 0 7 | 0 8 | 0 6 9 | 0 7 10 | 0 11 | 0 13 14 15 12 | 0 13 | 0 14 | 0 19 15 | 0 16 | 0 17 | 0 8 18 | 0 19 | 1 20 | 0 21 | 0 22 | 0 23 | 0 24 | 0 12 25 | 7 26 | 0 27 | 0 28 | 0 29 | 0 30 | 0 31 | 0 32 | 0 16 33 | 0 17 34 | 0 35 | 0 36 | 0 18 37 | 11 38 | 0 39 | 0 40 | 0 41 | 0 42 | 3 21 43 | 5 44 | 1 45 | 2 46 | -------------------------------------------------------------------------------- /Company/bin/facebook/Balances_testcases/output000.txt: -------------------------------------------------------------------------------- 1 | 0: 147 0 2 | 1: 0 0 3 | 2: 0 0 4 | 3: 25 0 5 | 4: 0 7 6 | 5: 0 54 7 | -------------------------------------------------------------------------------- /Company/bin/facebook/Balances_testcases/output001.txt: -------------------------------------------------------------------------------- 1 | 0: 188 0 2 | 1: 0 30 3 | 2: 0 0 4 | 3: 4 0 5 | 4: 94 0 6 | 5: 0 0 7 | 6: 0 10 8 | 7: 12 0 9 | 8: 1 0 10 | 9: 0 0 11 | 10: 0 0 12 | 11: 0 3 13 | 12: 0 0 14 | 13: 0 0 15 | 14: 0 0 16 | 15: 22 0 17 | 16: 0 0 18 | 17: 1 0 19 | 18: 0 0 20 | 19: 0 0 21 | 20: 0 12 22 | 21: 1 0 23 | -------------------------------------------------------------------------------- /Company/bin/groupon/others/BrainTeaser_25Horses: -------------------------------------------------------------------------------- 1 | Brain Teaser -- 25 horses 2 | 3 | Given 25 horses, find the 3 fastest. 4 | You have no timer and can know the relative order of 5 horses in a match. 5 | What's the minimum number of matches you should have? 6 | 7 | A: 8 | Wrong: heap sort, merge 5 heaps, 5 + 3 = 8 9 | 10 | Correct: 11 | Divide into 5 teams 12 | a1>a2>...a5 13 | b1>b2>...b5 14 | c1>c2>...c5 15 | d1>d2>...d5 16 | e1>e2>...e5 17 | 18 | with one more match, we can get the order of those horses ranking first in the match, we assume that 19 | a1>b1>c1>d1>e1 20 | then a1 is the fastest, the candidates for second and third fastest are: 21 | a2,a3,b1,b2,c1 22 | We can get the second and third fastest by one match 23 | so, 5+1+1 = 7 -------------------------------------------------------------------------------- /Company/src/amazon/BitAddOperation.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | public class BitAddOperation { 4 | 5 | /** 6 | * Implement addition without using '+' operators 7 | */ 8 | 9 | // a^b add each bit without carry, (a&b<<1) is the carry (has been shifted) 10 | // e.g. a=010, b=011, a^b = 001, a&b = 010 11 | public static int bitAdd1(int a, int b) { 12 | return b == 0 ? a : bitAdd1(a ^ b, (a & b) << 1); 13 | } 14 | 15 | public static int bitAdd2(int a, int b) { 16 | int res = 0; 17 | while (b != 0) { // until there's no carry 18 | res = a ^ b; 19 | b = ((a & b) << 1); 20 | a = res; 21 | } 22 | return res; 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println(bitAdd1(-8, 10)); 27 | System.out.println(bitAdd2(-8, 10)); 28 | System.out.println(bitAdd2(-8, 1)); 29 | System.out.println(bitAdd2(0, 1)); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Company/src/amazon/BitMinusOperation.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | public class BitMinusOperation { 4 | 5 | /** 6 | * Implement minus without using '-' operators 7 | */ 8 | public static void main(String[] args) { 9 | 10 | System.out.println(bitMinus(10, -8)); 11 | } 12 | 13 | public static int bitMinus(int a, int b){ 14 | return bitAdd(a, negative(b)); 15 | } 16 | 17 | // Get arithmetic negative number 18 | // The two's complement operation is the additive inverse operation 19 | public static int negative(int num){ 20 | return bitAdd(~num, 1); 21 | } 22 | 23 | public static int bitAdd(int a, int b){ 24 | return b==0? a : bitAdd(a^b, (a&b)<<1); // (a&b)<<1 is the carry 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Company/src/amazon/CountBitOne.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | public class CountBitOne { 4 | 5 | /** 6 | * Count the number of bit 1 in binary expression of given integer 7 | */ 8 | public static void main(String[] args) { 9 | int num = 2^32-1; 10 | System.out.println(Integer.bitCount(num)); 11 | System.out.println(countOne(num)); 12 | } 13 | 14 | public static int countOne(int num){ 15 | int count = 0; 16 | while (num != 0){ 17 | count += (num&1)>0? 1 : 0; 18 | num = (num>>1); 19 | } 20 | return count; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Company/src/amazon/CreateMirrorTree.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import lib.TreeNode; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class CreateMirrorTree { 9 | 10 | /** 11 | * Create the mirror tree of the original tree 12 | */ 13 | 14 | // swap the left and child node in place 15 | // time: O(n); space: O(1) 16 | public void mirror1(TreeNode node){ 17 | if(node == null) return; 18 | mirror1(node.left); 19 | mirror1(node.right); 20 | TreeNode tmp = node.left; node.left = node.right; node.right = tmp; 21 | } 22 | 23 | // create a new tree 24 | // input the original node and return the mirrored node 25 | // time: O(n); space: (n) 26 | public static TreeNode mirror2(TreeNode node){ 27 | if (node == null) return null; 28 | TreeNode copy = new TreeNode(node.val); 29 | copy.left = mirror2(node.right); 30 | copy.right = mirror2(node.left); 31 | return copy; 32 | } 33 | 34 | @Test 35 | public void test() { 36 | TreeNode root = new TreeNode(new int[]{1,2,3,4,5}); 37 | System.out.println(root.printTree()); 38 | mirror1(root); 39 | System.out.println(root.printTree()); 40 | System.out.println(mirror2(root).printTree()); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Company/src/amazon/CubeRoot.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import org.junit.Test; 4 | 5 | public class CubeRoot { 6 | 7 | /********************************************************/ 8 | /* */ 9 | /* This program computes the cube root of a float */ 10 | /* number using Newton's method of successive */ 11 | /* approximations. The acceptable tolerance is computed */ 12 | /* as a percentage of the correct answer. */ 13 | /* */ 14 | /********************************************************/ 15 | 16 | // http://www.cise.ufl.edu/~ddd/cis3020/summer-97/hw-7-sol.htm 17 | 18 | 19 | // Similar to Leetcode/sqrt, the difference lies in that we have to 20 | // note the case of negative float 21 | public float getCubeRoot(float x) { 22 | return x < 0 ? -cubeRoot(1, -x) : cubeRoot(1, x); 23 | } 24 | 25 | private float cubeRoot(float guess, float x) { 26 | while (true){ 27 | guess = (x / square(guess) + guess) / 2; 28 | if (Math.abs(cube(guess) - x) / x < 0.00001) 29 | break; 30 | } 31 | return guess; 32 | } 33 | 34 | private float cube(float x) { 35 | return x * x * x; 36 | } 37 | 38 | private float square(float x) { 39 | return x * x; 40 | } 41 | 42 | @Test 43 | public void test() { 44 | System.out.println(getCubeRoot(0.3f)); 45 | System.out.println(getCubeRoot(-9.3f)); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Company/src/amazon/DeserializePreorderArrayOfBST.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import lib.TreeNode; 4 | 5 | public class DeserializePreorderArrayOfBST { 6 | 7 | /** 8 | * A BST has been serizliazed as an array, using pre-order traversal. 9 | * Now recover the BST from the array 10 | * 11 | * Sol1: time O(n), same as preorder traversal 12 | * <1> do preorder traversal, insert the node to position where min refer to Leetcode -- constructBinaryTreeFromInorderAndPreorderTraversal 15 | */ 16 | public static void main(String[] args) { 17 | System.out.println(deserializatoinOfBST1(new int[]{30, 20, 10, 40, 35, 50}).printTree()); 18 | } 19 | 20 | private static int index = 0; 21 | public static TreeNode deserializatoinOfBST1(int[] A){ 22 | if (A==null || A.length==0) return null; 23 | return recover(Integer.MIN_VALUE, Integer.MAX_VALUE, A); 24 | } 25 | public static TreeNode recover(int min, int max, int[] A){ 26 | TreeNode node = null; 27 | int val = A[index]; 28 | if (val>min && val> findConsecutiveRange(int[] arr){ 21 | ArrayList> res = new ArrayList>(); 22 | if (arr==null || arr.length==0) return res; 23 | Set set = new HashSet(); 24 | for (int num : arr) set.add(num); 25 | while (!set.isEmpty()){ 26 | int mid = set.iterator().next(); 27 | set.remove(mid); 28 | int start=mid, end=mid; 29 | while (!set.isEmpty() && set.contains(start-1)) set.remove(--start); 30 | while (!set.isEmpty() && set.contains(end+1)) set.remove(++end); 31 | if (end-start+1 >= 2){ 32 | ArrayList range = new ArrayList(); 33 | range.add(start); range.add(end); 34 | res.add(range); 35 | } 36 | } 37 | return res; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Company/src/amazon/FindTwoMissingIntegers.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import java.util.Arrays; 4 | 5 | public class FindTwoMissingIntegers { 6 | 7 | /** 8 | * An array of integers from [1...n], there're two integers missing, find the missing integers 9 | */ 10 | public static void main(String[] args) { 11 | int n = 9; 12 | int[] num = new int[] { 1, 2, 3, 4, 5, 6, 9 }; 13 | System.out.println(Arrays.toString(findTwoMissingIntegers(num, n))); 14 | } 15 | 16 | // solve the formulas: 17 | // <1> x+y = a 18 | // <2> x*y = b 19 | // x*x - a*x + b = 0 20 | public static int[] findTwoMissingIntegers(int[] num, int n) { 21 | int[] res = new int[2]; 22 | int a = 0, b = 1; 23 | for (int i = 1; i <= n; i++) { 24 | a += i; 25 | b *= i; 26 | } 27 | for (int i = 0; i < num.length; i++) { 28 | a -= num[i]; 29 | b /= num[i]; 30 | } 31 | solveQuadraticEquation(res, 1, -a, b); 32 | return res; 33 | } 34 | 35 | public static void solveQuadraticEquation(int[] res, int a, int b, int c) { 36 | res[0] = (int) (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); 37 | res[1] = (int) (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); 38 | Arrays.sort(res); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Company/src/amazon/IsMirrorTree.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import lib.TreeNode; 4 | 5 | public class IsMirrorTree { 6 | 7 | /** 8 | * Check whether two input trees are mirror to each other 9 | */ 10 | public static void main(String[] args) { 11 | TreeNode a = new TreeNode(new int[]{2,3,1}); 12 | TreeNode b = CreateMirrorTree.mirror2(a); 13 | System.out.println(a.printTree()); 14 | System.out.println(b.printTree()); 15 | System.out.println(isMirrorTree(a,b)); 16 | } 17 | 18 | public static boolean isMirrorTree(TreeNode a, TreeNode b){ 19 | if (a==null || b==null) return a==null && b==null; 20 | if (a.val != b.val) return false; 21 | return isMirrorTree(a.left, b.right) && isMirrorTree(a.right, b.left); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Company/src/amazon/IsSumTree.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import lib.TreeNode; 4 | 5 | public class IsSumTree { 6 | 7 | /** 8 | * A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present in 9 | * its left subtree and right subtree. An empty tree is SumTree and sum of an empty tree can be 10 | * considered as 0. A leaf node is also considered as SumTree. 11 | * 12 | * Following is an example of SumTree. 13 | * 14 | * 26 15 | * / \ 16 | * 10 3 17 | * / \ \ 18 | * 4 6 3 19 | */ 20 | public static void main(String[] args) { 21 | TreeNode root = new TreeNode(new int[] { 4, 10, 6, 26, 3, 3 }, new int[] { 26, 10, 4, 6, 3, 3 }); 22 | System.out.println(root.printTree()); 23 | System.out.println(isSumTree(root)); 24 | } 25 | 26 | public static boolean isSumTree(TreeNode root) { 27 | return getSum(root) != -1; 28 | } 29 | 30 | public static int getSum(TreeNode node) { 31 | if (node == null) 32 | return 0; 33 | if (node.left==null && node.right==null) return node.val; 34 | int lsum = getSum(node.left), rsum = getSum(node.right); 35 | if (lsum == -1 || rsum == -1 || node.val != lsum + rsum) 36 | return -1; 37 | return node.val + lsum + rsum; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Company/src/amazon/MinimumCoinChange.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import org.junit.Test; 4 | 5 | public class MinimumCoinChange { 6 | 7 | /** 8 | * Find the minimum number of coins needed to make change 9 | * if there's no way to make change, return Integer.MAX_VALUE 10 | */ 11 | 12 | /* Think why this dp works here, but not in CoinChange problem */ 13 | 14 | // 2d DP, for each value, we find the minimum number of coins from all the possible combinations 15 | // time: O(m*n); space: O(m) 16 | public int minimumCoinChange(int[] A, int target) { 17 | if (A == null || A.length == 0) 18 | return 0; 19 | int[] dp = new int[target + 1]; 20 | for (int i = 1; i <= target; i++) { 21 | int min = Integer.MAX_VALUE; 22 | for (int j = 0; j < A.length; j++) { 23 | if (i >= A[j]) 24 | min = Math.min(min, dp[i - A[j]]); 25 | } 26 | dp[i] = min == Integer.MAX_VALUE ? min : min + 1; // notice overflow here 27 | } 28 | return dp[target]; 29 | } 30 | 31 | @Test 32 | public void test() { 33 | int[] A = new int[] { 2, 3, 5 }; 34 | int target = 1; 35 | System.out.println(minimumCoinChange(A, target)); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Company/src/amazon/RandomNumber.java: -------------------------------------------------------------------------------- 1 | package amazon; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | import org.junit.Test; 7 | 8 | public class RandomNumber { 9 | 10 | /** 11 | * rand7 from rand5 12 | * rand5 from rand7: if 6,7, redo 13 | * rand28 from rand5: get rand8 first, then use rand8 to construct the matrix 14 | */ 15 | 16 | private Random r = new Random(System.currentTimeMillis()); 17 | 18 | public int rand5() { 19 | return r.nextInt(5) + 1; 20 | } 21 | 22 | public int rand7() { 23 | int[][] matrix = new int[][] { { 1, 2, 3, 4, 5 }, { 6, 7, 1, 2, 3 }, { 4, 5, 6, 7, 1 }, 24 | { 2, 3, 4, 5, 6 }, { 7, 0, 0, 0, 0 } }; 25 | int res = 0; 26 | while (res == 0) { 27 | int i = rand5(), j = rand5(); 28 | res = matrix[i - 1][j - 1]; 29 | } 30 | return res; 31 | } 32 | 33 | public int rand7_2() { 34 | int rowNum = rand5(), colNum = rand5(); 35 | int val = (rowNum-1) * 5 + colNum; 36 | if (val >= 22 && val <= 25) 37 | return rand7_2(); 38 | return val % 7 +1; 39 | } 40 | 41 | @Test 42 | public void test() { 43 | int[] counts1 = new int[8]; 44 | int[] counts2 = new int[8]; 45 | for (int i = 0; i < 10000; i++) { 46 | counts1[rand7()]++; 47 | counts2[rand7_2()]++; 48 | } 49 | System.out.println(Arrays.toString(counts1)); 50 | System.out.println(Arrays.toString(counts2)); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Company/src/amazon/ReservoirSampleing.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/amazon/ReservoirSampleing.java -------------------------------------------------------------------------------- /Company/src/amazon/others/Concept_GraphSearch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/amazon/others/Concept_GraphSearch -------------------------------------------------------------------------------- /Company/src/amazon/others/Concept_HashTable: -------------------------------------------------------------------------------- 1 | 1. Explain how to solve the collisions in a hash table. 2 | Collision happens when two value has the same key, although they have different hash codes. 3 | Collision is solved by using a LinkedList to store the values with the same key 4 | 5 | 2. Time complexity of put a pair into the map. Best? Worst? Average? 6 | Best: 7 | O(1). use hash code to find the bucket index 8 | Worst: 9 | the 'put' triggers the resize of the hash table. In this case, a new bucket table 10 | is created. It doubles the size of the original table and need to copy all data of the original 11 | table, hence O(n) 12 | Average: 13 | O(1). Good hash table design improves the performance by choosing proper 14 | initial capacity and load factor. Initial capacity is the initial length of the table bucket, 15 | load factor decides when to resize the table bucket. Higher value of load factor decreases 16 | -------------------------------------------------------------------------------- /Company/src/amazon/others/Shell_GrepIPAddress: -------------------------------------------------------------------------------- 1 | Q: 2 | Write Linux commands to find all the IP address in the current directory 3 | 4 | 192.168.1.1 5 | 6 | 7 | A: 8 | range: 0-255 9 | some special cases: 10 | 03.1.1.1 11 | 12 | grep -r '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$' . -------------------------------------------------------------------------------- /Company/src/amazon/others/Shell_GrepPhoneNumber: -------------------------------------------------------------------------------- 1 | Q: 2 | Write Linux commands to find all the phone numbers in the current directory 3 | 4 | A: 5 | depends on the format of the phone number 6 | we use (000)000-0000 as example 7 | 8 | grep -r '^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$' . 9 | 10 | To search a single file 'foo' 11 | grep -r '^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$' 'foo' 12 | 13 | To search all the files on the computer 14 | grep -r '^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$' / 15 | -------------------------------------------------------------------------------- /Company/src/facebook/ArrayProduct.java: -------------------------------------------------------------------------------- 1 | package facebook; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | public class ArrayProduct { 8 | 9 | /** 10 | * input [2,3,1,4] 11 | * output [12,8,24,6] 12 | * Multiply all fields except it's own position. 13 | * Restrictions: 14 | * 1. no use of division 15 | * 2. complexity in O(n) 16 | */ 17 | 18 | // Two pass of the array to store the left and right product to current element 19 | // time: O(n); space: O(n) 20 | public int[] getProducts(int[] A) { 21 | if (A == null || A.length == 0) 22 | return null; 23 | int N = A.length; 24 | int[] P = new int[N]; 25 | P[0] = A[0]; 26 | for (int i = 1; i < N; i++) 27 | P[i] = P[i - 1] * A[i]; 28 | int rP = 1; 29 | for (int i = N - 1; i > 0; i--) { 30 | P[i] = rP * P[i - 1]; 31 | rP = A[i] * rP; 32 | } 33 | P[0] = rP; 34 | return P; 35 | } 36 | 37 | @Test 38 | public void test() { 39 | int[] A = new int[] { 2, 3, 1, 4 }; 40 | System.out.println(Arrays.toString(getProducts(A))); 41 | } 42 | } -------------------------------------------------------------------------------- /Company/src/facebook/Balances_testcases/input000.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 3 3 | 0 5 4 | 0 5 | 0 6 | 0 7 | 0 8 | 0 9 | 1 4 10 | 7 11 | 0 12 | 0 2 3 13 | 6 1 14 | -------------------------------------------------------------------------------- /Company/src/facebook/Balances_testcases/input001.txt: -------------------------------------------------------------------------------- 1 | 22 2 | 0 1 2 3 | 2 3 4 5 4 | 0 11 9 5 | 0 10 6 | 0 7 | 0 8 | 0 6 9 | 0 7 10 | 0 11 | 0 13 14 15 12 | 0 13 | 0 14 | 0 19 15 | 0 16 | 0 17 | 0 8 18 | 0 19 | 1 20 | 0 21 | 0 22 | 0 23 | 0 24 | 0 12 25 | 7 26 | 0 27 | 0 28 | 0 29 | 0 30 | 0 31 | 0 32 | 0 16 33 | 0 17 34 | 0 35 | 0 36 | 0 18 37 | 11 38 | 0 39 | 0 40 | 0 41 | 0 42 | 3 21 43 | 5 44 | 1 45 | 2 46 | -------------------------------------------------------------------------------- /Company/src/facebook/Balances_testcases/output000.txt: -------------------------------------------------------------------------------- 1 | 0: 147 0 2 | 1: 0 0 3 | 2: 0 0 4 | 3: 25 0 5 | 4: 0 7 6 | 5: 0 54 7 | -------------------------------------------------------------------------------- /Company/src/facebook/Balances_testcases/output001.txt: -------------------------------------------------------------------------------- 1 | 0: 188 0 2 | 1: 0 30 3 | 2: 0 0 4 | 3: 4 0 5 | 4: 94 0 6 | 5: 0 0 7 | 6: 0 10 8 | 7: 12 0 9 | 8: 1 0 10 | 9: 0 0 11 | 10: 0 0 12 | 11: 0 3 13 | 12: 0 0 14 | 13: 0 0 15 | 14: 0 0 16 | 15: 22 0 17 | 16: 0 0 18 | 17: 1 0 19 | 18: 0 0 20 | 19: 0 0 21 | 20: 0 12 22 | 21: 1 0 23 | -------------------------------------------------------------------------------- /Company/src/facebook/Bar_testcases/input000.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 3 3 3 | 3 2 5 3 4 | 3 8 1 6 5 | 3 7 4 9 6 | 20 11 7 | 1 3 8 | 1 2 9 | 11 1 4 55 6 80 8 9 19 11 12 13 10 | 15 14 177 16 17 18 10 20 21 22 37 24 25 26 27 28 11 | 7 190 30 31 32 33 34 35 12 | 12 81 23 195 39 40 41 42 43 49 45 46 47 13 | 15 48 44 50 51 52 53 54 5 121 57 58 59 98 61 62 14 | 3 63 64 65 15 | 10 66 67 68 69 70 71 72 73 74 75 16 | 4 76 91 29 79 17 | 11 7 36 82 83 84 85 86 96 88 89 90 18 | 17 77 92 93 172 95 87 97 60 99 100 101 102 103 135 186 106 107 19 | 10 108 109 110 111 112 113 114 115 116 117 20 | 1 118 21 | 8 119 120 56 122 123 124 125 126 22 | 9 127 128 129 130 131 132 133 134 104 23 | 11 136 137 138 139 140 141 142 143 144 145 146 24 | 20 147 148 149 150 151 152 153 154 159 156 157 158 155 180 161 162 163 164 165 166 25 | 18 167 168 169 170 171 94 173 174 175 176 15 178 179 160 181 182 183 184 26 | 17 185 105 187 188 189 78 191 192 193 194 38 196 197 198 199 200 201 -------------------------------------------------------------------------------- /Company/src/facebook/Bar_testcases/output000.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 89 -------------------------------------------------------------------------------- /Company/src/facebook/CelebrityProblem.java: -------------------------------------------------------------------------------- 1 | package facebook; 2 | 3 | public class CelebrityProblem { 4 | 5 | /** 6 | * In a party of N people, only one person is known to everyone. Such a person may be present in 7 | * the party, if yes, (s)he doesn't know anyone in the party. We can only ask questions like 8 | * does A know B? Find the stranger (celebrity) in minimum number of questions. 9 | */ 10 | 11 | // http://www.geeksforgeeks.org/the-celebrity-problem/ 12 | // This problem has various versions 13 | // [1] Given a set obejcts, and a method compareTo(), find the largest object in the set, if not exist 14 | // return null 15 | // [2] In a network of persons, there's a relationship between any two persons (A, B), that is 16 | // A likes B, or B likes A. Find the person that is loved by all the people 17 | 18 | // All the versions cen be converted to version[1]. 19 | // Basic idea is to traverse the array two times 20 | // [1] find the max value M in the array 21 | // [2] find if M is larger than all other values. This step is necessary as there may be two largest 22 | // max values, in this case, we return null. 23 | } 24 | -------------------------------------------------------------------------------- /Company/src/facebook/ConvertExcelColumnNumber.java: -------------------------------------------------------------------------------- 1 | package facebook; 2 | 3 | import org.junit.Test; 4 | 5 | public class ConvertExcelColumnNumber { 6 | 7 | /** 8 | * Microsoft Excel numbers cells as A...Z and after that AA, AB.... AAA, AAB...ZZZ and so on. 9 | * Given a number, convert it to that format and vice versa. 10 | */ 11 | 12 | // Basically, is convert base10 to base26. 13 | // The challenge is that not zero-indexed, the first number starts from 1 14 | // So, we have 1-A, 26-Z, 27-AA 15 | public String intToStr(int N) { 16 | if (N <= 0) 17 | throw new IllegalArgumentException("N should be a positive integer"); 18 | StringBuilder sb = new StringBuilder(); 19 | while (N > 0) { 20 | N--; 21 | int r = N % 26; 22 | char ch = (char) (r + 'A'); 23 | sb.append(ch); 24 | N = N / 26; 25 | } 26 | return sb.reverse().toString(); 27 | } 28 | 29 | public int strToInt(String s) { 30 | int num = 0; 31 | for (int i = 0; i < s.length(); i++) { 32 | num = num * 26 + (s.charAt(i) - 'A' + 1); 33 | } 34 | return num; 35 | } 36 | 37 | @Test 38 | public void test() { 39 | for (int i = 1; i < 1000; i++) { 40 | System.out.println(intToStr(i) + " : " + strToInt(intToStr(i))); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Company/src/facebook/FindSquaresInPlainOfPoints.java: -------------------------------------------------------------------------------- 1 | package facebook; 2 | 3 | public class FindSquaresInPlainOfPoints { 4 | 5 | /** 6 | * Given a plain of points, find all the squares in the plain 7 | */ 8 | 9 | // [1] find all point pairs (i,j), this will take O(n^2) 10 | // [2] store distance(i,j) into a map, distance as key, list of point pairs as value 11 | // [3] traverse the map's keyset, for each key, find if there exist a square in the list of pairs 12 | // [4] Need to avoid duplicate results 13 | } 14 | -------------------------------------------------------------------------------- /Company/src/facebook/ImplementLog2.java: -------------------------------------------------------------------------------- 1 | package facebook; 2 | 3 | import org.junit.Test; 4 | 5 | public class ImplementLog2 { 6 | 7 | /** 8 | * Implement log2(x), using sqrt(x) 9 | */ 10 | 11 | final static double epsilon = 0.0001; 12 | 13 | // Basically, binary search 14 | // Use the formula: if 2^x = y, 2^(x/2) = sqrt(y). 15 | // time: O(lgn); space: O(1) 16 | public double log2(int x) { 17 | int a = 0, b = 1; 18 | while (b <= x) { 19 | b <<= 1; 20 | a++; 21 | } 22 | double bs = b >> 1, be = b; 23 | double as = a - 1, ae = a; 24 | while (as <= ae) { 25 | double am = as + (ae - as) / 2; 26 | double bm = Math.sqrt(bs * be); 27 | if (Math.abs(bm - x) < epsilon) 28 | return am; 29 | else if (bm < x) { 30 | as = am + epsilon; 31 | bs = bm + epsilon; 32 | } else { 33 | ae = am - epsilon; 34 | be = bm - epsilon; 35 | } 36 | } 37 | return ae; 38 | } 39 | 40 | @Test 41 | public void test() { 42 | for (int i = 1; i < 10; i++) { 43 | System.out.println(i + ": " + log2(i) + "; " + Math.log(i) / Math.log(2)); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Company/src/facebook/ImplementReadKCharacters.java: -------------------------------------------------------------------------------- 1 | package facebook; 2 | 3 | public class ImplementReadKCharacters { 4 | 5 | /** 6 | * Given a function, read2014(), implement a method to read k characters 7 | */ 8 | // Similar to ImplementReadLine 9 | 10 | public String read2014(){ 11 | return null; 12 | } 13 | 14 | static StringBuilder buffer; 15 | public String read(int k){ 16 | if (buffer.length()==0){ 17 | buffer.append(read2014()); 18 | if (buffer.length()==0) 19 | return ""; 20 | } 21 | StringBuilder res = new StringBuilder(); 22 | if (k max; [3] min max) 26 | return trim(root.left, min, max); 27 | root.left = trim(root.left, min, max); 28 | root.right = trim(root.right, min, max); 29 | return root; 30 | } 31 | 32 | @Test 33 | public void test(){ 34 | int[] A = new int[]{1,2,3,4,5,6,7,8,9}; 35 | TreeNode root = new TreeNode(A); 36 | System.out.println(root.printTree()); 37 | System.out.println(trim(root, 3, 8).printTree()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Company/src/facebook/test12.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/facebook/test12.txt -------------------------------------------------------------------------------- /Company/src/facebook/test21.txt: -------------------------------------------------------------------------------- 1 | abcdefghijklmnopqrstuvwxyz123456ABCDEFGHIJKLMNOPQRSTUVWXYZ -------------------------------------------------------------------------------- /Company/src/facebook/test22.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/facebook/test22.txt -------------------------------------------------------------------------------- /Company/src/facebook/test23.txt: -------------------------------------------------------------------------------- 1 | abcdefghijklmnopqrstuvwxyz123456ABCDEFGHIJKLMNOPQRSTUVWXYZ -------------------------------------------------------------------------------- /Company/src/facebook/test32.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/facebook/test32.txt -------------------------------------------------------------------------------- /Company/src/facebook/test42.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/facebook/test42.txt -------------------------------------------------------------------------------- /Company/src/google/ArrayPartitionSum.java: -------------------------------------------------------------------------------- 1 | package google; 2 | 3 | import org.junit.Test; 4 | 5 | public class ArrayPartitionSum { 6 | /* 7 | * Given an array of integers and a target 8 | * Check whether there's a way to partition the array into several parts, whose sum is target 9 | * eg, A = [1,5,0,6], target = 21; 10 | * return true, (because 15 + 0 + 6 = 21) 11 | */ 12 | 13 | // Backtracking 14 | // time: O(2^n); space: recursive stack 15 | public boolean isValid(int[] A, int target){ 16 | if (A==null || A.length==0) 17 | return false; 18 | return dfs(A, 0, target); 19 | } 20 | 21 | private boolean dfs(int[] A, int dep, int target){ 22 | if (target==0) 23 | return true; 24 | if (target<0) 25 | return false; 26 | boolean isValid = false; 27 | for (int i=dep; i children; 22 | Person father; 23 | Person mother; 24 | 25 | public Person(String name) { 26 | this.name = name; 27 | } 28 | 29 | public ArrayList getParents(){ 30 | ArrayList parents = new ArrayList(); 31 | parents.add(father); 32 | parents.add(mother); 33 | return parents; 34 | } 35 | 36 | // Use BFS to search all parents of this's ancestors and store them 37 | // in a set. Then BFS search all parents of other's ancestors, once we find 38 | // that the two share common ancestor, they're blood related 39 | public boolean isBloodRelative(Person other){ 40 | return false; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Company/src/google/JavaPassByValue.java: -------------------------------------------------------------------------------- 1 | package google; 2 | 3 | import lib.TreeNode; 4 | 5 | import org.junit.Test; 6 | 7 | public class JavaPassByValue { 8 | /* 9 | * This is a test to show that Java manipulates objects 'by reference,' but it passes object 10 | * references to methods 'by value. 11 | */ 12 | 13 | @Test 14 | public void testManipulateObjectByReference() { 15 | TreeNode root = new TreeNode(0); 16 | root.left = new TreeNode(1); 17 | root.right = new TreeNode(2); 18 | setLeftChildToNull(root); 19 | System.out.println(root.left); 20 | } 21 | 22 | private void setLeftChildToNull(TreeNode root) { 23 | root.left = null; 24 | } 25 | 26 | @Test 27 | public void testPassReferenceByValue(){ 28 | TreeNode root = new TreeNode(0); 29 | root.left = new TreeNode(1); 30 | root.right = new TreeNode(2); 31 | changeRefernce(root); 32 | System.out.println(root); // if pass by reference, should return 1, otherwise, return 0 33 | } 34 | 35 | private void changeRefernce(TreeNode root){ 36 | root = root.left; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Company/src/google/KthElementInBST.java: -------------------------------------------------------------------------------- 1 | package google; 2 | 3 | import java.util.Stack; 4 | 5 | import lib.TreeNode; 6 | 7 | import org.junit.Test; 8 | 9 | public class KthElementInBST { 10 | 11 | /** 12 | * Find the kth smallest element (in order) in a binary search tree 13 | */ 14 | 15 | // iterative in-order traversal, and use a variable to count the order 16 | public int findKthElementInBST(TreeNode root, int k) { 17 | if (root == null) 18 | return Integer.MIN_VALUE; 19 | Stack st = new Stack(); 20 | TreeNode curr = root; 21 | while (curr != null) { 22 | st.push(curr); 23 | curr = curr.left; 24 | } 25 | int count = 0; 26 | while (!st.isEmpty()) { 27 | curr = st.pop(); 28 | count++; 29 | if (count == k) 30 | return curr.val; 31 | curr = curr.right; 32 | while (curr != null) { 33 | st.push(curr); 34 | curr = curr.left; 35 | } 36 | } 37 | return Integer.MIN_VALUE; 38 | } 39 | 40 | // Another solution is to use Order Statistics Tree, which takes O(lgn) to query the 41 | // kth smallest element. See also CTCI/ch11_8_RankNumberInStream 42 | 43 | @Test 44 | public void test() { 45 | TreeNode root = new TreeNode(new int[] { 4, 8, 10, 12, 14, 20, 22 }, new int[] { 20, 8, 4, 46 | 12, 10, 14, 22 }); 47 | System.out.println(root.printTree()); 48 | System.out.println(findKthElementInBST(root, 5)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Company/src/google/MatrixDiagonalSum.java: -------------------------------------------------------------------------------- 1 | package google; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | public class MatrixDiagonalSum { 8 | /* 9 | * Given a matrix, return an array of diagonal(top-left -> bottom-right) sums 10 | * eg, M = { 11 | * {1,2,3}, 12 | * {4,5,6}, 13 | * {7,8,9} 14 | * } 15 | * return [7,12,15,8,3] 16 | */ 17 | 18 | // Left shift the ith row by i steps, and then add each column 19 | // We have a total of (numRow+numColumn-1) diagonals 20 | // Traverse each element in the matrix and add the element to corresponding diagonal sum 21 | // time: O(m*n) 22 | public int[] getSums(int[][] matrix){ 23 | int M = matrix.length, N = matrix[0].length; 24 | int[] res = new int[M+N-1]; 25 | for (int i=0; i=1; j--){ 24 | dp[i] = Math.min(dp[i], dp[i-j*j] + 1); 25 | } 26 | } 27 | return dp[N]; 28 | } 29 | 30 | @Test 31 | public void test(){ 32 | for (int i=0; i<=14; i++) 33 | System.out.println(i +": " + getMinNumber(i)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Company/src/google/NumberOfValidParenthesis.java: -------------------------------------------------------------------------------- 1 | package google; 2 | 3 | public class NumberOfValidParenthesis { 4 | 5 | public int getNumberOfValidParenthesis(int N){ 6 | if (N==0) 7 | return 0; 8 | int[][] dp = new int[2*N+1][2*N+1]; 9 | for (int i=1; i<=N; i++){ 10 | for (int j=1; j<=N; j++){ 11 | if (i-1>=j) 12 | dp[i][j] += dp[i-1][j]; 13 | if (i>=j-1) 14 | dp[i][j] += dp[i][j-1]; 15 | } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Company/src/google/ReverseUTF8.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/google/ReverseUTF8.java -------------------------------------------------------------------------------- /Company/src/google/RunLengthEncoding.java: -------------------------------------------------------------------------------- 1 | package google; 2 | 3 | import org.junit.Test; 4 | 5 | public class RunLengthEncoding { 6 | /* 7 | * Given an input string, write a function that returns the Run Length Encoded string for the 8 | * input string. Assume there's only alphabetic characters in the given string. 9 | */ 10 | 11 | // http://www.geeksforgeeks.org/run-length-encoding/ 12 | 13 | // Maintain a counter 14 | // time: O(n); space: O(1) 15 | public String runLengthEncode(String s){ 16 | if (s==null || s.length()==0) 17 | return s; 18 | StringBuilder sb = new StringBuilder(); 19 | int count = 1, i = 0, N = s.length(); 20 | while (i insert O(lgn) 19 | * <2> adjust O(lgn) -- find previous node or next node 20 | * <3> get median -- O(1) 21 | */ 22 | // this method is difficult implement 23 | // see the CTCI - heard -- GetMedianOfStreamingData 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Company/src/groupon/others/BrainTeaser_25Horses: -------------------------------------------------------------------------------- 1 | Brain Teaser -- 25 horses 2 | 3 | Given 25 horses, find the 3 fastest. 4 | You have no timer and can know the relative order of 5 horses in a match. 5 | What's the minimum number of matches you should have? 6 | 7 | A: 8 | Wrong: heap sort, merge 5 heaps, 5 + 3 = 8 9 | 10 | Correct: 11 | Divide into 5 teams 12 | a1>a2>...a5 13 | b1>b2>...b5 14 | c1>c2>...c5 15 | d1>d2>...d5 16 | e1>e2>...e5 17 | 18 | with one more match, we can get the order of those horses ranking first in the match, we assume that 19 | a1>b1>c1>d1>e1 20 | then a1 is the fastest, the candidates for second and third fastest are: 21 | a2,a3,b1,b2,c1 22 | We can get the second and third fastest by one match 23 | so, 5+1+1 = 7 -------------------------------------------------------------------------------- /Company/src/lib/ArrayGenerator.java: -------------------------------------------------------------------------------- 1 | package lib; 2 | 3 | import java.util.Random; 4 | 5 | public class ArrayGenerator { 6 | private Random random; 7 | public ArrayGenerator(){ 8 | random = new Random(System.currentTimeMillis()); 9 | } 10 | public int[] generateIntArray(int size, int minValue, int maxValue){ 11 | int[] A = new int[size]; 12 | for (int i=0; i 0 14 | DoublyListNode node = buildList(arr); 15 | this.val = node.val; 16 | this.next = node.next; 17 | } 18 | 19 | public static DoublyListNode buildList(int[] arr) { 20 | DoublyListNode head = new DoublyListNode(arr[0]); 21 | DoublyListNode p = head; 22 | for (int i = 1; i < arr.length; i++) { 23 | p.next = new DoublyListNode(arr[i]); 24 | p.next.prev = p; 25 | p = p.next; 26 | } 27 | return head; 28 | } 29 | 30 | public String printList() { 31 | StringBuilder sb = new StringBuilder(); 32 | sb.append(val); 33 | sb.append("-> "); 34 | DoublyListNode p = this.next; 35 | while (p != null) { 36 | sb.append(p.val); 37 | sb.append("-> "); 38 | p = p.next; 39 | } 40 | sb.append("null"); 41 | return sb.toString(); 42 | } 43 | 44 | public String toString() { 45 | return val + ""; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Company/src/lib/HashMapTests.java: -------------------------------------------------------------------------------- 1 | package lib; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class HashMapTests { 8 | 9 | @Test 10 | public void testPutToMap() { 11 | HashMap map = new HashMap(); 12 | map.put(1, 10); 13 | assertTrue(map.containsKey(1)); 14 | assertTrue(map.size()==1); 15 | } 16 | 17 | @Test 18 | public void testResizeHashMap(){ 19 | HashMap map = new HashMap(); 20 | assertTrue(map.capacity()==map.DEFAULT_INITIAL_CAPACITY); 21 | for (int i=0; i<20; i++){ 22 | map.put(i, i+1); 23 | } 24 | assertTrue(map.capacity()==map.DEFAULT_INITIAL_CAPACITY*2); 25 | } 26 | 27 | @Test 28 | public void testGetFromMap(){ 29 | HashMap map = new HashMap(); 30 | map.put(1, 10); 31 | assertTrue(map.get(1)==10); 32 | } 33 | 34 | @Test 35 | public void testRemoveFromMap(){ 36 | HashMap map = new HashMap(); 37 | map.put(1, 10); 38 | assertTrue(map.containsKey(1)); 39 | map.remove(1); 40 | assertTrue(!map.containsKey(1)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Company/src/lib/Interval.java: -------------------------------------------------------------------------------- 1 | package lib; 2 | 3 | public class Interval { 4 | public int start; 5 | public int end; 6 | public int cost; 7 | 8 | public Interval(int start, int end) { 9 | this.start = start; 10 | this.end = end; 11 | cost = 0; 12 | } 13 | 14 | public Interval(int start, int end, int cost) { 15 | this.start = start; 16 | this.end = end; 17 | this.cost = cost; 18 | } 19 | 20 | public String toString() { 21 | return "[" + start + "," + end + "]"; 22 | } 23 | } -------------------------------------------------------------------------------- /Company/src/lib/LineSegment.java: -------------------------------------------------------------------------------- 1 | package lib; 2 | 3 | public class LineSegment { 4 | public Point p1; 5 | public Point p2; 6 | 7 | public LineSegment(Point p1, Point p2) { 8 | this.p1 = p1; 9 | this.p2 = p2; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Company/src/lib/ListNode.java: -------------------------------------------------------------------------------- 1 | package lib; 2 | 3 | public class ListNode { 4 | public int val; 5 | public ListNode next; 6 | 7 | public ListNode(int val){ 8 | this.val = val; 9 | next = null; 10 | } 11 | 12 | public ListNode(int[] arr){ 13 | // assert arr.length > 0 14 | ListNode node = buildList(arr); 15 | this.val = node.val; 16 | this.next = node.next; 17 | } 18 | 19 | public static ListNode buildList(int[] arr){ 20 | ListNode head = new ListNode(arr[0]); 21 | ListNode p = head; 22 | for (int i = 1; i < arr.length; i++){ 23 | p.next = new ListNode(arr[i]); 24 | p = p.next; 25 | } 26 | return head; 27 | } 28 | 29 | public String printList(){ 30 | StringBuilder sb = new StringBuilder(); 31 | sb.append(val); 32 | sb.append("-> "); 33 | ListNode p = this.next; 34 | while (p != null){ 35 | sb.append(p.val); 36 | sb.append("-> "); 37 | p = p.next; 38 | } 39 | sb.append("null"); 40 | return sb.toString(); 41 | } 42 | 43 | public String toString(){ 44 | return val+""; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Company/src/lib/Point.java: -------------------------------------------------------------------------------- 1 | package lib; 2 | 3 | public class Point{ 4 | public int x; 5 | public int y; 6 | public Point(int x, int y){ 7 | this.x = x; 8 | this.y = y; 9 | } 10 | 11 | public String toString(){ 12 | return "("+x+","+y+")"; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Company/src/linkedin/PaintHouse.java: -------------------------------------------------------------------------------- 1 | package linkedin; 2 | 3 | public class PaintHouse { 4 | 5 | /** 6 | * Minimize the cost of painting K houses, each house has different 7 | * costs to paint in different colors, 2 houses (next to each other) 8 | * cannot be painted in the same color 9 | */ 10 | 11 | // costs[0][2] =1, house#0 takes 1 unit to paint color#2 12 | // costs[1][2] =2, house#1 takes 2 unit to paint color#2 13 | // time: O(m * n^2), m is the number of houses, n is the number of colors 14 | public static int paintHouse(int[][] costs) { 15 | int color = costs[0].length, house = costs.length; 16 | int[][] dp = new int[house][color]; 17 | for (int i = 0; i < color; i++) 18 | dp[0][i] = costs[0][i]; 19 | for (int i = 1; i < house; i++) { 20 | for (int j = 0; j < color; j++) { 21 | int min = Integer.MAX_VALUE; 22 | for (int k = 0; k < color; k++) { 23 | if (k == j) 24 | continue; 25 | min = Math.min(min, dp[i - 1][k] + costs[i][j]); 26 | } 27 | dp[i][j] = min; 28 | } 29 | } 30 | int res = Integer.MAX_VALUE; 31 | for (int i = 0; i < color; i++) 32 | res = Math.min(res, dp[house - 1][i]); 33 | return res; 34 | } 35 | 36 | public static void main(String[] args) { 37 | int[][] costs = new int[][] { { 3, 2, 1 }, { 3, 5, 1 }, { 3, 2, 1 } }; 38 | System.out.println(paintHouse(costs)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Company/src/linkedin/RangeQueryInStreamingData.java: -------------------------------------------------------------------------------- 1 | package linkedin; 2 | 3 | public class RangeQueryInStreamingData { 4 | /* 5 | * The input is an endless stream of English words or phrases (we refer them as tokens). 6 | * Two Tasks: 7 | * Output top N tokens we have seen so far (from all the tokens we have seen!) 8 | * Output top N tokens in a historical window, say, last day or last week. 9 | */ 10 | 11 | // kafka + storm, http://stackoverflow.com/questions/3260653/algorithm-to-find-top-10-search-terms 12 | } 13 | -------------------------------------------------------------------------------- /Company/src/linkedin/TrieTest2.java: -------------------------------------------------------------------------------- 1 | package linkedin; 2 | 3 | import lib.Trie; 4 | 5 | public class TrieTest2 { 6 | 7 | /** 8 | * @param args 9 | */ 10 | public static void main(String[] args) { 11 | Trie dict = new Trie(); 12 | dict.add("apple"); 13 | dict.add("google"); 14 | System.out.println(dict.getWords().toString()); 15 | dict.add("good"); 16 | dict.add("goode"); 17 | dict.add("gooda"); 18 | dict.add("banana"); 19 | System.out.println(dict.getWords().toString()); 20 | System.out.println("good: " + dict.contains("good")); 21 | System.out.println("goo: " + dict.contains("goo")); 22 | dict.remove("good"); 23 | System.out.println(dict.getWords().toString()); 24 | System.out.println("gooda: " + dict.contains("gooda")); 25 | dict.remove("gooda"); 26 | dict.remove("googleer"); 27 | System.out.println(dict.getWords().toString()); 28 | System.out.println("gooda: " + dict.contains("gooda")); 29 | System.out.println("goode: " + dict.contains("goode")); 30 | System.out.println("googleer: " + dict.contains("googleer")); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Company/src/microsoft/MirrorImage.java: -------------------------------------------------------------------------------- 1 | package microsoft; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MirrorImage { 6 | 7 | /** 8 | * Given an image represented by byte[][] image, return its mirror image. 9 | * 10 | * Sol: 11 | * should decide the direction of the mirror 12 | */ 13 | public static void main(String[] args) { 14 | byte[][] img = new byte[][] { { 2, 0, 30, 1 }, { 0, 0, 41, 1 }, { 1, 13, 0, 10 }, 15 | { 1, 30, 1, 1 }, }; 16 | printImage(img); 17 | mirrorImage(img, Direction.Vertical); 18 | printImage(img); 19 | } 20 | 21 | enum Direction { 22 | Vertical, Horizontal 23 | } 24 | 25 | public static void mirrorImage(byte[][] img, Direction d) { 26 | if (img == null || img.length == 0 || img[0].length == 0) 27 | return; 28 | int h = img.length, w = img[0].length; 29 | if (d == Direction.Vertical) { 30 | for (int i = 0; i < h; i++) { 31 | int j = 0, k = w - 1; 32 | while (j < k) { 33 | byte tmp = img[i][k]; 34 | img[i][k] = img[i][j]; 35 | img[i][j] = tmp; 36 | j++; 37 | k--; 38 | } 39 | } 40 | } 41 | // Direction.Horizontal 42 | // ... 43 | } 44 | 45 | public static void printImage(byte[][] img) { 46 | if (img == null || img.length == 0 || img[0].length == 0) 47 | return; 48 | for (int i = 0; i < img.length; i++) 49 | System.out.println(Arrays.toString(img[i])); 50 | System.out.println(); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Company/src/microsoft/NextPrimeNumber.java: -------------------------------------------------------------------------------- 1 | package microsoft; 2 | 3 | public class NextPrimeNumber { 4 | 5 | /** 6 | * Given a number, find the nearest prime number that is larger than the number 7 | */ 8 | public static void main(String[] args) { 9 | System.out.println(nextPrime(80)); 10 | } 11 | 12 | public static int nextPrime(int num){ 13 | if (num <=1) return 2; 14 | if (num%2 == 0) num++; 15 | while (true){ 16 | if (isPrime(num)) break; 17 | num +=2; 18 | } 19 | return num; 20 | } 21 | 22 | public static boolean isPrime(int num){ 23 | if (num <=1) return false; 24 | if (num%2 == 0) return false; 25 | // num is odd number 26 | for (int i=3; i*i=1 && num<=9) return 0; 36 | else return random_new(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Company/src/slideshare/BattleshipShoot.java: -------------------------------------------------------------------------------- 1 | package slideshare; 2 | 3 | public class BattleshipShoot { 4 | 5 | /** 6 | * Implement the Shoot method from the Battleship game. The method required to identify if a shot 7 | * was a hit, miss, sunk a battleship or game over! There were two battleships of different 8 | * dimensions on a grid. 9 | * 10 | * Solution depends on input 11 | */ 12 | public static void main(String[] args) { 13 | // TODO Auto-generated method stub 14 | 15 | } 16 | // '~' for water 17 | // '*' for hit 18 | // 'x' for miss 19 | public void shoot(char[][] board, char[][] ships, int x, int y){ 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Company/src/slideshare/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | package slideshare; 2 | 3 | public class FizzBuzz { 4 | 5 | /** 6 | * Write a program that prints the numbers from 1 to 100. 7 | * But for multiples of three print "Fizz" instead of the number 8 | * and for the multiples of five print "Buzz". 9 | * For numbers which are multiples of both three and five print "FizzBuzz". 10 | */ 11 | public static void main(String[] args) { 12 | System.out.println(fizzBuz1()); 13 | System.out.println(fizzBuz2()); 14 | } 15 | 16 | public static String fizzBuz1(){ 17 | StringBuilder sb = new StringBuilder(); 18 | for (int i=1; i<=100; i++){ 19 | if (i%3 == 0) sb.append("Fizz"); 20 | if (i%5 == 0) sb.append("Buzz"); 21 | if (i%3!=0 && i%5!=0) sb.append(i); 22 | sb.append(" "); 23 | } 24 | return sb.toString(); 25 | } 26 | 27 | public static String fizzBuz2(){ 28 | StringBuilder sb = new StringBuilder(); 29 | for (int i=1; i<=100; i++){ 30 | if (i%15 == 0) sb.append("FizzBuzz"); 31 | else if (i%5 == 0) sb.append("Buzz"); 32 | else if (i%3 == 0) sb.append("Fizz"); 33 | else sb.append(i); 34 | sb.append(" "); 35 | } 36 | return sb.toString(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Company/src/square/ThiefProblem.java: -------------------------------------------------------------------------------- 1 | package square; 2 | 3 | public class ThiefProblem { 4 | 5 | /** 6 | * Given s line of houses on the street, each house has a value. The theif wants to 7 | * get the maximum value. Yet, he must obey the following rule, that is: if he steals 8 | */ 9 | public static void main(String[] args) { 10 | System.out.println(thief(new int[]{1,20,3,4,5,6,7})); 11 | } 12 | 13 | public static int thief(int[] rooms){ 14 | if (rooms==null || rooms.length==0) return 0; 15 | int[] dp = new int[rooms.length+1]; 16 | dp[0] = 0; 17 | dp[1] = rooms[0]; 18 | for (int i=2; i<=rooms.length; i++) 19 | dp[i] = Math.max(rooms[i-1] + dp[i-2], dp[i-1]); 20 | return dp[rooms.length]; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Company/src/twitter/CountBinaryTreesConstructedFromPreorderSequence.java: -------------------------------------------------------------------------------- 1 | package twitter; 2 | 3 | public class CountBinaryTreesConstructedFromPreorderSequence { 4 | /* 5 | * Given a preorder sequence from a Binary Tree, how many unique trees can be created from this? 6 | * (They want a recurrence relation and start with the easy cases): 7 | * T(0) = 1 8 | * T(1) = 1 9 | * T(2) = 2 10 | * What is T(N) ? 11 | */ 12 | 13 | // [1,2,3,4,5,6,7,8,9] 14 | // Take the pre-order sequence above as an example. The first element is used as root, then, we 15 | // cut the remaining array into 2 halves. One half is used to build left-subtree, another is used 16 | // to build the right-subtree. For an array of n elements, T(n) = T(1)*T(n-2) + T(2)*T(n-3) + ... 17 | // + T(n-2)*T(1) = Sum(T(i)*T(n-1-i)), i is in [1...n-2] 18 | } 19 | -------------------------------------------------------------------------------- /Company/src/twitter/CountOneInBitExpression.java: -------------------------------------------------------------------------------- 1 | package twitter; 2 | 3 | import org.junit.Test; 4 | 5 | public class CountOneInBitExpression { 6 | /* 7 | * Given a number, tell how many '1's are there in the binary format of this number 8 | */ 9 | 10 | // time: O(lgN), N is the value of input integer 11 | public int countBit2(int N){ 12 | int count = 0; 13 | while (N>0){ 14 | if ((N&1)!=0) 15 | count++; 16 | N >>= 1; 17 | } 18 | return count; 19 | } 20 | 21 | 22 | // optimized version, refer to CTCI- EvaluateExpression 23 | // time: O(k), k is the number of 1s in bit format 24 | public int countBit(int N){ 25 | int count = 0; 26 | while (N>0){ 27 | count++; 28 | N &= N-1; 29 | } 30 | return count; 31 | } 32 | 33 | @Test 34 | public void test(){ 35 | for (int i=0; i<=50; i++){ 36 | System.out.println(i + ": " + Integer.toBinaryString(i) + " " + countBit(i)); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Company/src/twitter/LongestIncreasingSubarray.java: -------------------------------------------------------------------------------- 1 | package twitter; 2 | 3 | import org.junit.Test; 4 | 5 | public class LongestIncreasingSubarray { 6 | 7 | /** 8 | * Find the length of the longest increasing subarray in an array of integers. 9 | * This subarray should be contiguous. 10 | */ 11 | 12 | // traverse the array and update the max length 13 | // time: O(n); space: O(1) 14 | public int findLISContinuous(int[] A) { 15 | if (A == null || A.length == 0) 16 | return 0; 17 | int len = 1, max = Integer.MIN_VALUE; 18 | for (int i = 1; i < A.length; i++) { 19 | if (A[i] > A[i - 1]) { 20 | len++; 21 | max = Math.max(max, len); 22 | } else 23 | len = 0; 24 | } 25 | return max; 26 | } 27 | 28 | @Test 29 | public void test(){ 30 | int[] A = new int[]{ 1, -2, 3, 5, 6, 8 }; 31 | System.out.println(findLISContinuous(A)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Company/src/twitter/MapReduceMedian.java: -------------------------------------------------------------------------------- 1 | package twitter; 2 | 3 | public class MapReduceMedian { 4 | /* 5 | * Given 1000 worker nodes/hosts, 1 coordinator node (4GB RAM) - 10 billion 6 | * numbers are distributed randomly among the worker nodes. 7 | * Find the mean 8 | */ 9 | // <1> map numbers to nodes, 10 | // <2> calculate the average of each node 11 | // <3> reduce the average value to coordinator and calculate the final mean 12 | 13 | // FOLLOWUP 14 | // Find the median 15 | // <1> Assign each node with a range of numbers 16 | // e.g. Node#1 - [0,99], Node#2 - [100, 199] ... 17 | // <2> map each number to the corresponding node 18 | // <3> get the size of numbers on each node, the total size of numbers, and the order of median 19 | // <4> Calculate the node containing the median number 20 | // <5> QuickSelect the median number 21 | } 22 | -------------------------------------------------------------------------------- /Company/src/twitter/OutOfOrderScore.java: -------------------------------------------------------------------------------- 1 | package twitter; 2 | 3 | public class OutOfOrderScore { 4 | /* 5 | * Given an array of values, find the total "score", where the score of each element is defined 6 | * as the number of elements with a smaller value that occur before it in the array. 7 | * e.g. 8 | * values: 4 1 3 2 5 9 | * scores: 0 0 1 1 4 10 | * total score: 6 11 | */ 12 | // This is similar to the CTCI-CountInversionsInArray. The total score is the number of 13 | // inversions in the array, an inversion is described as i= 0) 27 | dp[i] = Math.max(dp[i], dp[i - 2] + A[i]); 28 | if (i - 3 >= 0) 29 | dp[i] = Math.max(dp[i], dp[i - 3] + A[i]); 30 | max = Math.max(max, dp[i]); 31 | } 32 | return max; 33 | } 34 | 35 | @Test 36 | public void test() { 37 | int[] A = new int[] { 1, 3, 5, -1, 12, 6, 7, 11 }; 38 | System.out.println(getMax(new int[] { 1 })); 39 | System.out.println(getMax(new int[] { 1, 2 })); 40 | System.out.println(getMax(new int[] { 1, -4, 2 })); 41 | System.out.println(getMax(new int[] { -4, -5, -3, -9, -4 })); 42 | System.out.println(getMax(A)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Company/src/yahoo/NextPermutation3.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/Company/src/yahoo/NextPermutation3.java -------------------------------------------------------------------------------- /Company/src/yahoo/RangeQueryInStreamingData.java: -------------------------------------------------------------------------------- 1 | package yahoo; 2 | 3 | public class RangeQueryInStreamingData { 4 | /** 5 | * Given continuous data stream , design data structure to return 15 min stock information 6 | */ 7 | 8 | // The basic idea is to use a queue, because we need a FIFO data structure here. The problem lies 9 | // in the implementation we choose. 10 | // LinkedList is an option, yet it doesn't support O(1) random access, which is needed when we 11 | // calculate median of the data. 12 | // Another option is a normal array. We have an array of fixed size, and every time we remove the 13 | // first element in array, left shift all remaining elements and add new element to the end of the 14 | // array, which takes O(n) time. 15 | // The best solution I can think of is to use ArrayDeque, it provides constant time for addFirst(), 16 | // addLast(), removeFirst() and allows O(1) random access. 17 | // The core mechanism of ArrayDeque is Circular Buffer. 18 | // http://www.cs.wcupa.edu/rkline/ds/deque-stack-algorithms.html 19 | } 20 | -------------------------------------------------------------------------------- /Company/src/yahoo/SortStackUsingRecursion.java: -------------------------------------------------------------------------------- 1 | package yahoo; 2 | 3 | import java.util.Random; 4 | import java.util.Stack; 5 | 6 | import org.junit.Test; 7 | 8 | public class SortStackUsingRecursion { 9 | 10 | /** 11 | * Sort a stack suing recursion 12 | */ 13 | 14 | // This question is a variant of reverse a stack using recursion 15 | 16 | public Stack sort(Stack st){ 17 | if (st==null || st.isEmpty()) 18 | return st; 19 | int top = st.pop(); 20 | sort(st); 21 | insert(top, st); 22 | return st; 23 | } 24 | 25 | private void insert(int val, Stack st){ 26 | if (st.isEmpty() || val<=st.peek()){ 27 | st.push(val); 28 | return; 29 | } 30 | int top = st.pop(); 31 | insert(val, st); 32 | st.push(top); 33 | } 34 | 35 | @Test 36 | public void test(){ 37 | Stack st = new Stack(); 38 | Random r = new Random(System.currentTimeMillis()); 39 | for (int i=0; i<10; i++) 40 | st.push(r.nextInt(10)); 41 | System.out.println(st.toString()); 42 | System.out.println(sort(st).toString()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /LeetCode Question Difficulty Distribution.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/walnutown/CodingInTheDeep/9af04298579d9b406abdcbc3adb3410158606941/LeetCode Question Difficulty Distribution.pdf -------------------------------------------------------------------------------- /LeetCode/3SumClosest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array S of n integers, find three integers in S such that the sum is closest 3 | to a given number, target. Return the sum of the three integers. You may assume that 4 | each input would have exactly one solution. 5 | 6 | For example, given array S = {-1 2 1 -4}, and target = 1. 7 | 8 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 9 | */ 10 | 11 | // Similar to 3Sum, the difference lies in that we need to update the closest result all the time 12 | // time: O(n^2); sapce: O(1) 13 | public class Solution { 14 | public int threeSumClosest(int[] num, int target) { 15 | if (num==null || num.length<3) return 0; 16 | int m = num.length; 17 | Arrays.sort(num); // IMPORTANT, remember to sort here 18 | int min = num[0]+num[1]+num[2]; 19 | for (int i=0; i use sorted string as the key of a group of anagrams 8 | // <2> output groups that have at least two strings 9 | // Note: instead of sorted string, we can also use other key in map, such as string compression, aabc -> a2b1c1 10 | // time: O(n*mlgm), n is the number of words, m is the length of word; space: O(n*m) 11 | public class Solution { 12 | public ArrayList anagrams(String[] strs) { 13 | ArrayList res = new ArrayList(); 14 | Map> map = new HashMap>(); 15 | for (String s : strs){ 16 | String key = sort(s); 17 | if (!map.containsKey(key)){ 18 | ArrayList values = new ArrayList(); 19 | map.put(key, values); 20 | } 21 | map.get(key).add(s); 22 | } 23 | for (ArrayList r: map.values()){ 24 | if (r.size()>1) 25 | res.addAll(r); 26 | } 27 | return res; 28 | } 29 | 30 | private String sort(String s){ 31 | char[] ss = s.toCharArray(); 32 | Arrays.sort(ss); 33 | return new String(ss); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LeetCode/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | If you were only permitted to complete at most one transaction 5 | (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. 6 | */ 7 | // time: O(n); space: O(1) 8 | public class Solution { 9 | public int maxProfit(int[] prices) { 10 | if (prices==null || prices.length==0) return 0; 11 | int min = Integer.MAX_VALUE, prof = 0; 12 | for (int i=0; i prices[i-1]) sum += prices[i]-prices[i-1]; 17 | } 18 | return sum; 19 | } 20 | } -------------------------------------------------------------------------------- /LeetCode/BestTimeToBuyAndSellStock3.java: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | Note: 6 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 7 | */ 8 | 9 | // Similar to Leetcode/TrappingRainWater 10 | // sum[i] = left[i] + right[i]. time: O(n); space: O(n) 11 | public class Solution { 12 | public int maxProfit(int[] prices) { 13 | if (prices==null || prices.length==0) return 0; 14 | int m=prices.length; 15 | int[] left = new int[m]; 16 | int[] right = new int[m]; 17 | int lmin=prices[0], rmax=prices[m-1], sum=0; 18 | for (int i=1; i=0; i--){ 23 | right[i] = Math.max(right[i+1], rmax-prices[i]); 24 | rmax = Math.max(rmax, prices[i]); 25 | } 26 | for (int i=0; i> levelOrderBottom(TreeNode root) { 24 | ArrayList> res = new ArrayList>(); 25 | if (root==null) 26 | return res; 27 | ArrayList prev = new ArrayList(); 28 | prev.add(root); 29 | while (!prev.isEmpty()){ 30 | ArrayList curr = new ArrayList(); 31 | ArrayList nums = new ArrayList(); 32 | for (TreeNode node : prev){ 33 | nums.add(node.val); 34 | if (node.left!=null) 35 | curr.add(node.left); 36 | if (node.right!=null) 37 | curr.add(node.right); 38 | } 39 | res.add(nums); 40 | prev = curr; 41 | } 42 | Collections.reverse(res); 43 | return res; 44 | } 45 | } -------------------------------------------------------------------------------- /LeetCode/BinaryTreeMaximumPathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree, find the maximum path sum. 3 | 4 | The path may start and end at any node in the tree. 5 | 6 | For example: 7 | Given the below binary tree, 8 | 9 | 1 10 | / \ 11 | 2 3 12 | 13 | Return 6. 14 | */ 15 | 16 | /** 17 | * Definition for binary tree 18 | * public class TreeNode { 19 | * int val; 20 | * TreeNode left; 21 | * TreeNode right; 22 | * TreeNode(int x) { val = x; } 23 | * } 24 | */ 25 | 26 | // Recursion 27 | // Maintain a global variable to track the max path sum during recursion 28 | // The return value of getMax() is the max sum of path coantaining root node 29 | // time: O(n); space: recursive stack 30 | public class Solution { 31 | int max = Integer.MIN_VALUE; 32 | public int maxPathSum(TreeNode root) { 33 | if (root ==null) return 0; 34 | getMax(root); 35 | return max; 36 | } 37 | 38 | public int getMax(TreeNode root){ 39 | if (root == null) return 0; 40 | int lmax = getMax(root.left); 41 | int rmax = getMax(root.right); 42 | int mmax = Math.max(Math.max(lmax+root.val, rmax+root.val), root.val); 43 | max = Math.max(Math.max(mmax, lmax+rmax+root.val), max); 44 | return mmax; 45 | } 46 | } -------------------------------------------------------------------------------- /LeetCode/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | */ 6 | 7 | // Dynamic Programming, time: O(n); space: O(n) 8 | public class Solution { 9 | public int climbStairs(int n) { 10 | // we use DP here to store the solution to each step 11 | if (n <= 2) 12 | return n; 13 | int[] mem = new int[n+1]; 14 | mem[0] = 0; 15 | mem[1] = 1; 16 | mem[2] = 2; 17 | for (int i = 3; i <= n; i++){ 18 | mem[i] = mem[i-1] + mem[i-2]; 19 | } 20 | return mem[n]; 21 | } 22 | } 23 | 24 | // DP, optimize the space. time: O(n); space: O(1) 25 | public class Solution { 26 | public int climbStairs(int n) { 27 | if (n<=0) 28 | return 0; 29 | if (n<=2) 30 | return n; 31 | int a = 1, b = 2, c = 0; 32 | for (int i=3; i<=n; i++){ 33 | c = a + b; 34 | a = b; 35 | b = c; 36 | } 37 | return c; 38 | } 39 | } -------------------------------------------------------------------------------- /LeetCode/Combinations.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | For example, 5 | If n = 4 and k = 2, a solution is: 6 | 7 | [ 8 | [2,4], 9 | [3,4], 10 | [2,3], 11 | [1,2], 12 | [1,3], 13 | [1,4], 14 | ] 15 | */ 16 | 17 | // points to remember in combination/permutation question 18 | // 1) when to add res to resList 19 | // 2) order of elements in the res, notice requirement for descending or non-descending 20 | // 3) create new arrayList when add res to resList 21 | 22 | // DFS 23 | // time: O(Combination(n,k)), Combination(n,k) = (n!)/(k!*(n-k)! 24 | public class Solution { 25 | public ArrayList> combine(int n, int k) { 26 | ArrayList> res = new ArrayList>(); 27 | finder(n, 0, k, res, new ArrayList()); 28 | return res; 29 | } 30 | 31 | public void finder(int n, int index, int k, ArrayList> res, ArrayList r){ 32 | if (k==0){ 33 | res.add(new ArrayList(r)); 34 | return; 35 | } 36 | for (int i = index+1; i <= n; i++){ 37 | r.add(i); 38 | finder(n, i+1, k-1, res, r); 39 | r.remove(r.size()-1); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /LeetCode/ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). 3 | n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 4 | Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | 6 | Note: You may not slant the container. 7 | */ 8 | 9 | // Maintain two pointers, one for left border, starting from head of array 10 | // another for right border, starting from end of hte array 11 | // Each time, we adjust left or right border to find if there's more water 12 | // time: O(n); space: O(1) 13 | public class Solution { 14 | public int maxArea(int[] height) { 15 | if (height==null || height.length==0) return 0; 16 | int start=0, end=height.length-1, max=0; 17 | while (start < end){ 18 | max = Math.max(max, Math.min(height[start], height[end])*(end-start)); 19 | if (height[start] > height[end]) end--; 20 | else start++; 21 | } 22 | return max; 23 | } 24 | } -------------------------------------------------------------------------------- /LeetCode/ConvertSortedArrayToBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | */ 4 | 5 | /** 6 | * Definition for binary tree 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | // binary search the array to build tree 15 | // time: O(n); sapce: recursive stack 16 | public class Solution { 17 | public TreeNode sortedArrayToBST(int[] num) { 18 | if (num == null || num.length == 0) return null; 19 | return builder(num, 0, num.length-1); 20 | } 21 | 22 | public TreeNode builder(int[] num, int start, int end){ 23 | if (start > end) return null; 24 | int mid = (start + end) >> 1; 25 | TreeNode root = new TreeNode(num[mid]); 26 | root.left = builder(num, start, mid-1); 27 | root.right = builder(num, mid+1, end); 28 | return root; 29 | } 30 | } -------------------------------------------------------------------------------- /LeetCode/CopyListWithRandomPointer.java: -------------------------------------------------------------------------------- 1 | /* 2 | A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. 3 | 4 | Return a deep copy of the list. 5 | */ 6 | 7 | /** 8 | * Definition for singly-linked list with a random pointer. 9 | * class RandomListNode { 10 | * int label; 11 | * RandomListNode next, random; 12 | * RandomListNode(int x) { this.label = x; } 13 | * }; 14 | */ 15 | 16 | // Maintain a map to memoize the nodes that have been copied 17 | // time: O(n); space:O(n) 18 | public class Solution { 19 | public RandomListNode copyRandomList(RandomListNode head) { 20 | if (head ==null) return null; 21 | Map map = new HashMap(); 22 | RandomListNode sen = new RandomListNode(0), p = head, s = sen; 23 | while (p != null){ 24 | if (!map.containsKey(p)) 25 | map.put(p, new RandomListNode(p.label)); 26 | if (p.random!=null && !map.containsKey(p.random)) 27 | map.put(p.random, new RandomListNode(p.random.label)); 28 | s.next = map.get(p); 29 | s = s.next; 30 | s.random = map.get(p.random); 31 | p = p.next; 32 | } 33 | return sen.next; 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode/CountAndSay.java: -------------------------------------------------------------------------------- 1 | /* 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 1, 11, 21, 1211, 111221, ... 4 | 5 | 1 is read off as "one 1" or 11. 6 | 11 is read off as "two 1s" or 21. 7 | 21 is read off as "one 2, then one 1" or 1211. 8 | Given an integer n, generate the nth sequence. 9 | 10 | Note: The sequence of integers will be represented as a string. 11 | */ 12 | 13 | // Maintain a counter. Increment the counter if there's repeating characters, 14 | // otherwise, reset the counter to 1. 15 | // Each time, buuld the current string based on previous string 16 | // time: O(n^2); space: O(n^2) 17 | public class Solution { 18 | public String countAndSay(int n) { 19 | if (n==0) return ""; 20 | StringBuilder prev = new StringBuilder(); 21 | prev.append(1); 22 | while (n>1){ 23 | StringBuilder curr = new StringBuilder(); 24 | int count = 1; 25 | for (int i=0; i 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given an encoded message containing digits, determine the total number of ways to decode it. 9 | 10 | For example, 11 | Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). 12 | 13 | The number of ways decoding "12" is 2. 14 | */ 15 | 16 | // Dynamic Programming 17 | // check whether the single char is between 1-9, or the continuous two chars is betwen 10-26 18 | // time: O(n); space: O(n) 19 | public class Solution { 20 | public int numDecodings(String s) { 21 | if (s==null || s.length()==0) 22 | return 0; 23 | int N = s.length(); 24 | int[] dp = new int[N+1]; 25 | dp[0] = 1; // Note the initialization step here, should be 1, not 0 26 | for (int i=1; i<=N; i++){ 27 | if (s.charAt(i-1)>='1' && s.charAt(i-1)<='9') 28 | dp[i] += dp[i-1]; 29 | if (i>=2 && (s.charAt(i-2)=='1' && s.charAt(i-1)>='0' && s.charAt(i-1)<='9' 30 | || s.charAt(i-2)=='2' && s.charAt(i-1)>='0' && s.charAt(i-1)<='6')) 31 | dp[i] += dp[i-2]; 32 | } 33 | return dp[N]; 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode/DivideTwoIntegers.java: -------------------------------------------------------------------------------- 1 | /* 2 | Divide two integers without using multiplication, division and mod operator. 3 | */ 4 | 5 | // map + bit manipulation 6 | public class Solution { 7 | public int divide(int dividend, int divisor) { 8 | if (dividend == 0 || divisor == 0) return 0; 9 | long d = Math.abs((long)dividend); // avoid overflow, abs(Integer.MIN_VALUE) = Integer.MIN_VALUE 10 | long s = Math.abs((long)divisor); 11 | Map map = new HashMap(); // divisor mapping 12 | int key = 0; 13 | while (s <= d){ 14 | map.put(key++, s); 15 | s = s << 1; 16 | } 17 | int res = 0; 18 | while (--key >= 0 ){ // remember to '--' first 19 | if (d >= map.get(key)){ 20 | d -= map.get(key); 21 | res += 1 << key; 22 | } 23 | } 24 | return (dividend > 0) ^ (divisor > 0) ? -res : res; // ^ is both bitwise and logical XOR in java 25 | } 26 | } 27 | 28 | // See Company/amazon/BitDivision 29 | // time: O(32); space: O(1) 30 | public class Solution { 31 | public int divide(int dividend, int divisor) { 32 | if (dividend==0) return 0; 33 | long a = Math.abs((long)dividend), b = Math.abs((long)divisor); 34 | int res = 0, i=31; 35 | while (i>=0 && a>0){ 36 | if ((a>>i)>=b){ 37 | a -= (b<=0? res: -res; 42 | } 43 | } -------------------------------------------------------------------------------- /LeetCode/EvaluateReversePolishNotation.java: -------------------------------------------------------------------------------- 1 | /* 2 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 3 | 4 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 5 | 6 | Some examples: 7 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 8 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 9 | */ 10 | 11 | // Use a stack 12 | // time: O(n), space: O(n) 13 | public class Solution { 14 | public int evalRPN(String[] tokens) { 15 | if (tokens==null || tokens.length==0) return 0; 16 | Stack st = new Stack(); 17 | for (int i=0; i> 3 +1; 15 | BitSet s = new BitSet(length); 16 | for(int a: A){ 17 | if(a > 0 && a<= length ) 18 | s.set(a); 19 | } 20 | return s.nextClearBit(1); 21 | } 22 | 23 | // Swap each element in array to its right position 24 | // If we cannot find the corresponding element in the position, it's missing. 25 | // time: O(n); space: O(1) 26 | public class Solution { 27 | public int firstMissingPositive(int[] A) { 28 | if (A==null || A.length==0) 29 | return 1; // if empty, return the fisrt positive 1 30 | int N = A.length; 31 | for (int i=0; i=0 && A[i]-1l || r<0 || l<0 12 | // time: O(2^(2n)); 13 | public class Solution { 14 | public ArrayList generateParenthesis(int n) { 15 | ArrayList res = new ArrayList(); 16 | if (n == 0) 17 | return res; 18 | finder(n, n, res, new String()); 19 | return res; 20 | } 21 | 22 | public void finder(int l, int r, ArrayList res, String s){ 23 | if (l <0 || r <0 || r > l) // r>l is also invalid 24 | return; 25 | if (l == 0 && r == 0){ 26 | res.add(s); 27 | return; 28 | } 29 | finder(l-1, r, n, res, s+"("); 30 | finder(l, r-1, n, res, s+")"); 31 | } 32 | } -------------------------------------------------------------------------------- /LeetCode/GrayCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | The gray code is a binary numeral system where two successive values differ in only one bit. 3 | 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 7 | 8 | 00 - 0 9 | 01 - 1 10 | 11 - 3 11 | 10 - 2 12 | Note: 13 | For a given n, a gray code sequence is not uniquely defined. 14 | 15 | For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. 16 | 17 | For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. 18 | */ 19 | 20 | // observe that the sequence is in a vertical mirror, except the highest significant bit 21 | public class Solution { 22 | public ArrayList grayCode(int n) { 23 | ArrayList res = new ArrayList(); 24 | res.add(0); 25 | if (n==0) return res; 26 | for (int i=1; i<=n; i++){ 27 | for (int j=res.size()-1; j>=0; j--){ 28 | res.add(res.get(j) | (1<<(i-1))); 29 | } 30 | } 31 | return res; 32 | } 33 | } -------------------------------------------------------------------------------- /LeetCode/InsertionSortList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Sort a linked list using insertion sort. 3 | */ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { 11 | * val = x; 12 | * next = null; 13 | * } 14 | * } 15 | */ 16 | 17 | // Note to disconnect the node from the list when move its position 18 | // time: O(n^2); space: O(1) 19 | public class Solution { 20 | public ListNode insertionSortList(ListNode head) { 21 | if (head==null || head.next==null) 22 | return head; 23 | ListNode sen = new ListNode(Integer.MIN_VALUE); sen.next = head; 24 | ListNode p = head.next; 25 | head.next = null; // cut the list here to avoid endless loop 26 | while (p!=null){ 27 | ListNode next = p.next; 28 | ListNode s = sen; 29 | while (s.next!=null && s.next.val < p.val) 30 | s = s.next; 31 | p.next = s.next; 32 | s.next = p; 33 | p = next; 34 | } 35 | return sen.next; 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode/JumpGame.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | For example: 9 | A = [2,3,1,1,4], return true. 10 | 11 | A = [3,2,1,0,4], return false. 12 | */ 13 | 14 | // Maintain the max distance we can reach 15 | // Traverse the array and update the max 16 | // Once we find that current distance out of reach, return false 17 | // time: O(n); space: O(1) 18 | public class Solution { 19 | public boolean canJump(int[] A) { 20 | if (A==null || A.length==0) 21 | return true; 22 | int N = A.length, max = 0; 23 | for (int i=0; i prevMax) prevMax = currMax; 39 | currMax = Math.max(currMax, A[i] + i); 40 | if (currMax == i && i!=N-1) return false; // notice here, i!= N-1 41 | } 42 | return true; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /LeetCode/LengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 3 | 4 | If the last word does not exist, return 0. 5 | 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | For example, 9 | Given s = "Hello World", 10 | return 5. 11 | */ 12 | 13 | // Trim trailing whitespace and then count the length 14 | // time: O(n); space: O(1) 15 | public class Solution { 16 | public int lengthOfLastWord(String s) { 17 | if (s==null || s.length()==0) 18 | return 0; 19 | int len = 0, N = s.length(), i = N-1; 20 | while (i>=0 && s.charAt(i)==' ') // trim trailing whitespace 21 | i--; 22 | while (i>=0 && s.charAt(i)!=' '){ 23 | i--; 24 | len++; 25 | } 26 | return len; 27 | } 28 | } -------------------------------------------------------------------------------- /LeetCode/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, determine if it has a cycle in it. 3 | 4 | Follow up: 5 | Can you solve it without using extra space? 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode(int x) { 14 | * val = x; 15 | * next = null; 16 | * } 17 | * } 18 | */ 19 | 20 | // fast/slow pointer, time: O(n); space: O(1) 21 | public class Solution { 22 | public boolean hasCycle(ListNode head) { 23 | if (head==null) return false; 24 | ListNode fast = head, slow = head; 25 | while(fast!=null && fast.next!=null){ 26 | slow = slow.next; 27 | fast = fast.next.next; 28 | if (slow==fast) return true; 29 | } 30 | return false; 31 | } 32 | } -------------------------------------------------------------------------------- /LeetCode/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | */ 4 | 5 | // use the first string as the base, and compare each char with chars in other strings 6 | // Note strings may have different lengths. So, rememebr to check the length of the string 7 | // time: O(m*n), space: O(n). m is the number of strings, n is the length of the longest string 8 | public class Solution { 9 | public String longestCommonPrefix(String[] strs) { 10 | if (strs==null || strs.length==0) return ""; 11 | StringBuilder sb = new StringBuilder(); 12 | for (int i=0; i=strs[j].length() || strs[j].charAt(i)!=ch) // Remember to check string length here 16 | return sb.toString(); 17 | } 18 | sb.append(ch); 19 | } 20 | return sb.toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /LeetCode/MergeIntervals.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | For example, 5 | Given [1,3],[2,6],[8,10],[15,18], 6 | return [1,6],[8,10],[15,18]. 7 | */ 8 | 9 | /** 10 | * Definition for an interval. 11 | * public class Interval { 12 | * int start; 13 | * int end; 14 | * Interval() { start = 0; end = 0; } 15 | * Interval(int s, int e) { start = s; end = e; } 16 | * } 17 | */ 18 | 19 | // Sort all the intervals according start value, and then merge and delete 20 | // time: O(nlgn); space: O(1) -- in place 21 | public class Solution { 22 | public ArrayList merge(ArrayList intervals) { 23 | if (intervals == null || intervals.size() <= 1) 24 | return intervals; 25 | // no need to compare end here 26 | Comparator com = new Comparator(){ 27 | public int compare(Interval in1, Interval in2){ 28 | return in1.start - in2.start; 29 | } 30 | }; 31 | Collections.sort(intervals, com); 32 | int i = 0; 33 | while (i < intervals.size()-1){ 34 | Interval curr = intervals.get(i), next = intervals.get(i+1); 35 | if (curr.end < next.start) 36 | i++; 37 | else { 38 | curr.start = Math.min(curr.start, next.start); 39 | curr.end = Math.max(curr.end, next.end); 40 | intervals.remove(i+1); 41 | } 42 | } 43 | return intervals; 44 | } 45 | } -------------------------------------------------------------------------------- /LeetCode/MergeKSortedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Merge k sorted linked lists and return it as one sorted list. 3 | Analyze and describe its complexity. 4 | */ 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * public class ListNode { 9 | * int val; 10 | * ListNode next; 11 | * ListNode(int x) { 12 | * val = x; 13 | * next = null; 14 | * } 15 | * } 16 | */ 17 | 18 | // heap sort, 19 | // time: O(nlgk), space: O(k) (k is the number of lists, n is the number of nodes) 20 | public class Solution { 21 | public ListNode mergeKLists(ArrayList lists) { 22 | // heap sort, O (nlgk) 23 | if (lists == null || lists.size() == 0) return null; 24 | Comparator com = new Comparator(){ 25 | public int compare(ListNode n1, ListNode n2){ 26 | return n1.val - n2.val; 27 | } 28 | }; 29 | PriorityQueue heap = new PriorityQueue(lists.size(), com); 30 | for (ListNode node : lists){ 31 | if (node != null) heap.add(node); 32 | } 33 | ListNode dum = new ListNode(0); 34 | ListNode r = dum; 35 | while (!heap.isEmpty()){ 36 | ListNode curr = heap.poll(); 37 | if (curr.next != null) heap.add(curr.next); 38 | r.next = curr; 39 | r = r.next; 40 | } 41 | return dum.next; 42 | } 43 | } -------------------------------------------------------------------------------- /LeetCode/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted integer arrays A and B, merge B into A as one sorted array. 3 | 4 | Note: 5 | You may assume that A has enough space to hold additional elements from B. 6 | The number of elements initialized in A and B are m and n respectively. 7 | */ 8 | 9 | // <1> compare sort from the end of array 10 | // <2> copy remaning parts of array B to array A 11 | // time: O(n); space: O(1) 12 | public class Solution { 13 | public void merge(int A[], int m, int B[], int n) { 14 | if (n == 0) return; 15 | int i = m-1, j = n-1; 16 | int index = A.length-1; 17 | while (i >= 0 && j >= 0){ 18 | if (A[i] > B[j]) A[index--] = A[i--]; 19 | else A[index--] = B[j--]; 20 | } 21 | while (j >= 0) A[index--] = B[j--]; // don't forget this step & no need to copy remaing elements in A, understand why 22 | } 23 | } -------------------------------------------------------------------------------- /LeetCode/MergeTwoSortedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Merge two sorted linked lists and return it as a new list. 3 | The new list should be made by splicing together the nodes of the first two lists. 4 | */ 5 | 6 | /** 7 | * Definition for singly-linked list. 8 | * public class ListNode { 9 | * int val; 10 | * ListNode next; 11 | * ListNode(int x) { 12 | * val = x; 13 | * next = null; 14 | * } 15 | * } 16 | */ 17 | 18 | // Maintain two pointers on two lists 19 | // In each step, compare the two vlaues and move forward the corresponding pointer 20 | // time: O(n) 21 | public class Solution { 22 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 23 | if (l1 == null || l2 == null) 24 | return l1 == null? l2 : l1; 25 | ListNode p1 = l1, p2 = l2; 26 | ListNode dum = new ListNode(0), r = dum; 27 | while (p1 != null && p2 != null){ 28 | if (p1.val < p2.val){ 29 | r.next = p1; 30 | p1 = p1.next; 31 | } 32 | else{ 33 | r.next = p2; 34 | p2 = p2.next; 35 | } 36 | r = r.next; 37 | } 38 | if(p1 != null) 39 | r.next = p1; 40 | if(p2 != null) 41 | r.next = p2; 42 | return dum.next; 43 | } 44 | } -------------------------------------------------------------------------------- /LeetCode/MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | */ 6 | 7 | 8 | // 2d DP, time: O(m*n); space: O(m*n) 9 | // similar to uniquePaths, uniquePaths2 10 | public class Solution { 11 | public int minPathSum(int[][] grid) { 12 | if (grid==null || grid.length==0 || grid[0].length==0) return 0; 13 | int h = grid.length; 14 | int w = grid[0].length; 15 | int[][] mem = new int[h][w]; 16 | mem[0][0] = grid[0][0]; 17 | for (int i=1; i=0; i--){ 26 | sb.append((carry+res[i])%10); 27 | carry = (carry+res[i])/10; 28 | } 29 | if (carry>0) 30 | sb.append(carry); 31 | return sb.reverse().toString(); 32 | } 33 | } -------------------------------------------------------------------------------- /LeetCode/NextPermutation.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 | 6 | The replacement must be in-place, do not allocate extra memory. 7 | 8 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 | 1,2,3 → 1,3,2 10 | 3,2,1 → 1,2,3 11 | 1,1,5 → 1,5,1 12 | */ 13 | 14 | 15 | // [1] find the head (H) of the descending subarray ending at the last element 16 | // [2] reverse this subarray to make it in ascending order 17 | // [3] find the smallest element in the subarray that is larger than the num[H-1], swap the two. 18 | // time: O(n); space: O(1) 19 | public class Solution { 20 | public void nextPermutation(int[] num) { 21 | if (num==null || num.length<=1) return; 22 | int i=num.length-1; 23 | while (i>0 && num[i] <= num[i-1]) i--; 24 | reverse(num, i, num.length-1); 25 | if (i==0) return; 26 | int j = i; 27 | while (j 0){ 16 | reversed = reversed*10 + x%10; 17 | x /= 10; 18 | } 19 | return reversed == original; 20 | } 21 | } -------------------------------------------------------------------------------- /LeetCode/Pascal'sTriangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given numRows, generate the first numRows of Pascal's triangle. 3 | 4 | For example, given numRows = 5, 5 | Return 6 | 7 | [ 8 | [1], 9 | [1,1], 10 | [1,2,1], 11 | [1,3,3,1], 12 | [1,4,6,4,1] 13 | ] 14 | */ 15 | 16 | // Get each level in top-down order 17 | // Each level is based on the previous level 18 | // time: O(n^2); sapce: O(n^2) 19 | public class Solution { 20 | public ArrayList> generate(int numRows) { 21 | ArrayList> res = new ArrayList>(); 22 | if (numRows <=0) return res; 23 | ArrayList prev = new ArrayList(); prev.add(1); 24 | res.add(prev); 25 | for (int i=2; i<=numRows; i++){ 26 | ArrayList curr = new ArrayList(); 27 | curr.add(1); 28 | for (int j=1; j getRow(int rowIndex) { 17 | ArrayList res = new ArrayList(); 18 | int[] row = new int[rowIndex+1]; 19 | row[0] = 1; 20 | int i = 0; 21 | while (i<=rowIndex){ 22 | for (int j=i;j>=1; j--){ 23 | row[j] = row[j-1] + row[j]; 24 | } 25 | i++; 26 | } 27 | for (int num: row) 28 | res.add(num); 29 | return res; 30 | } 31 | } -------------------------------------------------------------------------------- /LeetCode/PathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. 3 | 4 | For example: 5 | Given the below binary tree and sum = 22, 6 | 5 7 | / \ 8 | 4 8 9 | / / \ 10 | 11 13 4 11 | / \ \ 12 | 7 2 1 13 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 14 | */ 15 | 16 | /** 17 | * Definition for binary tree 18 | * public class TreeNode { 19 | * int val; 20 | * TreeNode left; 21 | * TreeNode right; 22 | * TreeNode(int x) { val = x; } 23 | * } 24 | */ 25 | 26 | // Recursion 27 | // Note root-to-leaf path, the condition for a leaf node is 'node.left==null && node.right==null' 28 | // A node with only one null child is not a leaf node 29 | // time: O(n); space: recursive stack 30 | public class Solution { 31 | public boolean hasPathSum(TreeNode root, int sum) { 32 | if (root==null) return false; 33 | sum -= root.val; 34 | if (root.left==null && root.right==null) return sum==0; 35 | return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode/PlusOne.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number represented as an array of digits, plus one to the number. 3 | */ 4 | 5 | // Maintain a varialble to hold the carry 6 | // Traverse from the least significant digit to the most significant digit 7 | // Finally, we have to check 'carry' to know whether we have to resize the array 8 | // One interesting thing is that if we have to resize the array, actually we don't have 9 | // to copy vlaues from original array to new array, because all the values are zero 10 | // time: O(n); space: O(n) 11 | public class Solution { 12 | public int[] plusOne(int[] digits) { 13 | if (digits==null || digits.length==0) return digits; 14 | int carry =1; 15 | for (int i=digits.length-1; i>=0; i--){ 16 | int val = digits[i]; 17 | digits[i] = (carry+val)%10; 18 | carry = (carry+val)/10; 19 | } 20 | if (carry==0) return digits; 21 | // if we're here, the digits should be 9999..9, and the res is 10000..0 22 | int[] res = new int[digits.length+1]; 23 | res[0] =1; 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /LeetCode/Pow.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement pow(x, n). 3 | */ 4 | 5 | // Divide and Conquer 6 | // Note to handle positive and negative x 7 | // time: O(lgn) 8 | public class Solution { 9 | public double pow(double x, int n) { 10 | if (n==0) return 1.0; 11 | double val = pow(x, n/2); 12 | if (n%2==0) return val*val; 13 | return n>0 ? val*val*x : val*val/x; // notice not 1/(val*val*x) here, understand why 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LeetCode/RemoveDuplicatesFromSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this in place with constant memory. 5 | 6 | For example, 7 | Given input array A = [1,1,2], 8 | 9 | Your function should return length = 2, and A is now [1,2]. 10 | */ 11 | 12 | // Maintain two pointers, one for current index, and one for result index 13 | // time: O(n); space:O(1) 14 | public class Solution { 15 | public int removeDuplicates(int[] A) { 16 | if (A==null || A.length==0) return 0; 17 | int i=1, j=1, N =A.length; 18 | while (j< N){ 19 | if (A[j] == A[j-1]) 20 | j++; 21 | else 22 | A[i++] = A[j++]; 23 | } 24 | return i; 25 | } 26 | } -------------------------------------------------------------------------------- /LeetCode/RemoveDuplicatesFromSortedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | 4 | For example, 5 | Given 1->1->2, return 1->2. 6 | Given 1->1->2->3->3, return 1->2->3. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { 15 | * val = x; 16 | * next = null; 17 | * } 18 | * } 19 | */ 20 | 21 | // For each node, find the following duplicates and remove them 22 | // time: O(n); space:O(1) 23 | public class Solution { 24 | public ListNode deleteDuplicates(ListNode head) { 25 | if (head==null || head.next==null) 26 | return head; 27 | ListNode p = head; 28 | while (p!=null){ 29 | ListNode pp = p.next; 30 | while (pp!=null && pp.val == p.val){ 31 | pp = pp.next; 32 | } 33 | p.next = pp; 34 | p = pp; 35 | } 36 | return head; 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode/RemoveDuplicatesFromSortedList2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 3 | 4 | For example, 5 | Given 1->2->3->3->4->4->5, return 1->2->5. 6 | Given 1->1->1->2->3, return 2->3. 7 | */ 8 | 9 | // keep a prev pointer, if the following nodes are duplicates, remove them; 10 | // otherwise, move the prev pointer forwrd 11 | // time: O(n); space: O(1) 12 | public class Solution { 13 | public ListNode deleteDuplicates(ListNode head) { 14 | if (head==null || head.next==null) 15 | return head; 16 | ListNode sen = new ListNode(0); sen.next = head; 17 | ListNode pp = sen, p = head; 18 | while (p!=null && p.next!=null){ 19 | ListNode q = p.next; 20 | while (q!=null && q.val==p.val) q = q.next; 21 | if (q!=p.next) 22 | pp.next = q; 23 | else 24 | pp = p; 25 | p = q; 26 | } 27 | return sen.next; 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/RemoveElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array and a value, remove all instances of that value in place and return the new length. 3 | 4 | The order of elements can be changed. It doesn't matter what you leave beyond the new length. 5 | */ 6 | 7 | // overwrite the target elem 8 | public class Solution { 9 | public int removeElement(int[] A, int elem) { 10 | if (A == null || A.length == 0) return 0; 11 | int index = 0; 12 | for (int i = 0; i < A.length; i++){ 13 | if (A[i] != elem) A[index++] = A[i]; 14 | } 15 | return index; 16 | } 17 | } 18 | 19 | // swap target elem to the end of the array 20 | public class Solution { 21 | public int removeElement(int[] A, int elem) { 22 | if (A==null || A.length==0) return 0; 23 | int i=0, j=A.length-1; 24 | while (i <= j){ 25 | if (A[i] == elem) swap(A, i, j--); 26 | else i++; 27 | } 28 | return j+1; 29 | } 30 | 31 | public void swap(int[] A, int i, int j){ 32 | int tmp = A[i]; 33 | A[i] = A[j]; 34 | A[j] = tmp; 35 | } 36 | } -------------------------------------------------------------------------------- /LeetCode/RemoveNthNodeFromEndOfList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, remove the nth node from the end of list and return its head. 3 | 4 | For example, 5 | 6 | Given linked list: 1->2->3->4->5, and n = 2. 7 | 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | Note: 10 | Given n will always be valid. 11 | Try to do this in one pass. 12 | */ 13 | 14 | // Maintain two pointers 15 | // find the N+1 node from end of list and remove the Nth node 16 | // Note: Given n will always be valid. 17 | // time: O(n), one pass, in position 18 | public class Solution { 19 | public ListNode removeNthFromEnd(ListNode head, int n) { 20 | if (head==null) return null; 21 | ListNode sen = new ListNode(0); sen.next = head; 22 | ListNode l = sen, r = head; 23 | while (n-- > 0) r = r.next; 24 | while (r!=null){ 25 | r = r.next; 26 | l = l.next; 27 | } 28 | l.next = l.next.next; 29 | return dum.next; 30 | } 31 | } -------------------------------------------------------------------------------- /LeetCode/RestoreIPAddresses.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 3 | 4 | For example: 5 | Given "25525511135", 6 | 7 | return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 8 | */ 9 | 10 | // Backtracking 11 | // Use dot as delimiter to partition the string into 4 parts 12 | // Note the range of a partition is [0,255], and 00 or 000 is not allowed 13 | // time: O(Com(n,3)) 14 | public class Solution { 15 | public ArrayList restoreIpAddresses(String s) { 16 | ArrayList res = new ArrayList(); 17 | if (s==null || s.length() == 0) return res; 18 | finder(s, 0, 1, res, new StringBuilder()); 19 | return res; 20 | } 21 | 22 | public void finder(String s, int index, int dot, ArrayList res, StringBuilder r){ 23 | if (dot == 5){ 24 | if (index == s.length()) res.add(r.substring(0, r.length()-1).toString()); // important, should check length here 25 | return; 26 | } 27 | for (int i=1; i<=3 && index+i <= s.length(); i++){ 28 | String str = s.substring(index, index+i); 29 | if (i > 1 && str.charAt(0) == '0') break; 30 | int num = Integer.parseInt(str); 31 | if (num>=0 && num<=255){ 32 | r.append(num); 33 | r.append('.'); 34 | finder(s, index+i, dot+1, res, r); 35 | r.delete(r.length()-i-1, r.length()); 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /LeetCode/ReverseLinkedList2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 3 | 4 | For example: 5 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 6 | 7 | return 1->4->3->2->5->NULL. 8 | 9 | Note: 10 | Given m, n satisfy the following condition: 11 | 1 ≤ m ≤ n ≤ length of list. 12 | */ 13 | 14 | // Find starting node to reverse and then do normal reverseLinkedList 15 | // time: O(n); space: O(1) 16 | public class Solution { 17 | public ListNode reverseBetween(ListNode head, int m, int n) { 18 | if (head==null || head.next==null) 19 | return head; 20 | ListNode sen = new ListNode(0); sen.next = head; 21 | ListNode prev = sen, curr = sen.next; 22 | int k = n-m; 23 | while (--m>0){ 24 | prev = prev.next; 25 | curr = curr.next; 26 | } 27 | while (k-->0){ 28 | ListNode next = curr.next; 29 | curr.next = next.next; 30 | next.next = prev.next; 31 | prev.next = next; 32 | } 33 | return sen.next; 34 | } 35 | } -------------------------------------------------------------------------------- /LeetCode/ReverseWordsInString.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an input string, reverse the string word by word. 3 | 4 | For example, 5 | Given s = "the sky is blue", 6 | return "blue is sky the". 7 | */ 8 | 9 | // maintain a stack to hold all the words parsed from the origianl string 10 | // then, construct the reversed string from stack 11 | // time: O(n); space: O(n) 12 | public class Solution { 13 | public String reverseWords(String s) { 14 | if (s==null || s.length()==0) 15 | return ""; 16 | Stack st = new Stack(); 17 | StringBuilder sb = new StringBuilder(); 18 | for (int i=0; i0){ 23 | st.push(sb.toString()); 24 | sb.delete(0, sb.length()); 25 | } 26 | } 27 | } 28 | if (sb.length()>0) 29 | st.push(sb.toString()); 30 | sb.delete(0,sb.length()); 31 | while (!st.isEmpty()) 32 | sb.append(st.pop()+" "); 33 | if (sb.length()>0) // check here 34 | sb.deleteCharAt(sb.length()-1); 35 | return sb.toString(); 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode/RotateImage.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | 6 | Follow up: 7 | Could you do this in-place? 8 | */ 9 | 10 | // Rotate the matrix by layers, from outer layer to inner layer 11 | // Each time, we swap the four sides in a layer in clockwise direction 12 | // time: O(n*n), each cell will be accessed at most twice; space: O(1) 13 | public class Solution { 14 | public void rotate(int[][] matrix) { 15 | if (matrix==null || matrix.length==0 || matrix[0].length==0) 16 | return; 17 | int N = matrix.length; 18 | // If the length of the matrix border is odd numebr, the central cell will not be rotated 19 | // otherwise, all cells will be rotated 20 | for (int layer=0; layer2->3->4->5->NULL and k = 2, 6 | return 4->5->1->2->3->NULL. 7 | */ 8 | 9 | /** 10 | * Definition for singly-linked list. 11 | * public class ListNode { 12 | * int val; 13 | * ListNode next; 14 | * ListNode(int x) { 15 | * val = x; 16 | * next = null; 17 | * } 18 | * } 19 | */ 20 | 21 | 22 | // Maintain two poointers to track the start and end of the sub-list to be rotated 23 | // time: O(n); space: O(1) 24 | public class Solution { 25 | public ListNode rotateRight(ListNode head, int n) { 26 | if (head==null || head.next==null || n==0) return head; 27 | int len = getLength(head); 28 | n = n % len; // Note modulo here 29 | if (n==0) return head; 30 | ListNode dum = new ListNode(0); dum.next = head; 31 | ListNode l=head, r=head; 32 | while (n-->0) r=r.next; 33 | while (r.next!=null){ 34 | r=r.next; l=l.next; 35 | } 36 | r.next = dum.next; 37 | dum.next = l.next; 38 | l.next=null; 39 | return dum.next; 40 | } 41 | public int getLength(ListNode head){ 42 | int len=0; 43 | while (head!=null){ 44 | head=head.next; 45 | len++; 46 | } 47 | return len; 48 | } 49 | } -------------------------------------------------------------------------------- /LeetCode/SearchInRotatedSortedArray2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Follow up for "Search in Rotated Sorted Array": 3 | What if duplicates are allowed? 4 | 5 | Would this affect the run-time complexity? How and why? 6 | 7 | Write a function to determine if a given target is in the array. 8 | */ 9 | 10 | // Assertion: allow duplicates 11 | // Binary Search 12 | // time: average O(lgn), worst case O(n); space: O(1) 13 | public class Solution { 14 | public boolean search(int[] A, int target) { 15 | if (A == null || A.length == 0) return false; 16 | int start = 0, end = A.length-1; 17 | while (start <= end){ 18 | int mid = (start + end) >> 1; 19 | if (A[mid] == target) return true; 20 | if (A[start] < A[mid]){ 21 | if (A[start] <= target && target < A[mid]) end =mid-1; 22 | else start = mid+1; 23 | }else if (A[start] > A[mid]){ 24 | if (A[mid] < target && target <= A[end]) start = mid+1; 25 | else end = mid-1; 26 | }else // A[start] == A[mid], A[start]!=target 27 | start++; 28 | } 29 | return false; 30 | } 31 | } -------------------------------------------------------------------------------- /LeetCode/SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 3 | 4 | You may assume no duplicates in the array. 5 | 6 | Here are few examples. 7 | [1,3,5,6], 5 → 2 8 | [1,3,5,6], 2 → 1 9 | [1,3,5,6], 7 → 4 10 | [1,3,5,6], 0 → 0 11 | */ 12 | 13 | // binary search 14 | // The key observation is that: the last step in while loop is start==end==mid, 15 | // if A[mid]>target, mid is insertion position; if A[mid]>1); 23 | if (A[mid] == target) return mid; 24 | else if (A[mid] > target) end=mid-1; 25 | else start=mid+1; 26 | } 27 | return start; // equals 'return end+1;' 28 | } 29 | } -------------------------------------------------------------------------------- /LeetCode/SingleNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears twice except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | 8 | // Bit manipulation, xor. a^a = 0; 9 | // time: O(n); space: O(1) 10 | public class Solution { 11 | public int singleNumber(int[] A) { 12 | 13 | if (A == null || A.length == 0) 14 | return 0; 15 | int single = A[0]; 16 | for (int i = 1; i < A.length; i++){ 17 | single ^= A[i]; 18 | } 19 | return single; 20 | } 21 | } -------------------------------------------------------------------------------- /LeetCode/SingleNumber2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers, every element appears three times except for one. Find that single one. 3 | 4 | Note: 5 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | */ 7 | 8 | // sum the number of 1s in each gidit, 9 | // the sum should be divisible by 3 if only the element appearing three times contribute 1 to this digit 10 | // time: O(32n); space (1) 11 | public class Solution { 12 | public int singleNumber(int[] A) { 13 | if (A==null || A.length==0) 14 | return 0; 15 | int res = 0; 16 | for (int i=0; i<32; i++){ 17 | int count = 0; 18 | for (int num : A){ 19 | if (((num>>i)&1)!=0) 20 | count++; 21 | } 22 | if (count%3!=0) 23 | res |= (1< spiralOrder(int[][] matrix) { 19 | ArrayList res = new ArrayList(); 20 | if (matrix == null || matrix.length==0 || matrix[0].length==0) return res; 21 | int left=0, right=matrix[0].length-1, top=0, bottom= matrix.length-1; 22 | while (left <= right && top <=bottom){ 23 | for (int i=left; i<=right; i++) 24 | res.add(matrix[top][i]); 25 | if (++top > bottom) break; // need to break immediately, otherwise will produce duplicates 26 | for (int i=top; i<=bottom; i++) 27 | res.add(matrix[i][right]); 28 | if (--right < left) break; 29 | for (int i=right; i>=left; i--) 30 | res.add(matrix[bottom][i]); 31 | if (--bottom < top) break; 32 | for (int i=bottom; i>=top; i--) 33 | res.add(matrix[i][left]); 34 | if (++left > right) break; 35 | } 36 | return res; 37 | } 38 | } -------------------------------------------------------------------------------- /LeetCode/Sqrt.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement int sqrt(int x). 3 | 4 | Compute and return the square root of x. 5 | */ 6 | 7 | // binary search 8 | // The square root of x will be smaller than x/2+1. Why? (x/2+1)*(x/2+1)> x 9 | // time: O(lgn) 10 | public class Solution { 11 | public int sqrt(int x) { 12 | if (x<=1) return x; 13 | int start = 0, end = x/2+1; 14 | while (start<=end){ 15 | int mid = start + (end-start)/2; 16 | if (mid==x/mid) return mid; // compare mid & x/mid, instead of mid*mid & x, to avoid overflow 17 | else if (mid < x/mid) start = mid+1; 18 | else end = mid-1; 19 | } 20 | return end; // choose the smaller one 21 | } 22 | } 23 | 24 | // Newton's Method, better than binary search 25 | public class Solution { 26 | public int sqrt(int x) { 27 | if (x<=1) 28 | return x; 29 | double r = 1; // need to use double here, otherwise, sqrt(2) may fall in endless loop 30 | while (true){ 31 | double r0 = (r+x/r)/2; 32 | if (Math.abs(r-r0)<0.1) 33 | return (int)r0; // remember to cast here 34 | r = r0; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /LeetCode/SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | For example, 5 | Given 1->2->3->4, you should return the list as 2->1->4->3. 6 | 7 | Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 8 | */ 9 | 10 | /** 11 | * Definition for singly-linked list. 12 | * public class ListNode { 13 | * int val; 14 | * ListNode next; 15 | * ListNode(int x) { 16 | * val = x; 17 | * next = null; 18 | * } 19 | * } 20 | */ 21 | // Basic idea is to maintain 4 pointers, 22 | // two pointers for pair nodes, prev pointer for node before the pair, 23 | // next pointer for node after the pair 24 | // time: O(n); space: O(1) 25 | public class Solution { 26 | public ListNode swapPairs(ListNode head) { 27 | if (head==null || head.next==null) 28 | return head; 29 | ListNode dum = new ListNode(0); 30 | dum.next = head; 31 | ListNode p = head, prev = dum; 32 | while (p!=null && p.next!=null){ 33 | ListNode first = p, second = p.next, next = second.next; 34 | prev.next =second; 35 | second.next = first; 36 | first.next = next; 37 | prev = first; 38 | p = next; 39 | } 40 | return dum.next; 41 | } 42 | } -------------------------------------------------------------------------------- /LeetCode/UniquePaths2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Follow up for "Unique Paths": 3 | 4 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 5 | 6 | An obstacle and empty space is marked as 1 and 0 respectively in the grid. 7 | 8 | For example, 9 | There is one obstacle in the middle of a 3x3 grid as illustrated below. 10 | 11 | [ 12 | [0,0,0], 13 | [0,1,0], 14 | [0,0,0] 15 | ] 16 | The total number of unique paths is 2. 17 | 18 | Note: m and n will be at most 100. 19 | */ 20 | 21 | // 2d DP 22 | // When we encounter an obstacle, set number of paths to it to 0 23 | // time: O(m*n); space: O(m*n) 24 | public class Solution { 25 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 26 | int w = obstacleGrid[0].length; 27 | int h = obstacleGrid.length; 28 | if (w==0 || h==0) return 0; 29 | int[][] mem = new int[h][w]; 30 | mem[0][0] = obstacleGrid[0][0] == 1? 0:1; 31 | for (int i=1; i st = new Stack(); 16 | int N = s.length(); 17 | for (int i=0; i dict) { 15 | if (s==null || s.length()==0) return true; 16 | boolean[] dp = new boolean[s.length()+1]; 17 | dp[0] = true; 18 | for (int i=1; i<=s.length(); i++){ 19 | for (int j=i-1; j>=0; j--){ 20 | if (dict.contains(s.substring(j,i)) && dp[j]){ 21 | dp[i] = true; 22 | break; 23 | } 24 | } 25 | } 26 | return dp[s.length()]; 27 | } 28 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Coding In the Deep 2 | =============== 3 | 4 | This is a repo of questions for programming interviews, including questions from **[Leetcode](http://oj.leetcode.com)**, **[Crack The Coding Interview](https://github.com/gaylemcd/ctci)**, **[CareerCup](http://www.careercup.com)**, **Glassdoor**, **[1point2acres](http://www.1point3acres.com/bbs/)** and **[GeeksForGeeks](http://www.geeksforgeeks.org)**. 5 | * CTCI: my solutions to CTCI questions, categorized by chapters 6 | * Leetcode: Each question has at least one solution passing the online judge 7 | * Company: Questions that are frequently asked in this company's interviews, categorized by company name. 8 | * KnowledgeBase: Knowledges about Java, Android and Computer Science basics. 9 | --------------------------------------------------------------------------------