├── .github
└── workflows
│ └── maven.yml
├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── coollime
├── .factorypath
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── coollime
│ │ ├── App.java
│ │ ├── binarysearch
│ │ ├── classic
│ │ │ └── Solution.java
│ │ ├── closest
│ │ │ ├── closest
│ │ │ │ └── Solution.java
│ │ │ └── kclosest
│ │ │ │ └── Solution.java
│ │ ├── occurrence
│ │ │ ├── first
│ │ │ │ └── Solution.java
│ │ │ └── last
│ │ │ │ └── Solution.java
│ │ └── search
│ │ │ ├── findminimuminrotatedsortedarray
│ │ │ └── Solution.java
│ │ │ ├── searchinsortedmatrixi
│ │ │ └── Solution.java
│ │ │ └── searchinunknownsizedsortedarray
│ │ │ ├── Dictionary.java
│ │ │ └── Solution.java
│ │ ├── binarytree
│ │ ├── bst
│ │ │ ├── getkeys
│ │ │ │ └── Solution.java
│ │ │ ├── insert
│ │ │ │ └── Solution.java
│ │ │ ├── search
│ │ │ │ └── Solution.java
│ │ │ └── validbst
│ │ │ │ └── Solution.java
│ │ ├── general
│ │ │ ├── balanced
│ │ │ │ └── Solution.java
│ │ │ ├── symmetric
│ │ │ │ └── Solution.java
│ │ │ └── tweaked
│ │ │ │ └── Solution.java
│ │ ├── path
│ │ │ └── sumi
│ │ │ │ └── Solution.java
│ │ └── traversal
│ │ │ ├── inorder
│ │ │ └── Solution.java
│ │ │ ├── postorder
│ │ │ └── Solution.java
│ │ │ └── preorder
│ │ │ └── Solution.java
│ │ ├── common
│ │ └── objects
│ │ │ ├── GraphNode.java
│ │ │ ├── ListNode.java
│ │ │ └── TreeNode.java
│ │ ├── linkedlist
│ │ ├── addtwonumbers
│ │ │ └── Solution.java
│ │ ├── checkiflinkedlisthasacycyle
│ │ │ └── Solution.java
│ │ ├── checkiflinkedlistispalindrome
│ │ │ └── Solution.java
│ │ ├── cyclenodeinlinkedlist
│ │ │ └── Solution.java
│ │ ├── insertinsortedlinkedlist
│ │ │ └── Solution.java
│ │ ├── mergesortlinkedlist
│ │ │ └── Solution.java
│ │ ├── mergetwosortedlinkedlists
│ │ │ └── Solution.java
│ │ ├── middlenodeoflinkedlist
│ │ │ └── Solution.java
│ │ ├── partitionlinkedlist
│ │ │ └── Solution.java
│ │ ├── reorderlinkedlist
│ │ │ └── Solution.java
│ │ └── reverselinkedlist
│ │ │ └── Solution.java
│ │ ├── queueandstack
│ │ ├── queuebytwostacks
│ │ │ └── Solution.java
│ │ ├── sortwiththreestacks
│ │ │ └── Solution.java
│ │ ├── sortwithtwostacks
│ │ │ └── Solution.java
│ │ └── stackwithmin
│ │ │ └── Solution.java
│ │ ├── recursion
│ │ ├── atothepowerofb
│ │ │ └── Solution.java
│ │ ├── binarytreepathsumtotargetiii
│ │ │ └── Solution.java
│ │ ├── fibonaccinumber
│ │ │ └── Solution.java
│ │ ├── lowestcommonancestori
│ │ │ └── Solution.java
│ │ ├── lowestcommonancestorii
│ │ │ └── Solution.java
│ │ ├── maximumpathsumbinarytreeii
│ │ │ └── Solution.java
│ │ ├── maximumpathsumbinarytreeiii
│ │ │ └── Solution.java
│ │ ├── nqueens
│ │ │ └── Solution.java
│ │ ├── spiralordertraversei
│ │ │ └── Solution.java
│ │ └── spiralordertraverseii
│ │ │ └── Solution.java
│ │ └── sortingalgorithms
│ │ ├── mergesort
│ │ └── Solution.java
│ │ ├── movezerostotheendi
│ │ └── Solution.java
│ │ ├── quicksort
│ │ └── Solution.java
│ │ ├── rainbowsort
│ │ └── Solution.java
│ │ └── selectionsort
│ │ └── Solution.java
│ └── test
│ └── java
│ └── coollime
│ ├── AppTest.java
│ ├── binarysearch
│ ├── classic
│ │ └── ClassicalBinarySearchTest.java
│ ├── closest
│ │ └── kclosest
│ │ │ └── KClosestInSortedArrayTest.java
│ ├── occurrence
│ │ ├── first
│ │ │ └── FirstOccurrenceTest.java
│ │ └── last
│ │ │ └── LastOccurrenceTest.java
│ └── search
│ │ ├── findminimuminrotatedsortedarray
│ │ └── FindMinimumInRotatedSortedArrayTest.java
│ │ ├── searchinsortedmatrixi
│ │ └── SearchInSortedMatrixITest.java
│ │ └── searchinunknownsizedsortedarray
│ │ └── SearchInUnknownSizedSortedArrayTest.java
│ ├── binarytree
│ ├── bst
│ │ ├── getkeys
│ │ │ └── GetKeysInBinarySearchTreeInGivenRangeTest.java
│ │ ├── insert
│ │ │ └── InsertInBinarySearchTreeTest.java
│ │ ├── search
│ │ │ └── SearchInBinarySearchTreeTest.java
│ │ └── validbst
│ │ │ └── IsBinarySearchTreeOrNotTest.java
│ ├── general
│ │ ├── balanced
│ │ │ └── CheckIfBinaryTreeIsBalancedTest.java
│ │ ├── symmetric
│ │ │ └── SymmetricBinaryTreeTest.java
│ │ └── tweaked
│ │ │ └── TweakedIdenticalBinaryTreesTest.java
│ ├── path
│ │ └── sumi
│ │ │ └── BinaryTreePathSumToTargetITest.java
│ └── traversal
│ │ ├── inorder
│ │ └── InorderTraversalOfBinaryTreeTest.java
│ │ ├── postorder
│ │ └── PostorderTraversalOfBinaryTreeTest.java
│ │ └── preorder
│ │ └── PreorderTraversalOfBinaryTreeTest.java
│ ├── linkedlist
│ ├── addtwonumbers
│ │ └── AddTwoNumbersTest.java
│ ├── checkiflinkedlisthasacycyle
│ │ └── CheckIfLinkedListHasACycyleTest.java
│ ├── checkiflinkedlistispalindrome
│ │ └── CheckIfLinkedListIsPalindromeTest.java
│ ├── cyclenodeinlinkedlist
│ │ └── CycleNodeInLinkedListTest.java
│ ├── insertinsortedlinkedlist
│ │ └── InsertInSortedLinkedListTest.java
│ ├── mergesortlinkedlist
│ │ └── MergeSortLinkedListTest.java
│ ├── mergetwosortedlinkedlists
│ │ └── MergeTwoSortedLinkedListsTest.java
│ ├── middlenodeoflinkedlist
│ │ └── MiddleNodeOfLinkedListTest.java
│ ├── partitionlinkedlist
│ │ └── PartitionLinkedListTest.java
│ ├── reorderlinkedlist
│ │ └── ReOrderLinkedListTest.java
│ └── reverselinkedlist
│ │ └── ReverseLinkedListTest.java
│ ├── queueandstack
│ ├── queuebytwostacks
│ │ └── QueueByTwoStacksTest.java
│ ├── sortwiththreestacks
│ │ └── SortWith3StacksTest.java
│ ├── sortwithtwostacks
│ │ └── SortWith2StacksTest.java
│ └── stackwithmin
│ │ └── StackWithMinTest.java
│ ├── recursion
│ ├── atothepowerofb
│ │ └── AToThePowerOfBTest.java
│ ├── binarytreepathsumtotargetiii
│ │ └── BinaryTreePathSumToTargetIIITest.java
│ ├── fibonaccinumber
│ │ └── FibonacciNumberTest.java
│ ├── lowestcommonancestori
│ │ └── LowestCommonAncestorITest.java
│ ├── lowestcommonancestorii
│ │ └── LowestCommonAncestorIITest.java
│ ├── maximumpathsumbinarytreeiii
│ │ └── MaximumPathSumBinaryTreeIIITest.java
│ ├── nqueens
│ │ └── NQueensTest.java
│ ├── spiralordertraversei
│ │ └── SpiralOrderTraverseITest.java
│ └── spiralordertraverseii
│ │ └── SpiralOrderTraverseIITest.java
│ └── sortingalgorithms
│ ├── mergesort
│ └── MergeSortTest.java
│ ├── movezerostotheendi
│ └── Move0sToTheEndITest.java
│ ├── quicksort
│ └── QuickSortTest.java
│ ├── rainbowsort
│ └── RainbowSortTest.java
│ └── selectionsort
│ └── SelectionSortTest.java
├── docs
├── binarysearch
│ ├── ClassicalBinarySearch.md
│ ├── ClosestInSortedArray.md
│ ├── FindMinimumInRotatedSortedArray.md
│ ├── FirstOccurrence.md
│ ├── KClosestInSortedArray.md
│ ├── LastOccurrence.md
│ ├── README.md
│ ├── SearchInSortedMatrixI.md
│ ├── SearchInUnknownSizedSortedArray.md
│ └── search_sorted_matrix.png
├── binarytree
│ ├── BinaryTreePathSumToTargetI.md
│ ├── CheckIfBinaryTreeIsBalanced.md
│ ├── GetKeysInBinarySearchTreeInGivenRange.md
│ ├── InorderTraversalOfBinaryTree.md
│ ├── InsertInBinarySearchTree.md
│ ├── IsBinarySearchTreeOrNot.md
│ ├── PostorderTraversalOfBinaryTree.md
│ ├── PreorderTraversalOfBinaryTree.md
│ ├── README.md
│ ├── SearchInBinarySearchTree.md
│ ├── SymmetricBinaryTree.md
│ ├── Tweaked-Identical0.png
│ └── TweakedIdenticalBinaryTrees.md
├── linkedlist
│ ├── AddTwoNumbers.md
│ ├── CheckIfLinkedListHasACycle.md
│ ├── CheckIfLinkedListIsPalindrome.md
│ ├── CycleNodeInLinkedList.md
│ ├── CycleNodeInLinkedList.png
│ ├── InsertInSortedLinkedList.md
│ ├── MergeSortLinkedList.md
│ ├── MergeTwoSortedLinkedLists.md
│ ├── MiddleNodeOfLinkedList.md
│ ├── PartitionLinkedList.md
│ ├── README.md
│ ├── ReOrderLinkedList.md
│ └── ReverseLinkedList.md
├── queueandstack
│ ├── QueueByTwoStacks.md
│ ├── README.md
│ ├── SortWith2Stacks.md
│ ├── SortWith3Stacks.md
│ └── StackWithMin.md
├── recursion
│ ├── README.md
│ ├── i
│ │ ├── AToThePowerOfB.md
│ │ ├── FibonacciNumber.md
│ │ ├── README.md
│ │ ├── improved_complexity.png
│ │ ├── improved_method.png
│ │ ├── naive_complexity.png
│ │ └── optimized_complexity.png
│ └── ii
│ │ ├── BinaryTreePathSumToTargetIII.md
│ │ ├── LowestCommonAncestorI.md
│ │ ├── LowestCommonAncestorII.md
│ │ ├── MaximumPathSumBinaryTreeII.md
│ │ ├── NQueens.md
│ │ ├── README.md
│ │ ├── SpiralOrderTraverseI.md
│ │ ├── SpiralOrderTraverseII.md
│ │ ├── lca0.png
│ │ ├── lca1.png
│ │ └── nqueens.png
└── sortingalgorithms
│ ├── MergeSort.md
│ ├── Move0sToTheEndI.md
│ ├── QuickSort.md
│ ├── README.md
│ ├── RainbowSort.md
│ ├── SelectionSort.md
│ ├── merge_sort.png
│ ├── quick_sort1.png
│ ├── quick_sort2.png
│ └── rainbowsort.png
├── package-lock.json
├── package.json
└── src
├── G
└── HeapAndBFS
│ ├── Easy
│ └── GetKeysInBinaryTreeLayerByLayer
│ │ ├── GetKeysInBinaryTreeLayerByLayer.java
│ │ ├── GetKeysInBinaryTreeLayerByLayerTest.java
│ │ └── README.md
│ ├── Hard
│ └── Bipartite
│ │ ├── Bipartite.java
│ │ ├── BipartiteTest.java
│ │ └── README.md
│ ├── Medium
│ ├── CheckIfBinaryTreeIsCompleted
│ │ ├── CheckIfBinaryTreeIsCompleted.java
│ │ ├── CheckIfBinaryTreeIsCompletedTest.java
│ │ └── README.md
│ ├── KSmallestInUnsortedArray
│ │ ├── KSmallestInUnsortedArray.java
│ │ ├── KSmallestInUnsortedArrayTest.java
│ │ └── README.md
│ ├── KthSmallestNumberInSortedMatrix
│ │ ├── KthSmallestNumberInSortedMatrix.java
│ │ ├── KthSmallestNumberInSortedMatrixTest.java
│ │ └── README.md
│ ├── NumberOfIslands
│ │ ├── NumberOfIslands.java
│ │ └── README.md
│ └── WallsAndGates
│ │ ├── README.md
│ │ ├── Solution.java
│ │ └── SolutionTest.java
│ └── README.md
├── H
└── DFS
│ ├── I
│ ├── Medium
│ │ ├── AllPermutationsI
│ │ │ ├── AllPermutationsI.java
│ │ │ ├── AllPermutationsITest.java
│ │ │ └── README.md
│ │ ├── AllSubsetsI
│ │ │ ├── AllSubsetsI.java
│ │ │ ├── AllSubsetsITest.java
│ │ │ └── README.md
│ │ ├── AllValidPermutationsOfParenthesesI
│ │ │ ├── AllValidPermutationsOfParenthesesI.java
│ │ │ ├── AllValidPermutationsOfParenthesesITest.java
│ │ │ └── README.md
│ │ └── CombinationsOfCoins
│ │ │ ├── CombinationsOfCoins.java
│ │ │ ├── CombinationsOfCoinsTest.java
│ │ │ ├── README.md
│ │ │ └── algorithm.png
│ └── README.md
│ ├── II
│ ├── Hard
│ │ ├── AllSubsetsII
│ │ │ ├── AllSubsetsII.java
│ │ │ ├── AllSubsetsIITest.java
│ │ │ └── README.md
│ │ └── AllValidPermutationsOfParenthesesII
│ │ │ ├── AllValidPermutationsOfParenthesesII.java
│ │ │ ├── AllValidPermutationsOfParenthesesIITest.java
│ │ │ └── README.md
│ ├── Medium
│ │ └── AllSubsetsSizeOfK
│ │ │ ├── AllSubsetsSizeOfK.java
│ │ │ ├── AllSubsetsSizeOfKTest.java
│ │ │ └── README.md
│ └── README.md
│ └── README.md
├── I
└── HashTable
│ ├── Easy
│ └── CommonNumbersOfTwoSortedArrays
│ │ ├── CommonNumbersOfTwoSortedArrays.java
│ │ ├── CommonNumbersOfTwoSortedArraysTest.java
│ │ └── README.md
│ ├── Medium
│ ├── MissingNumberI
│ │ ├── MissingNumberI.java
│ │ ├── MissingNumberITest.java
│ │ └── README.md
│ └── TopKFrequentWords
│ │ ├── README.md
│ │ ├── TopKFrequentWords.java
│ │ └── TopKFrequentWordsTest.java
│ └── README.md
├── J
└── String
│ ├── I
│ ├── Easy
│ │ ├── RemoveAdjacentRepeatedCharactersI
│ │ │ ├── README.md
│ │ │ ├── RemoveAdjacentRepeatedCharactersI.java
│ │ │ └── RemoveAdjacentRepeatedCharactersITest.java
│ │ ├── RemoveCertainCharacters
│ │ │ ├── README.md
│ │ │ ├── RemoveCertainCharacters.java
│ │ │ └── RemoveCertainCharactersTest.java
│ │ └── RemoveSpaces
│ │ │ ├── README.md
│ │ │ ├── RemoveSpaces.java
│ │ │ └── RemoveSpacesTest.java
│ ├── Hard
│ │ └── RemoveAdjacentRepeatedCharactersIV
│ │ │ ├── README.md
│ │ │ ├── RemoveAdjacentRepeatedCharactersIV.java
│ │ │ └── RemoveAdjacentRepeatedCharactersIVTest.java
│ ├── Medium
│ │ └── DetermineIfOneStringIsAnothersSubstring
│ │ │ ├── DetermineIfOneStringIsAnothersSubstring.java
│ │ │ ├── DetermineIfOneStringIsAnothersSubstringTest.java
│ │ │ ├── README.md
│ │ │ └── rabin_karp.png
│ └── README.md
│ ├── II
│ ├── Easy
│ │ ├── ReverseString
│ │ │ ├── README.md
│ │ │ ├── ReverseString.java
│ │ │ └── ReverseStringTest.java
│ │ └── RightShiftByNCharacters
│ │ │ ├── README.md
│ │ │ ├── RightShiftByNCharacters.java
│ │ │ └── RightShiftByNCharactersTest.java
│ ├── Hard
│ │ ├── AllPermutationsII
│ │ │ ├── AllPermutationsII.java
│ │ │ ├── AllPermutationsIITest.java
│ │ │ └── README.md
│ │ ├── DecompressStringII
│ │ │ ├── DecompressStringII.java
│ │ │ ├── DecompressStringIITest.java
│ │ │ └── README.md
│ │ ├── ReOrderArray
│ │ │ ├── README.md
│ │ │ ├── ReOrderArray.java
│ │ │ └── ReOrderArrayTest.java
│ │ └── StringReplace
│ │ │ ├── README.md
│ │ │ ├── StringReplace.java
│ │ │ └── StringReplaceTest.java
│ ├── Medium
│ │ ├── AllAnagrams
│ │ │ ├── AllAnagrams.java
│ │ │ ├── AllAnagramsTest.java
│ │ │ └── README.md
│ │ ├── LongestSubstringWithoutRepeatingCharacters
│ │ │ ├── LongestSubstringWithoutRepeatingCharacters.java
│ │ │ ├── LongestSubstringWithoutRepeatingCharactersTest.java
│ │ │ └── README.md
│ │ └── ReverseWordsInASentenceI
│ │ │ ├── README.md
│ │ │ ├── ReverseWordsInASentenceI.java
│ │ │ └── ReverseWordsInASentenceITest.java
│ └── README.md
│ └── README.md
├── K
└── Bit
│ ├── Easy
│ ├── HexadecimalRepresentation
│ │ ├── HexadecimalRepresentation.java
│ │ ├── HexadecimalRepresentationTest.java
│ │ ├── README.md
│ │ └── hex_mod.png
│ └── PowerOfTwo
│ │ ├── PowerOfTwo.java
│ │ ├── PowerOfTwoTest.java
│ │ └── README.md
│ ├── Medium
│ ├── AllUniqueCharactersII
│ │ ├── AllUniqueCharactersII.java
│ │ ├── AllUniqueCharactersIITest.java
│ │ ├── README.md
│ │ └── bit_vector.png
│ └── NumberOfDifferentBits
│ │ ├── NumberOfDifferentBits.java
│ │ ├── NumberOfDifferentBitsTest.java
│ │ └── README.md
│ └── README.md
├── L
└── DynamicProgramming
│ ├── I
│ ├── Easy
│ │ └── LongestAscendingSubArray
│ │ │ ├── LongestAscendingSubArray.java
│ │ │ ├── LongestAscendingSubArrayTest.java
│ │ │ └── README.md
│ ├── Medium
│ │ ├── ArrayHopperI
│ │ │ ├── ArrayHopperI.java
│ │ │ ├── ArrayHopperITest.java
│ │ │ ├── README.md
│ │ │ └── notes.png
│ │ └── MaxProductOfCuttingRope
│ │ │ ├── MaxProductOfCuttingRope.java
│ │ │ ├── MaxProductOfCuttingRopeTest.java
│ │ │ ├── README.md
│ │ │ └── example.png
│ └── README.md
│ ├── II
│ ├── Hard
│ │ └── LargestSquareOfOnes
│ │ │ ├── LargestSquareOfOnes.java
│ │ │ ├── LargestSquareOfOnesTest.java
│ │ │ ├── README.md
│ │ │ └── notes.png
│ ├── Medium
│ │ ├── ArrayHopperII
│ │ │ ├── ArrayHopperII.java
│ │ │ ├── ArrayHopperIITest.java
│ │ │ └── README.md
│ │ ├── DictionaryWordI
│ │ │ ├── DictionaryWordI.java
│ │ │ ├── DictionaryWordITest.java
│ │ │ ├── README.md
│ │ │ └── dictionary_word.png
│ │ ├── EditDistance
│ │ │ ├── EditDistance.java
│ │ │ ├── EditDistanceTest.java
│ │ │ ├── README.md
│ │ │ ├── edit_distance00.png
│ │ │ ├── edit_distance01.png
│ │ │ └── edit_distance02.png
│ │ └── LargestSubArraySum
│ │ │ ├── LargestSubArraySum.java
│ │ │ ├── LargestSubArraySumTest.java
│ │ │ └── README.md
│ └── README.md
│ ├── III
│ ├── Easy
│ │ └── LongestConsecutiveOnes
│ │ │ ├── LongestConsecutiveOnes.java
│ │ │ ├── LongestConsecutiveOnesTest.java
│ │ │ └── README.md
│ ├── Hard
│ │ ├── LargestSubMatrixSum
│ │ │ ├── LargestSubMatrixSum.java
│ │ │ ├── LargestSubMatrixSumTest.java
│ │ │ ├── README.md
│ │ │ ├── prefix_sum1.png
│ │ │ ├── prefix_sum2.1.png
│ │ │ ├── prefix_sum2.2.png
│ │ │ └── prefix_sum3.png
│ │ ├── LargestXOf1s
│ │ │ ├── LargestXOf1s.java
│ │ │ ├── LargestXOf1sTest.java
│ │ │ └── README.md
│ │ └── LongestCrossOfOnes
│ │ │ ├── LongestCrossOfOnes.java
│ │ │ ├── LongestCrossOfOnesTest.java
│ │ │ ├── README.md
│ │ │ └── longestcross.png
│ ├── Medium
│ │ └── LargestSubarraySum
│ │ │ ├── LargestSubarraySum.java
│ │ │ ├── LargestSubarraySumTest.java
│ │ │ └── README.md
│ └── README.md
│ └── README.md
├── M
└── Probability
│ ├── Medium
│ ├── MedianTracker
│ │ ├── MedianTracker.java
│ │ ├── MedianTrackerTest.java
│ │ ├── README.md
│ │ └── median_tracker.png
│ ├── NinetyFivePercentile
│ │ ├── NinetyFivePercentile.java
│ │ ├── README.md
│ │ └── javadoc
│ │ │ ├── N
│ │ │ └── Probability
│ │ │ │ └── Medium
│ │ │ │ └── NinetyFivePercentile
│ │ │ │ ├── NinetyFivePercentile.html
│ │ │ │ ├── package-frame.html
│ │ │ │ ├── package-summary.html
│ │ │ │ └── package-tree.html
│ │ │ ├── allclasses-frame.html
│ │ │ ├── allclasses-noframe.html
│ │ │ ├── constant-values.html
│ │ │ ├── deprecated-list.html
│ │ │ ├── element-list
│ │ │ ├── help-doc.html
│ │ │ ├── index-files
│ │ │ ├── index-1.html
│ │ │ └── index-2.html
│ │ │ ├── index.html
│ │ │ ├── jquery
│ │ │ ├── external
│ │ │ │ └── jquery
│ │ │ │ │ └── jquery.js
│ │ │ ├── images
│ │ │ │ ├── ui-bg_flat_0_aaaaaa_40x100.png
│ │ │ │ ├── ui-bg_flat_75_ffffff_40x100.png
│ │ │ │ ├── ui-bg_glass_55_fbf9ee_1x400.png
│ │ │ │ ├── ui-bg_glass_65_ffffff_1x400.png
│ │ │ │ ├── ui-bg_glass_75_dadada_1x400.png
│ │ │ │ ├── ui-bg_glass_75_e6e6e6_1x400.png
│ │ │ │ ├── ui-bg_glass_95_fef1ec_1x400.png
│ │ │ │ ├── ui-bg_highlight-soft_75_cccccc_1x100.png
│ │ │ │ ├── ui-icons_222222_256x240.png
│ │ │ │ ├── ui-icons_2e83ff_256x240.png
│ │ │ │ ├── ui-icons_454545_256x240.png
│ │ │ │ ├── ui-icons_888888_256x240.png
│ │ │ │ └── ui-icons_cd0a0a_256x240.png
│ │ │ ├── jquery-1.10.2.js
│ │ │ ├── jquery-ui.css
│ │ │ ├── jquery-ui.js
│ │ │ ├── jquery-ui.min.css
│ │ │ ├── jquery-ui.min.js
│ │ │ ├── jquery-ui.structure.css
│ │ │ ├── jquery-ui.structure.min.css
│ │ │ ├── jszip-utils
│ │ │ │ └── dist
│ │ │ │ │ ├── jszip-utils-ie.js
│ │ │ │ │ ├── jszip-utils-ie.min.js
│ │ │ │ │ ├── jszip-utils.js
│ │ │ │ │ └── jszip-utils.min.js
│ │ │ └── jszip
│ │ │ │ └── dist
│ │ │ │ ├── jszip.js
│ │ │ │ └── jszip.min.js
│ │ │ ├── member-search-index.js
│ │ │ ├── member-search-index.zip
│ │ │ ├── overview-tree.html
│ │ │ ├── package-search-index.js
│ │ │ ├── package-search-index.zip
│ │ │ ├── resources
│ │ │ ├── glass.png
│ │ │ └── x.png
│ │ │ ├── script.js
│ │ │ ├── search.js
│ │ │ ├── stylesheet.css
│ │ │ ├── type-search-index.js
│ │ │ └── type-search-index.zip
│ ├── PerfectShuffle
│ │ ├── PerfectShuffle.java
│ │ ├── README.md
│ │ ├── perfect_shuffle1.png
│ │ └── perfect_shuffle2.png
│ ├── Random1000UsingRandom5
│ │ ├── README.md
│ │ └── Random1000UsingRandom5.java
│ ├── Random7UsingRandom5
│ │ ├── README.md
│ │ ├── Random7UsingRandom5.java
│ │ ├── random7.1.png
│ │ └── random7.2.png
│ └── ReservoirSampling
│ │ ├── README.md
│ │ ├── ReservoirSampling.java
│ │ └── reservoir_sampling.png
│ └── README.md
├── N
└── CrossTraining
│ ├── I
│ ├── Easy
│ │ ├── ArrayDeduplicationI
│ │ │ ├── ArrayDeduplicationI.java
│ │ │ ├── ArrayDeduplicationITest.java
│ │ │ ├── README.md
│ │ │ ├── arraydedup0.png
│ │ │ └── arraydedup1.png
│ │ ├── Move0sToTheEndII
│ │ │ ├── Move0sToTheEndII.java
│ │ │ ├── Move0sToTheEndTest.java
│ │ │ └── README.md
│ │ └── TwoSum
│ │ │ ├── README.md
│ │ │ └── Solution.java
│ ├── Hard
│ │ └── ArrayDeduplicationIV
│ │ │ ├── ArrayDeduplicationIV.java
│ │ │ ├── ArrayDeduplicationIVTest.java
│ │ │ └── README.md
│ ├── Medium
│ │ ├── ArrayDeduplicationII
│ │ │ ├── ArrayDeduplicationII.java
│ │ │ ├── ArrayDeduplicationIITest.java
│ │ │ └── README.md
│ │ ├── ArrayDeduplicationIII
│ │ │ ├── ArrayDeduplicationIII.java
│ │ │ ├── ArrayDeduplicationIIITest.java
│ │ │ └── README.md
│ │ ├── BinaryTreeZigZagTraversal
│ │ │ ├── BinaryTreeZigZagTraversal.java
│ │ │ ├── BinaryTreeZigZagTraversalTest.java
│ │ │ ├── README.md
│ │ │ └── zigzag.png
│ │ ├── LargestAndSecondLargest
│ │ │ ├── LargestAndSecondLargest.java
│ │ │ ├── LargestAndSecondLargestTest.java
│ │ │ ├── README.md
│ │ │ └── largest_second.png
│ │ ├── LargestAndSmallest
│ │ │ ├── LargestAndSmallest.java
│ │ │ ├── LargestAndSmallestTest.java
│ │ │ └── README.md
│ │ ├── RotateMatrix
│ │ │ ├── README.md
│ │ │ ├── RotateMatrix.java
│ │ │ └── RotateMatrixTest.java
│ │ ├── ThreeSum
│ │ │ ├── README.md
│ │ │ ├── Solution.java
│ │ │ └── SolutionTest.java
│ │ ├── TwoSumPairI
│ │ │ ├── README.md
│ │ │ ├── Solution.java
│ │ │ └── SolutionTest.java
│ │ └── TwoSumPairII
│ │ │ ├── README.md
│ │ │ └── Solution.java
│ └── README.md
│ ├── II
│ ├── Medium
│ │ ├── ClosestNumberInBinarySearchTree
│ │ │ ├── ClosestNumberInBinarySearchTree.java
│ │ │ ├── ClosestNumberInBinarySearchTreeTest.java
│ │ │ └── README.md
│ │ ├── DeepCopyLinkedListWithRandomPointer
│ │ │ ├── DeepCopyLinkedListWithRandomPointer.java
│ │ │ ├── DeepCopyLinkedListWithRandomPointerTest.java
│ │ │ └── README.md
│ │ ├── DeepCopyUndirectedGraph
│ │ │ ├── DeepCopyUndirectedGraph.java
│ │ │ ├── DeepCopyUndirectedGraphTest.java
│ │ │ └── README.md
│ │ ├── DeleteInBinarySearchTree
│ │ │ ├── DeleteInBinarySearchTree.java
│ │ │ ├── DeleteInBinarySearchTreeTest.java
│ │ │ └── README.md
│ │ ├── LargestNumberSmallerInBinarySearchTree
│ │ │ ├── LargestNumberSmallerInBinarySearchTree.java
│ │ │ ├── LargestNumberSmallerInBinarySearchTreeTest.java
│ │ │ └── README.md
│ │ ├── MergeKSortedArrays
│ │ │ ├── MergeKSortedArrays.java
│ │ │ ├── MergeKSortedArraysTest.java
│ │ │ ├── README.md
│ │ │ └── algorithm.png
│ │ └── MergeKSortedLists
│ │ │ ├── MergeKSortedLists.java
│ │ │ ├── MergeKSortedListsTest.java
│ │ │ └── README.md
│ └── README.md
│ ├── III
│ └── README.md
│ ├── IV
│ ├── Easy
│ │ └── MajorityNumberI
│ │ │ ├── MajorityNumberI.java
│ │ │ └── README.md
│ ├── Hard
│ │ └── KthSmallestInTwoSortedArrays
│ │ │ ├── KthSmallestInTwoSortedArrays.java
│ │ │ ├── KthSmallestInTwoSortedArraysTest.java
│ │ │ └── README.md
│ ├── Medium
│ │ ├── FirstNonRepeatingCharacterInStream
│ │ │ ├── FirstNonRepeatingCharacterInStream.java
│ │ │ ├── FirstNonRepeatingCharacterInStreamTest.java
│ │ │ └── README.md
│ │ ├── ImplementLRUCache
│ │ │ ├── ImplementLRUCache.java
│ │ │ └── README.md
│ │ └── MaximumValuesOfSizeKSlidingWindows
│ │ │ ├── MaximumValuesOfSizeKSlidingWindows.java
│ │ │ ├── MaximumValuesOfSizeKSlidingWindowsTest.java
│ │ │ └── README.md
│ └── README.md
│ ├── README.md
│ └── VI
│ ├── Medium
│ ├── LongestAscendingSubsequence
│ │ ├── LongestAscendingSubsequence.java
│ │ └── README.md
│ └── LongestCommonSubstring
│ │ ├── LongestCommonSubstring.java
│ │ └── README.md
│ └── README.md
└── Z
└── FreePractice
├── Easy
├── PalindromePermutation
│ ├── PalindromePermutation.java
│ ├── PalindromePermutationTest.java
│ └── README.md
└── PlusOne
│ ├── PlusOne.java
│ └── README.md
├── Medium
├── CloneGraph
│ ├── CloneGraph.java
│ ├── CloneGraphTest.java
│ └── README.md
└── PalindromePermutationII
│ ├── PalindromePermutationII.java
│ ├── PalindromePermutationIITest.java
│ └── README.md
└── README.md
/.github/workflows/maven.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a Java project with Maven
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
3 |
4 | name: Java CI with Maven
5 |
6 | on:
7 | push:
8 | branches: "**"
9 | pull_request:
10 | branches: [master]
11 |
12 | jobs:
13 | build:
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 | - uses: actions/checkout@v2
18 | - name: Set up JDK 11 for x64
19 | uses: actions/setup-java@v2
20 | with:
21 | java-version: "11"
22 | distribution: "adopt"
23 | architecture: x64
24 | - name: Build with Maven
25 | run: mvn -B package --file coollime/pom.xml
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode/
2 | .settings/
3 | .classpath
4 | .project
5 | out/
6 | *.class
7 | *.iml
8 | *.lst
9 | *.txt
10 | *.xml
11 | *.jar
12 | *.log
13 | node_modules
14 | coollime/target/
15 | coollime/target/maven-archiver/pom.properties
16 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "printWidth": 100,
3 | "semi": true,
4 | "useTabs": false,
5 | "tabWidth": 2
6 | }
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Cool Lime
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/coollime/.factorypath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/App.java:
--------------------------------------------------------------------------------
1 | package coollime;
2 |
3 | /**
4 | * Hello world!
5 | *
6 | */
7 | public class App
8 | {
9 | public static void main( String[] args )
10 | {
11 | System.out.println( "Hello World!" );
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/classic/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.classic;
2 |
3 | public class Solution {
4 | public int binarySearch(int[] array, int target) {
5 | if (array == null || array.length == 0) {
6 | return -1;
7 | }
8 | int start = 0;
9 | int end = array.length - 1;
10 | while (start <= end) {
11 | int mid = start + (end - start) / 2;
12 | if (array[mid] == target) {
13 | return mid;
14 | } else if (array[mid] < target) {
15 | start = mid + 1;
16 | } else {
17 | end = mid - 1;
18 | }
19 | }
20 | return -1;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/closest/closest/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.closest.closest;
2 |
3 | public class Solution {
4 | public int closest(int[] array, int target) {
5 | if (array == null || array.length == 0) {
6 | return -1;
7 | }
8 | int left = 0;
9 | int right = array.length - 1;
10 | while (left + 1 < right) {
11 | int mid = left + (right - left) / 2;
12 | if (array[mid] == target) {
13 | return mid;
14 | } else if (array[mid] < target) {
15 | left = mid;
16 | } else {
17 | right = mid;
18 | }
19 | }
20 | if (Math.abs(array[left] - target) < Math.abs(array[right] - target)) {
21 | return left;
22 | }
23 | return right;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/closest/kclosest/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.closest.kclosest;
2 |
3 | public class Solution {
4 | public int[] kClosest(int[] array, int target, int k) {
5 | if (array == null || array.length == 0 || k < 0 || k > array.length) {
6 | return new int[] {};
7 | }
8 | int left = 0;
9 | int right = array.length - 1;
10 | while (left + 1 < right) {
11 | int mid = left + (right - left) / 2;
12 | if (array[mid] > target) {
13 | right = mid;
14 | } else {
15 | left = mid;
16 | }
17 | }
18 | int[] result = new int[k];
19 | int index = 0;
20 | while (index < k && left >= 0 && right < array.length) {
21 | if (Math.abs(array[left] - target) <= Math.abs(array[right] - target)) {
22 | result[index++] = array[left--];
23 | } else {
24 | result[index++] = array[right++];
25 | }
26 | }
27 | while (index < k && right < array.length) {
28 | result[index++] = array[right++];
29 | }
30 | while (index < k && left >= 0) {
31 | result[index++] = array[left--];
32 | }
33 | return result;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/occurrence/first/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.occurrence.first;
2 |
3 | public class Solution {
4 | public int firstOccur(int[] array, int target) {
5 | if (array == null || array.length == 0) {
6 | return -1;
7 | }
8 | int start = 0;
9 | int end = array.length - 1;
10 | while (start + 1 < end) {
11 | int mid = start + (end - start) / 2;
12 | if (array[mid] < target) {
13 | start = mid;
14 | } else {
15 | end = mid;
16 | }
17 | }
18 | if (array[start] == target) {
19 | return start;
20 | } else if (array[end] == target) {
21 | return end;
22 | }
23 | return -1;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/occurrence/last/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.occurrence.last;
2 |
3 | public class Solution {
4 | public int lastOccur(int[] array, int target) {
5 | if (array == null || array.length == 0) {
6 | return -1;
7 | }
8 | int start = 0;
9 | int end = array.length - 1;
10 | while (start + 1 < end) {
11 | int mid = start + (end - start) / 2;
12 | if (array[mid] > target) {
13 | end = mid;
14 | } else {
15 | start = mid;
16 | }
17 | }
18 | if (array[end] == target) {
19 | return end;
20 | } else if (array[start] == target) {
21 | return start;
22 | }
23 | return -1;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/search/findminimuminrotatedsortedarray/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.search.findminimuminrotatedsortedarray;
2 |
3 | public class Solution {
4 | public int findMin(int[] nums) {
5 | if (nums == null || nums.length == 0) {
6 | return -1;
7 | }
8 | int start = 0;
9 | int end = nums.length - 1;
10 | if (nums[start] < nums[end]) {
11 | return nums[start];
12 | }
13 | while (start + 1 < end) {
14 | int mid = start + (end - start) / 2;
15 | if (nums[mid] > nums[mid + 1]) {
16 | return nums[mid + 1];
17 | } else if (nums[mid] < nums[mid - 1]) {
18 | return nums[mid];
19 | } else if (nums[mid] > nums[0]) {
20 | start = mid + 1;
21 | } else {
22 | end = mid - 1;
23 | }
24 | }
25 | return nums[start] < nums[end] ? nums[start] : nums[end];
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/search/searchinsortedmatrixi/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.search.searchinsortedmatrixi;
2 |
3 | public class Solution {
4 | public int[] search(int[][] matrix, int target) {
5 | if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
6 | return new int[] { -1, -1 };
7 | }
8 |
9 | int m = matrix.length;
10 | int n = matrix[0].length;
11 |
12 | int start = 0;
13 | int end = m * n - 1;
14 | while (start <= end) {
15 | int mid = start + (end - start) / 2;
16 | int row = mid / n;
17 | int col = mid % n;
18 | if (matrix[row][col] == target) {
19 | return new int[] { row, col };
20 | } else if (matrix[row][col] < target) {
21 | start = mid + 1;
22 | } else {
23 | end = mid - 1;
24 | }
25 | }
26 | return new int[] { -1, -1 };
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/search/searchinunknownsizedsortedarray/Dictionary.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.search.searchinunknownsizedsortedarray;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * For simplicity, a Dictionary class is created directly instead of
8 | * implementation of a Dictionary interface
9 | */
10 | class Dictionary {
11 | /**
12 | * Use an ArrayList to mimic the function
13 | */
14 | private List dict;
15 |
16 | public Dictionary(List dictionary) {
17 | this.dict = new ArrayList<>(dictionary);
18 | }
19 |
20 | public Integer get(int index) {
21 | if (dict == null || index > dict.size() - 1) {
22 | return null;
23 | }
24 | return dict.get(index);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarysearch/search/searchinunknownsizedsortedarray/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.search.searchinunknownsizedsortedarray;
2 |
3 | /**
4 | * You do not need to implement the Dictionary interface. You can use it
5 | * directly, the implementation is provided when testing your solution.
6 | */
7 | public class Solution {
8 | public int search(Dictionary dict, int target) {
9 | if (dict == null || dict.get(0) == null) {
10 | return -1;
11 | }
12 | int start = 0;
13 | int end = 1;
14 | while (end < Integer.MAX_VALUE / 2 && dict.get(end) != null && dict.get(end) < target) {
15 | start = end + 1;
16 | end *= 2;
17 | }
18 | while (start <= end) {
19 | int mid = start + (end - start) / 2;
20 | if (dict.get(mid) == null) {
21 | end = mid - 1;
22 | continue;
23 | }
24 | if (dict.get(mid) == target) {
25 | return mid;
26 | } else if (dict.get(mid) < target) {
27 | start = mid + 1;
28 | } else {
29 | end = mid - 1;
30 | }
31 | }
32 | return -1;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarytree/bst/search/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.bst.search;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | public class Solution {
6 |
7 | /**
8 | * Given a Binary Search Tree, look for the node with a target key Recursive
9 | * method
10 | *
11 | * @param root The root of the given BST
12 | * @param key The value of the target key
13 | * @return The node with the target key. Or null if no such node in the tree
14 | */
15 | public TreeNode search(TreeNode root, int key) {
16 | if (root == null || root.key == key) {
17 | return root;
18 | }
19 | return root.key > key ? search(root.left, key) : search(root.right, key);
20 | }
21 |
22 | /**
23 | * Given a Binary Search Tree, look for the node with a target key Iterative
24 | * method
25 | *
26 | * @param root The root of the given BST
27 | * @param key The value of the target key
28 | * @return The node with the target key. Or null if no such node in the tree
29 | */
30 | public TreeNode iterativeSearch(TreeNode root, int key) {
31 | // Write your solution here
32 | // Corner case
33 | if (root == null) {
34 | return null;
35 | }
36 | while (root != null) {
37 | if (root.key == key) {
38 | return root;
39 | } else if (root.key > key) {
40 | root = root.left;
41 | } else {
42 | root = root.right;
43 | }
44 | }
45 | return null;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarytree/bst/validbst/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.bst.validbst;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | public class Solution {
6 |
7 | public boolean isBST(TreeNode root) {
8 | if (root == null) {
9 | return true;
10 | }
11 | return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
12 | }
13 |
14 | private boolean isValidBST(TreeNode root, int min, int max) {
15 | if (root == null) {
16 | return true;
17 | }
18 | if (root.key <= min || root.key >= max) {
19 | return false;
20 | }
21 | return (
22 | isValidBST(root.left, min, root.key) &&
23 | isValidBST(root.right, root.key, max)
24 | );
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarytree/general/symmetric/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.general.symmetric;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | public class Solution {
6 |
7 | public boolean isSymmetric(TreeNode root) {
8 | if (root == null) {
9 | return true;
10 | }
11 | return isSymmetricBinaryTree(root.left, root.right);
12 | }
13 |
14 | private boolean isSymmetricBinaryTree(TreeNode left, TreeNode right) {
15 | if (left == null && right == null) {
16 | return true;
17 | } else if (left == null || right == null) {
18 | return false;
19 | } else if (left.key != right.key) {
20 | return false;
21 | }
22 | return (
23 | isSymmetricBinaryTree(left.left, right.right) &&
24 | isSymmetricBinaryTree(right.left, left.right)
25 | );
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarytree/general/tweaked/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.general.tweaked;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | public class Solution {
6 |
7 | public boolean isTweakedIdentical(TreeNode one, TreeNode two) {
8 | if (one == null && two == null) {
9 | return true;
10 | } else if (one == null || two == null) {
11 | return false;
12 | } else if (one.key != two.key) {
13 | return false;
14 | }
15 | return (
16 | isTweakedIdentical(one.left, two.right) &&
17 | isTweakedIdentical(one.right, two.left) ||
18 | isTweakedIdentical(one.left, two.left) &&
19 | isTweakedIdentical(one.right, two.right)
20 | );
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarytree/path/sumi/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.path.sumi;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | public class Solution {
6 |
7 | private static class SingletonHolder {
8 |
9 | private static final Solution INSTANCE = new Solution();
10 | }
11 |
12 | public static Solution getInstance() {
13 | return SingletonHolder.INSTANCE;
14 | }
15 |
16 | /**
17 | * Determine if a binary tree has a root-to-leaf path that sums up to a target
18 | * number
19 | *
20 | * @param root the root of the given binary tree
21 | * @param target the target sum
22 | * @return whether there exists such a root-to-leaf path
23 | */
24 | public boolean exist(TreeNode root, int target) {
25 | if (root == null) {
26 | return false;
27 | }
28 | if (root.left == null && root.right == null) {
29 | return root.key == target;
30 | }
31 | return (
32 | exist(root.left, target - root.key) ||
33 | exist(root.right, target - root.key)
34 | );
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarytree/traversal/inorder/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.traversal.inorder;
2 |
3 | import coollime.common.objects.TreeNode;
4 | import java.util.ArrayDeque;
5 | import java.util.ArrayList;
6 | import java.util.Deque;
7 | import java.util.List;
8 |
9 | public class Solution {
10 |
11 | public List inOrder(TreeNode root) {
12 | List result = new ArrayList<>();
13 | if (root == null) {
14 | return result;
15 | }
16 | List left = inOrder(root.left);
17 | List right = inOrder(root.right);
18 | result.addAll(left);
19 | result.add(root.key);
20 | result.addAll(right);
21 | return result;
22 | }
23 |
24 | public List iterativeInOrder(TreeNode root) {
25 | List result = new ArrayList<>();
26 | if (root == null) {
27 | return result;
28 | }
29 | Deque stack = new ArrayDeque<>();
30 | TreeNode current = root;
31 | while (current != null || !stack.isEmpty()) {
32 | if (current != null) {
33 | // When the node does have a left child, go left
34 | stack.offerFirst(current);
35 | current = current.left;
36 | } else {
37 | // When the node does not have a left child
38 | // current stack top is the node: add the key to result and go right
39 | current = stack.pollFirst();
40 | result.add(current.key);
41 | current = current.right;
42 | }
43 | }
44 | return result;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/binarytree/traversal/preorder/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.traversal.preorder;
2 |
3 | import coollime.common.objects.TreeNode;
4 | import java.util.ArrayList;
5 | import java.util.Deque;
6 | import java.util.LinkedList;
7 | import java.util.List;
8 |
9 | public class Solution {
10 |
11 | public List preOrder(TreeNode root) {
12 | List result = new ArrayList<>();
13 | if (root == null) {
14 | return result;
15 | }
16 | // Use a stack to store the left/right children of the root such that they can
17 | // be trace back later
18 | Deque stack = new LinkedList<>();
19 | stack.offerFirst(root);
20 | while (!stack.isEmpty()) {
21 | TreeNode node = stack.pollFirst();
22 | result.add(node.key);
23 | // Push the right child first such that it will be visit later than the left
24 | // child
25 | if (node.right != null) {
26 | stack.offerFirst(node.right);
27 | }
28 | if (node.left != null) {
29 | stack.offerFirst(node.left);
30 | }
31 | }
32 | return result;
33 | }
34 |
35 | public List recursivePreOrder(TreeNode root) {
36 | List result = new ArrayList<>();
37 | if (root == null) {
38 | return result;
39 | }
40 | List left = preOrder(root.left);
41 | List right = preOrder(root.right);
42 | result.add(root.key);
43 | result.addAll(left);
44 | result.addAll(right);
45 | return result;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/linkedlist/checkiflinkedlisthasacycyle/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.checkiflinkedlisthasacycyle;
2 |
3 | import coollime.common.objects.ListNode;
4 |
5 | public class Solution {
6 |
7 | public boolean hasCycle(ListNode head) {
8 | if (head == null || head.next == null) {
9 | return false;
10 | }
11 | ListNode slow = head;
12 | ListNode fast = head.next;
13 | while (fast != null && fast.next != null) {
14 | if (slow == fast) {
15 | return true;
16 | }
17 | slow = slow.next;
18 | fast = fast.next.next;
19 | }
20 | return false;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/linkedlist/cyclenodeinlinkedlist/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.cyclenodeinlinkedlist;
2 |
3 | import coollime.common.objects.ListNode;
4 |
5 | public class Solution {
6 |
7 | /**
8 | * Find the start of the cycle in a linked list
9 | *
10 | * @param head The head of the given linked list
11 | * @return The starting node of the cycle in the list
12 | */
13 | public ListNode cycleNode(ListNode head) {
14 | if (head == null || head.next == null) {
15 | return null;
16 | }
17 | ListNode slow = head;
18 | ListNode fast = head;
19 | boolean hasCycle = false;
20 | while (fast != null && fast.next != null) {
21 | slow = slow.next;
22 | fast = fast.next.next;
23 | if (slow == fast) {
24 | hasCycle = true;
25 | break;
26 | }
27 | }
28 | // Proceed only if there is a cycle
29 | if (!hasCycle) {
30 | return null;
31 | }
32 | // distance(head, start) == distance(meet, start)
33 | // So, let slow moves one step at a time from the head
34 | // let fast moves one step at a time from the meeting point
35 | // They will meet at the starting point of the cycle
36 | slow = head;
37 | while (slow != fast) {
38 | slow = slow.next;
39 | fast = fast.next;
40 | }
41 | return slow;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/linkedlist/insertinsortedlinkedlist/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.insertinsortedlinkedlist;
2 |
3 | import coollime.common.objects.ListNode;
4 |
5 | public class Solution {
6 |
7 | public ListNode insert(ListNode head, int value) {
8 | ListNode newNode = new ListNode(value);
9 | // Case 1: insert before head
10 | if (head == null || head.value >= value) {
11 | newNode.next = head;
12 | return newNode;
13 | }
14 | // Case 2: insert in the middle/tail
15 | ListNode current = head;
16 | // Skip all the nodes whose values are less than (NOT equal to) value
17 | while (current.next != null && current.next.value < value) {
18 | current = current.next;
19 | }
20 | // current is either the tail or smaller than next, insert the new node after
21 | // current
22 | newNode.next = current.next;
23 | current.next = newNode;
24 | return head;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/linkedlist/mergetwosortedlinkedlists/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.mergetwosortedlinkedlists;
2 |
3 | import coollime.common.objects.ListNode;
4 |
5 | public class Solution {
6 |
7 | public ListNode merge(ListNode one, ListNode two) {
8 | if (one == null) {
9 | return two;
10 | } else if (two == null) {
11 | return one;
12 | }
13 | ListNode head = new ListNode(0);
14 | ListNode current = head;
15 | ListNode oneCurr = one;
16 | ListNode twoCurr = two;
17 | // Traversing both lists and move the smaller pointer after each comparison
18 | while (oneCurr != null && twoCurr != null) {
19 | if (oneCurr.value < twoCurr.value) {
20 | current.next = oneCurr;
21 | oneCurr = oneCurr.next;
22 | } else {
23 | current.next = twoCurr;
24 | twoCurr = twoCurr.next;
25 | }
26 | current = current.next;
27 | }
28 | // One of the two lists may still have elements left
29 | if (oneCurr != null) {
30 | current.next = oneCurr;
31 | } else if (twoCurr != null) {
32 | current.next = twoCurr;
33 | }
34 | return head.next;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/linkedlist/middlenodeoflinkedlist/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.middlenodeoflinkedlist;
2 |
3 | import coollime.common.objects.ListNode;
4 |
5 | public class Solution {
6 |
7 | public ListNode middleNode(ListNode head) {
8 | if (head == null || head.next == null) {
9 | return head;
10 | }
11 | ListNode slow = head;
12 | ListNode fast = head.next;
13 | while (fast != null && fast.next != null) {
14 | slow = slow.next;
15 | fast = fast.next.next;
16 | }
17 | return slow;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/linkedlist/partitionlinkedlist/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.partitionlinkedlist;
2 |
3 | import coollime.common.objects.ListNode;
4 |
5 | public class Solution {
6 |
7 | public ListNode partition(ListNode head, int target) {
8 | if (head == null || head.next == null) {
9 | return head;
10 | }
11 | ListNode smallDummy = new ListNode(0);
12 | ListNode smallCurr = smallDummy;
13 | ListNode largeDummy = new ListNode(0);
14 | ListNode largeCurr = largeDummy;
15 | ListNode current = head;
16 | // Compare the node values to the target and move the smaller pointer like what
17 | // is done in quick sort
18 | while (current != null) {
19 | if (current.value < target) {
20 | smallCurr.next = current;
21 | smallCurr = smallCurr.next;
22 | } else {
23 | largeCurr.next = current;
24 | largeCurr = largeCurr.next;
25 | }
26 | current = current.next;
27 | }
28 | // Concatenate the two lists
29 | // smallHead -> ... smallCurr -> largeHead -> largeCurr -> null
30 | smallCurr.next = largeDummy.next;
31 | largeCurr.next = null;
32 | return smallDummy.next;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/linkedlist/reverselinkedlist/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.reverselinkedlist;
2 |
3 | import coollime.common.objects.ListNode;
4 |
5 | public class Solution {
6 |
7 | /**
8 | * Reverse a linked list iteratively
9 | *
10 | * @param head - the head node of the linked list
11 | * @return the head of the reversed linked list
12 | */
13 | public ListNode reverse(ListNode head) {
14 | if (head == null || head.next == null) {
15 | return head;
16 | }
17 | ListNode previous = null;
18 | ListNode current = head;
19 | while (current != null) {
20 | ListNode next = current.next;
21 | current.next = previous;
22 | previous = current;
23 | current = next;
24 | }
25 | return previous;
26 | }
27 |
28 | /**
29 | * Reverse a linked list recursively
30 | *
31 | * @param head - the head node of the linked list
32 | * @return - the head of the reversed linked list
33 | */
34 | public ListNode reverseRecursively(ListNode head) {
35 | // Base case: when we reach the last node in the original order
36 | if (head == null || head.next == null) {
37 | // The real case happens only when head.next == null
38 | return head;
39 | }
40 | ListNode reversedHead = reverse(head.next);
41 | head.next.next = head;
42 | head.next = null;
43 | return reversedHead;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/queueandstack/queuebytwostacks/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.queueandstack.queuebytwostacks;
2 |
3 | import java.util.Deque;
4 | import java.util.LinkedList;
5 |
6 | public class Solution {
7 | // Set up two stacks
8 | private Deque stackOne;
9 | private Deque stackTwo;
10 |
11 | public Solution() {
12 | // The 1st stack is used only when we need to add in new elements
13 | // The 2nd stack is used only when we need to poll or peek the first element
14 | stackOne = new LinkedList<>();
15 | stackTwo = new LinkedList<>();
16 | }
17 |
18 | public Integer poll() {
19 | // When there are elements in the 2nd stack --> poll directly
20 | // Otherwise, transfer all elements from the 1st stack to the 2nd stack and poll
21 | if (stackTwo.isEmpty()) {
22 | transferStack();
23 | }
24 | return stackTwo.pollFirst();
25 | }
26 |
27 | public void offer(int element) {
28 | stackOne.addFirst(element);
29 | }
30 |
31 | public Integer peek() {
32 | if (stackTwo.isEmpty()) {
33 | transferStack();
34 | }
35 | return stackTwo.peekFirst();
36 | }
37 |
38 | public int size() {
39 | return stackOne.size() + stackTwo.size();
40 | }
41 |
42 | public boolean isEmpty() {
43 | return stackOne.isEmpty() && stackTwo.isEmpty();
44 | }
45 |
46 | private void transferStack() {
47 | while (!stackOne.isEmpty()) {
48 | stackTwo.addFirst(stackOne.pollFirst());
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/queueandstack/stackwithmin/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.queueandstack.stackwithmin;
2 |
3 | import java.util.ArrayDeque;
4 | import java.util.Deque;
5 |
6 | public class Solution {
7 | private Deque stack;
8 | private Deque minStack;
9 |
10 | private class Element {
11 | int val;
12 | int size;
13 |
14 | private Element(int val, int size) {
15 | this.val = val;
16 | this.size = size;
17 | }
18 | }
19 |
20 | public Solution() {
21 | stack = new ArrayDeque<>();
22 | minStack = new ArrayDeque<>();
23 | }
24 |
25 | public int pop() {
26 | if (stack.isEmpty()) {
27 | return -1;
28 | }
29 | if (stack.size() == minStack.peekFirst().size) {
30 | minStack.pollFirst();
31 | }
32 | return stack.pollFirst();
33 | }
34 |
35 | public void push(int element) {
36 | stack.offerFirst(element);
37 | if (minStack.isEmpty() || element < minStack.peekFirst().val) {
38 | minStack.offerFirst(new Element(element, stack.size()));
39 | }
40 | }
41 |
42 | public int top() {
43 | return stack.isEmpty() ? -1 : stack.peekFirst();
44 | }
45 |
46 | public int min() {
47 | return minStack.isEmpty() ? -1 : minStack.peekFirst().val;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/recursion/atothepowerofb/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.atothepowerofb;
2 |
3 | public class Solution {
4 |
5 | public long power(int a, int b) {
6 | if (b == 0) {
7 | return 1;
8 | }
9 | // Divide b by 1/2 each time and do result * result
10 | long half = power(a, b / 2);
11 | // We need to differentiate the situations where b is odd or even
12 | if (b % 2 == 0) {
13 | return half * half;
14 | }
15 | return half * half * a;
16 | }
17 |
18 | /**
19 | * There are two simpler but more naive ways to do this problem
20 | **/
21 | public long naivePower(int a, int b) {
22 | // Method 1: directly computation one level at a time
23 | // if (b == 0) {
24 | // return 1;
25 | // }
26 | // return a * power(a, b - 1);
27 |
28 | // Method 2: use a mid point (b/2) and compute the left and right halves
29 | if (b == 0) {
30 | return 1;
31 | } else if (b == 1) {
32 | return a;
33 | }
34 | int mid = b / 2;
35 | return power(a, mid) * power(a, b - mid);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/recursion/binarytreepathsumtotargetiii/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.binarytreepathsumtotargetiii;
2 |
3 | import coollime.common.objects.TreeNode;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | public class Solution {
8 |
9 | public boolean exist(TreeNode root, int target) {
10 | // Write your solution here
11 | // Base case: root is null
12 | if (root == null) {
13 | return false;
14 | }
15 | Set prefixSums = new HashSet<>();
16 | prefixSums.add(0);
17 | return existPath(root, prefixSums, 0, target);
18 | }
19 |
20 | private boolean existPath(
21 | TreeNode root,
22 | Set prefixSums,
23 | int currentSum,
24 | int target
25 | ) {
26 | currentSum += root.key;
27 | // When the current_path_sum - target is in the path's prefixSum set
28 | // there is such a path
29 | if (prefixSums.contains(currentSum - target)) {
30 | return true;
31 | }
32 | boolean needRemove = prefixSums.add(currentSum);
33 | if (
34 | root.left != null && existPath(root.left, prefixSums, currentSum, target)
35 | ) {
36 | return true;
37 | }
38 | if (
39 | root.right != null &&
40 | existPath(root.right, prefixSums, currentSum, target)
41 | ) {
42 | return true;
43 | }
44 | if (needRemove) {
45 | prefixSums.remove(currentSum);
46 | }
47 | return false;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/recursion/fibonaccinumber/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.fibonaccinumber;
2 |
3 | public class Solution {
4 |
5 | public long fibonacci(int K) {
6 | if (K == 0) {
7 | return 0;
8 | } else if (K == 1) {
9 | return 1;
10 | }
11 | return fibonacci(K - 1) + fibonacci(K - 2);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/recursion/lowestcommonancestori/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.lowestcommonancestori;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | /**
6 | * LowestCommonAncestorI
7 | *
8 | * @author meng
9 | * @date 1/23/19
10 | */
11 | public class Solution {
12 |
13 | /**
14 | * Find the lowest common ancestor of node one and two under current binary tree
15 | * node root
16 | *
17 | * @param root the root of the tree
18 | * @param one the first child node
19 | * @param two the second child node
20 | * @return the lowest common ancestor of one and two
21 | */
22 | public TreeNode lowestCommonAncestor(
23 | TreeNode root,
24 | TreeNode one,
25 | TreeNode two
26 | ) {
27 | if (root == null || root == one || root == two) {
28 | return root;
29 | }
30 | TreeNode left = lowestCommonAncestor(root.left, one, two);
31 | TreeNode right = lowestCommonAncestor(root.right, one, two);
32 | if (left != null && right != null) {
33 | return root;
34 | }
35 | if (left != null) {
36 | return left;
37 | } else if (right != null) {
38 | return right;
39 | }
40 | return null;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/recursion/maximumpathsumbinarytreeii/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.maximumpathsumbinarytreeii;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | public class Solution {
6 |
7 | public int maxPathSum(TreeNode root) {
8 | if (root == null) {
9 | return 0;
10 | }
11 | int[] max = new int[] { Integer.MIN_VALUE };
12 | findMaxPathSum(root, max);
13 | return max[0];
14 | }
15 |
16 | private int findMaxPathSum(TreeNode root, int[] max) {
17 | // Base case: when reaching a null
18 | if (root == null) {
19 | return 0;
20 | }
21 | // Ask the left and right subtrees for their max path sum
22 | int left = findMaxPathSum(root.left, max);
23 | int right = findMaxPathSum(root.right, max);
24 | // Treat any negative result as 0 since it will not increase our result
25 | left = left < 0 ? 0 : left;
26 | right = right < 0 ? 0 : right;
27 | // Update max
28 | max[0] = Math.max(max[0], left + right + root.key);
29 | // Return the larger single path sum to the parent
30 | return Math.max(left, right) + root.key;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/recursion/maximumpathsumbinarytreeiii/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.maximumpathsumbinarytreeiii;
2 |
3 | import coollime.common.objects.TreeNode;
4 |
5 | public class Solution {
6 |
7 | public int maxPathSum(TreeNode root) {
8 | if (root == null) {
9 | return 0;
10 | }
11 | // Maintain a global variable to keep track of the max path sum
12 | int[] max = new int[] { Integer.MIN_VALUE };
13 | findMaxPathSum(root, max);
14 | return max[0];
15 | }
16 |
17 | private int findMaxPathSum(TreeNode root, int[] max) {
18 | if (root == null) {
19 | return 0;
20 | }
21 | int left = findMaxPathSum(root.left, max);
22 | int right = findMaxPathSum(root.right, max);
23 | // In the current level, compare the two sums and the root's value
24 | // Return the largest one to the parent
25 | int larger = Integer.MIN_VALUE;
26 | // Directly return the root's key if it has no children
27 | if (root.left == null && root.right == null) {
28 | return root.key;
29 | } else if (root.left == null) {
30 | larger = right;
31 | } else if (root.right == null) {
32 | larger = left;
33 | } else {
34 | larger = Math.max(left, right);
35 | }
36 | // Update the global max only when there are sub-paths from either child
37 | max[0] = Math.max(max[0], larger);
38 | // Return the largest value among left, right, and the root
39 | return root.key > larger ? root.key : root.key + larger;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/sortingalgorithms/movezerostotheendi/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.sortingalgorithms.movezerostotheendi;
2 |
3 | public class Solution {
4 |
5 | // This method does not preserve the relative position of the elements
6 | public int[] moveZero(int[] array) {
7 | if (array == null || array.length == 0) {
8 | return array;
9 | }
10 | int left = 0;
11 | int right = array.length - 1;
12 | while (left < right) {
13 | if (array[left] != 0) {
14 | left++;
15 | } else if (array[right] == 0) {
16 | right--;
17 | } else {
18 | array[left++] = array[right];
19 | array[right--] = 0;
20 | }
21 | }
22 | return array;
23 | }
24 |
25 | // This method keeps the relative position of the elements after switching.
26 | public int[] moveZeroPreservePosition(int[] array) {
27 | if (array == null || array.length == 0) {
28 | return array;
29 | }
30 | int left = 0;
31 | int right = 0;
32 | while (right < array.length) {
33 | if (array[right] != 0) {
34 | int temp = array[left];
35 | array[left] = array[right];
36 | array[right] = temp;
37 | left++;
38 | }
39 | right++;
40 | }
41 | return array;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/sortingalgorithms/quicksort/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.sortingalgorithms.quicksort;
2 |
3 | public class Solution {
4 |
5 | public int[] quickSort(int[] array) {
6 | if (array == null || array.length == 0) {
7 | return array;
8 | }
9 | sortArray(array, 0, array.length - 1);
10 | return array;
11 | }
12 |
13 | private void sortArray(int[] array, int start, int end) {
14 | if (start >= end) {
15 | return;
16 | }
17 | int pivotIndex = partitionArray(array, start, end);
18 | sortArray(array, start, pivotIndex - 1);
19 | sortArray(array, pivotIndex + 1, end);
20 | }
21 |
22 | private int partitionArray(int[] array, int start, int end) {
23 | int pivotIndex = (int) Math.random() * (end - start + 1) + start;
24 | int pivot = array[pivotIndex];
25 | swap(array, pivotIndex, end);
26 | int left = start;
27 | int right = end - 1;
28 | while (left <= right) {
29 | if (array[left] < pivot) {
30 | left++;
31 | } else if (array[right] > pivot) {
32 | right--;
33 | } else {
34 | swap(array, left++, right--);
35 | }
36 | }
37 | swap(array, left, end);
38 | return left;
39 | }
40 |
41 | private void swap(int[] array, int indexOne, int indexTwo) {
42 | int temp = array[indexOne];
43 | array[indexOne] = array[indexTwo];
44 | array[indexTwo] = temp;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/sortingalgorithms/rainbowsort/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.sortingalgorithms.rainbowsort;
2 |
3 | public class Solution {
4 |
5 | /**
6 | * Given an array that has only three types of elements (-1, 0, and 1) in it,
7 | * sort the elements such that elements of the same group are grouped together
8 | *
9 | * @param array The input array
10 | * @return The array with the elements grouped accordingly
11 | */
12 | public int[] rainbowSort(int[] array) {
13 | if (array == null || array.length <= 1) {
14 | return array;
15 | }
16 | int i = 0;
17 | int j = 0;
18 | int k = array.length - 1;
19 | while (j <= k) {
20 | if (array[j] == -1) {
21 | swap(array, i++, j++);
22 | } else if (array[j] == 0) {
23 | j++;
24 | } else if (array[j] == 1) {
25 | swap(array, j, k--);
26 | }
27 | }
28 | return array;
29 | }
30 |
31 | private void swap(int[] array, int left, int right) {
32 | int temp = array[left];
33 | array[left] = array[right];
34 | array[right] = temp;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/coollime/src/main/java/coollime/sortingalgorithms/selectionsort/Solution.java:
--------------------------------------------------------------------------------
1 | package coollime.sortingalgorithms.selectionsort;
2 |
3 | public class Solution {
4 |
5 | public int[] sort(int[] array) {
6 | if (array == null || array.length == 0) {
7 | return array;
8 | }
9 | for (int i = 0; i < array.length - 1; i++) {
10 | int minIndex = i;
11 | for (int j = i + 1; j < array.length; j++) {
12 | if (array[j] < array[minIndex]) {
13 | minIndex = j;
14 | }
15 | }
16 | if (i != minIndex) {
17 | int temp = array[i];
18 | array[i] = array[minIndex];
19 | array[minIndex] = temp;
20 | }
21 | }
22 | return array;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/AppTest.java:
--------------------------------------------------------------------------------
1 | package coollime;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertTrue;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest {
11 | /**
12 | * Rigorous Test :-)
13 | */
14 | @Test
15 | public void shouldAnswerWithTrue() {
16 | assertTrue(true);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarysearch/classic/ClassicalBinarySearchTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.classic;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | class ClassicalBinarySearchTest {
9 | private static Solution sut;
10 | int[] arrayOne;
11 | int[] arrayTwo;
12 |
13 | @BeforeEach
14 | void setUp() {
15 | sut = new Solution();
16 | arrayOne = new int[] { 1, 2, 3, 4, 5 };
17 | arrayTwo = new int[] { 1, 2, 2, 2, 3, 4 };
18 | }
19 |
20 | @Test
21 | void shouldNotFindTheTargetWhenTheArrayIsNull() {
22 | int result = sut.binarySearch(null, 0);
23 | assertEquals(-1, result);
24 | }
25 |
26 | @Test
27 | void shouldNotFindTheTargetWhenTheArrayIsEmpty() {
28 | int result = sut.binarySearch(new int[] {}, 0);
29 | assertEquals(-1, result);
30 | }
31 |
32 | @Test
33 | void shouldNotFindTheTargetWhenItIsNotPresentInTheArray() {
34 | int result = sut.binarySearch(arrayOne, 6);
35 | assertEquals(-1, result);
36 | }
37 |
38 | @Test
39 | void shouldFindTheTargetWhenItIsPresentInTheArray() {
40 | int result = sut.binarySearch(arrayOne, 3);
41 | assertEquals(2, result);
42 | result = sut.binarySearch(arrayTwo, 2);
43 | assertEquals(2, result);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarysearch/closest/kclosest/KClosestInSortedArrayTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.closest.kclosest;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4 |
5 | import org.junit.jupiter.api.BeforeAll;
6 | import org.junit.jupiter.api.Test;
7 |
8 | class KClosestInSortedArrayTest {
9 | private static Solution sut;
10 |
11 | @BeforeAll
12 | static void setInstance() {
13 | sut = new Solution();
14 | }
15 |
16 | @Test
17 | void shouldNotFindTheResultWhenTheArrayIsNull() {
18 | int[] result = sut.kClosest(null, 1, 1);
19 | assertArrayEquals(new int[] {}, result);
20 | }
21 |
22 | @Test
23 | void shouldNotFindTheResultWhenTheArrayIsEmpty() {
24 | int[] result = sut.kClosest(new int[] {}, 1, 1);
25 | assertArrayEquals(new int[] {}, result);
26 | }
27 |
28 | @Test
29 | void shouldFindTheResult() {
30 | int[] result = sut.kClosest(new int[] { 1, 2, 3 }, 2, 3);
31 | assertArrayEquals(new int[] { 2, 1, 3 }, result);
32 |
33 | result = sut.kClosest(new int[] { 1, 4, 6, 8 }, 3, 3);
34 | assertArrayEquals(new int[] { 4, 1, 6 }, result);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarysearch/occurrence/first/FirstOccurrenceTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.occurrence.first;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | class FirstOccurrenceTest {
9 | private static Solution sut;
10 |
11 | @BeforeEach
12 | void setUp() {
13 | sut = new Solution();
14 | }
15 |
16 | @Test
17 | void shouldNotFindTargetWhenTheInputIsNull() {
18 | int result = sut.firstOccur(null, 0);
19 | assertEquals(-1, result);
20 | }
21 |
22 | @Test
23 | void shouldNotFindTargetWhenTheInputIsEmpty() {
24 | int result = sut.firstOccur(new int[] {}, 0);
25 | assertEquals(-1, result);
26 | }
27 |
28 | @Test
29 | void shouldNotFindTheTargetWhenItIsNotInTheArray() {
30 | int result = sut.firstOccur(new int[] { 1, 2, 3 }, 4);
31 | assertEquals(-1, result);
32 | }
33 |
34 | @Test
35 | void shouldFindTheTargetWhenItIsUnique() {
36 | int result = sut.firstOccur(new int[] { 1, 2, 3 }, 2);
37 | assertEquals(1, result);
38 | }
39 |
40 | @Test
41 | void shouldFindTheFirstTargetWhenThereAreMultipleOccurrences() {
42 | int result = sut.firstOccur(new int[] { 1, 2, 2, 2, 3 }, 2);
43 | assertEquals(1, result);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarysearch/occurrence/last/LastOccurrenceTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.occurrence.last;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.BeforeAll;
6 | import org.junit.jupiter.api.Test;
7 |
8 | class LastOccurrenceTest {
9 | private static Solution sut;
10 |
11 | @BeforeAll
12 | static void setUp() {
13 | sut = new Solution();
14 | }
15 |
16 | @Test
17 | void shouldNotFindTheTargetWhenTheArrayIsNull() {
18 | int result = sut.lastOccur(null, 0);
19 | assertEquals(-1, result);
20 | }
21 |
22 | @Test
23 | void shouldNotFindTheTargetWhenTheArrayIsEmpty() {
24 | int result = sut.lastOccur(new int[] {}, 0);
25 | assertEquals(-1, result);
26 | }
27 |
28 | @Test
29 | void shouldNotFindTheTargetWhenItIsNotPresentInTheArray() {
30 | int result = sut.lastOccur(new int[] { 1, 2, 3 }, 4);
31 | assertEquals(-1, result);
32 | }
33 |
34 | @Test
35 | void shouldFindTheUniqueTarget() {
36 | int result = sut.lastOccur(new int[] { 1, 2, 3 }, 2);
37 | assertEquals(1, result);
38 | }
39 |
40 | @Test
41 | void shouldFindTheLastOccurrenceWhenThereAreMultipleOccurrence() {
42 | int result = sut.lastOccur(new int[] { 1, 2, 2, 2, 3 }, 2);
43 | assertEquals(3, result);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarysearch/search/findminimuminrotatedsortedarray/FindMinimumInRotatedSortedArrayTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.search.findminimuminrotatedsortedarray;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | class FindMinimumInRotatedSortedArrayTest {
9 | private static Solution sut;
10 | private int[] nums;
11 |
12 | @BeforeEach
13 | void setUp() {
14 | sut = new Solution();
15 | nums = null;
16 | }
17 |
18 | @Test
19 | void shouldNotFindTheTargetWhenTheArrayIsNull() {
20 | int result = sut.findMin(nums);
21 | assertEquals(-1, result);
22 | }
23 |
24 | @Test
25 | void shouldNotFindTheTargetWhenTheArrayIsEmpty() {
26 | int result = sut.findMin(new int[] {});
27 | assertEquals(-1, result);
28 | }
29 |
30 | @Test
31 | void shouldFindTheMin() {
32 | nums = new int[] { 0 };
33 | assertEquals(0, sut.findMin(nums));
34 |
35 | nums = new int[] { 1, 2, 3, 4, 5 };
36 | assertEquals(1, sut.findMin(nums));
37 |
38 | nums = new int[] { 2, 3, 4, 5, 1 };
39 | assertEquals(1, sut.findMin(nums));
40 |
41 | nums = new int[] { 3, 4, 5, 1, 2 };
42 | assertEquals(1, sut.findMin(nums));
43 |
44 | nums = new int[] { 5, 1, 2, 3, 4 };
45 | assertEquals(1, sut.findMin(nums));
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarysearch/search/searchinsortedmatrixi/SearchInSortedMatrixITest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarysearch.search.searchinsortedmatrixi;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4 |
5 | import org.junit.jupiter.api.BeforeAll;
6 | import org.junit.jupiter.api.Test;
7 |
8 | class SearchInSortedMatrixITest {
9 | private static Solution sut;
10 |
11 | @BeforeAll
12 | static void setUp() {
13 | sut = new Solution();
14 | }
15 |
16 | @Test
17 | void shouldNotFindTheTargetWhenTheArrayIsNull() {
18 | int[] result = sut.search(null, 0);
19 | assertArrayEquals(new int[] { -1, -1 }, result);
20 | }
21 |
22 | @Test
23 | void shouldNotFindTheTargetWhenTheArrayIsEmpty() {
24 | int[] result = sut.search(new int[][] {}, 0);
25 | assertArrayEquals(new int[] { -1, -1 }, result);
26 | }
27 |
28 | @Test
29 | void shouldNotFindTheTargetWhenItIsNotInTheInput() {
30 | int[][] matrix = new int[][] { { 1, 2, 3 }, { 4, 5, 7 }, { 8, 9, 10 } };
31 | int[] result = sut.search(matrix, 6);
32 | assertArrayEquals(new int[] { -1, -1 }, result);
33 | }
34 |
35 | @Test
36 | void shouldFindTheTarget() {
37 | int[][] matrix = new int[][] { { 1, 2, 3 }, { 4, 5, 7 }, { 8, 9, 10 } };
38 | int[] result = sut.search(matrix, 7);
39 | assertArrayEquals(new int[] { 1, 2 }, result);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarytree/bst/insert/InsertInBinarySearchTreeTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.bst.insert;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import coollime.common.objects.TreeNode;
6 | import java.util.Arrays;
7 | import org.junit.jupiter.api.BeforeEach;
8 | import org.junit.jupiter.api.Test;
9 |
10 | class InsertInBinarySearchTreeTest {
11 |
12 | private static Solution sut;
13 | private TreeNode root;
14 | private int key;
15 |
16 | @BeforeEach
17 | void setUp() {
18 | sut = new Solution();
19 | root = null;
20 | key = 0;
21 | }
22 |
23 | @Test
24 | void shouldInsertAsRootWhenTheTreeIsEmpty() {
25 | assertEquals(new TreeNode(key), sut.recursiveInsert(root, key));
26 | assertEquals(new TreeNode(key), sut.iterativeInsert(root, key));
27 | }
28 |
29 | @Test
30 | void shouldInsertTheNode() {
31 | root = new TreeNode(-1);
32 | TreeNode expected = TreeNode.buildTree(Arrays.asList(-1, null, 0));
33 | assertEquals(expected, sut.recursiveInsert(root, key));
34 | assertEquals(expected, sut.iterativeInsert(root, key));
35 |
36 | root = TreeNode.buildTree(Arrays.asList(5, 3, 8, 1, 4));
37 | key = 11;
38 | expected = TreeNode.buildTree(Arrays.asList(5, 3, 8, 1, 4, null, 11));
39 | assertEquals(expected, sut.recursiveInsert(root, key));
40 | assertEquals(expected, sut.iterativeInsert(root, key));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarytree/bst/search/SearchInBinarySearchTreeTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.bst.search;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertNull;
5 |
6 | import coollime.common.objects.TreeNode;
7 | import java.util.Arrays;
8 | import org.junit.jupiter.api.BeforeEach;
9 | import org.junit.jupiter.api.Test;
10 |
11 | class SearchInBinarySearchTreeTest {
12 |
13 | private static Solution sut;
14 | private TreeNode root;
15 |
16 | @BeforeEach
17 | void setUp() {
18 | sut = new Solution();
19 | root = null;
20 | }
21 |
22 | @Test
23 | void shouldNotFindAnyWhenTheTreeIsEmpty() {
24 | assertNull(sut.search(root, 0));
25 | assertNull(sut.iterativeSearch(root, 0));
26 | }
27 |
28 | @Test
29 | void shouldNotFindTheNodeWhenItIsNotInTheTree() {
30 | root = TreeNode.buildTree(Arrays.asList(5, 3, 8, 1, 4, null, 11));
31 | assertNull(sut.search(root, 0));
32 | assertNull(sut.iterativeSearch(root, 0));
33 |
34 | assertNull(sut.search(root, 10));
35 | assertNull(sut.iterativeSearch(root, 10));
36 | }
37 |
38 | @Test
39 | void shouldFindTheNodeWhenItIsInTheTree() {
40 | root = TreeNode.buildTree(Arrays.asList(5, 3, 8, 1, 4, null, 11));
41 | assertEquals(3, sut.search(root, 3).key);
42 | assertEquals(3, sut.iterativeSearch(root, 3).key);
43 |
44 | assertEquals(11, sut.search(root, 11).key);
45 | assertEquals(11, sut.iterativeSearch(root, 11).key);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarytree/general/balanced/CheckIfBinaryTreeIsBalancedTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.general.balanced;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import coollime.common.objects.TreeNode;
7 | import java.util.Arrays;
8 | import org.junit.jupiter.api.BeforeEach;
9 | import org.junit.jupiter.api.Test;
10 |
11 | class CheckIfBinaryTreeIsBalancedTest {
12 |
13 | private static Solution sut;
14 | private TreeNode root;
15 |
16 | @BeforeEach
17 | void setUp() {
18 | sut = new Solution();
19 | root = null;
20 | }
21 |
22 | @Test
23 | void shouldReturnTrueWhenTheTreeIsEmpty() {
24 | assertTrue(sut.isBalanced(root));
25 | }
26 |
27 | @Test
28 | void shouldReturnTrueWhenTheTreeHasOnlyOneNode() {
29 | root = new TreeNode(0);
30 | assertTrue(sut.isBalanced(root));
31 | }
32 |
33 | @Test
34 | void shouldReturnTrueWhenTheTreeIsBalanced() {
35 | // In-order build tree: [5, 3, 8, 1, 4, #, 11]
36 | // 5
37 | // / \
38 | // 3 8
39 | // / \ \
40 | // 1 4 11
41 | root = TreeNode.buildTree(Arrays.asList(5, 3, 8, 1, 4, null, 11));
42 | assertTrue(sut.isBalanced(root));
43 | }
44 |
45 | @Test
46 | void shouldReturnTrueWhenTheTreeIsNotBalanced() {
47 | // In-order build tree: [5, 3, null, 1, 4]
48 | // 5
49 | // /
50 | // 3
51 | // / \
52 | // 1 4
53 | root = TreeNode.buildTree(Arrays.asList(5, 3, null, 1, 4));
54 | assertFalse(sut.isBalanced(root));
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarytree/traversal/inorder/InorderTraversalOfBinaryTreeTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.traversal.inorder;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import coollime.common.objects.TreeNode;
6 | import java.util.Arrays;
7 | import java.util.Collections;
8 | import java.util.List;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class InorderTraversalOfBinaryTreeTest {
13 |
14 | private static Solution sut;
15 | private TreeNode root;
16 |
17 | @BeforeEach
18 | void setUp() {
19 | sut = new Solution();
20 | root = null;
21 | }
22 |
23 | @Test
24 | void shouldNotTraverseWhenTheTreeIsEmpty() {
25 | assertEquals(Collections.emptyList(), sut.inOrder(root));
26 | assertEquals(Collections.emptyList(), sut.iterativeInOrder(root));
27 | }
28 |
29 | @Test
30 | void shouldDoInOrderTraversal() {
31 | root = new TreeNode(0);
32 | assertEquals(Collections.singletonList(0), sut.inOrder(root));
33 | assertEquals(Collections.singletonList(0), sut.iterativeInOrder(root));
34 |
35 | // In-order build tree: [5, 3, 8, 1, 4, #, 11]
36 | // In-order result: [1, 3, 4, 5, 8, 11]
37 | root = TreeNode.buildTree(Arrays.asList(5, 3, 8, 1, 4, null, 11));
38 | List expected = Arrays.asList(1, 3, 4, 5, 8, 11);
39 | assertEquals(expected, sut.inOrder(root));
40 | assertEquals(expected, sut.iterativeInOrder(root));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarytree/traversal/postorder/PostorderTraversalOfBinaryTreeTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.traversal.postorder;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import coollime.common.objects.TreeNode;
6 | import java.util.Arrays;
7 | import java.util.Collections;
8 | import java.util.List;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class PostorderTraversalOfBinaryTreeTest {
13 |
14 | private static Solution sut;
15 | private TreeNode root;
16 |
17 | @BeforeEach
18 | void setUp() {
19 | sut = new Solution();
20 | root = null;
21 | }
22 |
23 | @Test
24 | void shouldReturnEmptyListWhenTheTreeIsEmpty() {
25 | assertEquals(Collections.emptyList(), sut.postOrder(root));
26 | assertEquals(Collections.emptyList(), sut.recursivePostOrder(root));
27 | }
28 |
29 | @Test
30 | void shouldDoPostOrderTraversal() {
31 | root = new TreeNode(0);
32 | List expected = Collections.singletonList(0);
33 | assertEquals(expected, sut.postOrder(root));
34 | assertEquals(expected, sut.recursivePostOrder(root));
35 |
36 | // In-order build tree: [5, 3, 8, 1, 4, #, 11]
37 | // Post-order result: [1, 4, 3, 11, 8, 5]
38 | root = TreeNode.buildTree(Arrays.asList(5, 3, 8, 1, 4, null, 11));
39 | expected = Arrays.asList(1, 4, 3, 11, 8, 5);
40 | assertEquals(expected, sut.postOrder(root));
41 | assertEquals(expected, sut.recursivePostOrder(root));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/binarytree/traversal/preorder/PreorderTraversalOfBinaryTreeTest.java:
--------------------------------------------------------------------------------
1 | package coollime.binarytree.traversal.preorder;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import coollime.common.objects.TreeNode;
6 | import java.util.Arrays;
7 | import java.util.Collections;
8 | import java.util.List;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class PreorderTraversalOfBinaryTreeTest {
13 |
14 | private static Solution sut;
15 | private TreeNode root;
16 |
17 | @BeforeEach
18 | void setUp() {
19 | sut = new Solution();
20 | root = null;
21 | }
22 |
23 | @Test
24 | void shouldReturnEmptyListWhenTheTreeIsEmpty() {
25 | assertEquals(Collections.emptyList(), sut.preOrder(root));
26 | assertEquals(Collections.emptyList(), sut.recursivePreOrder(root));
27 | }
28 |
29 | @Test
30 | void shouldDoPreOrderTraversal() {
31 | root = new TreeNode(0);
32 | assertEquals(Collections.singletonList(0), sut.preOrder(root));
33 | assertEquals(Collections.singletonList(0), sut.recursivePreOrder(root));
34 |
35 | // In-order: [5, 3, 8, 1, 4, #, 11]
36 | // Pre-order result: [5, 3, 1, 4, 8, 11]
37 | List keys = Arrays.asList(5, 3, 8, 1, 4, null, 11);
38 | root = TreeNode.buildTree(keys);
39 | List expected = Arrays.asList(5, 3, 1, 4, 8, 11);
40 | assertEquals(expected, sut.preOrder(root));
41 | assertEquals(expected, sut.recursivePreOrder(root));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/linkedlist/checkiflinkedlistispalindrome/CheckIfLinkedListIsPalindromeTest.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.checkiflinkedlistispalindrome;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import coollime.common.objects.ListNode;
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class CheckIfLinkedListIsPalindromeTest {
13 |
14 | private static Solution sut;
15 | private ListNode head;
16 |
17 | @BeforeEach
18 | void setUp() {
19 | sut = new Solution();
20 | head = null;
21 | }
22 |
23 | @Test
24 | void shouldReturnTrueWhenTheListIsEmpty() {
25 | assertTrue(sut.isPalindrome(head));
26 | }
27 |
28 | @Test
29 | void shouldReturnTrueWhenThereIsOnlyOneNode() {
30 | head = new ListNode(0);
31 | assertTrue(sut.isPalindrome(head));
32 | }
33 |
34 | @Test
35 | void shouldReturnTrueWhenTheListIsAPalindrome() {
36 | head = ListNode.buildList(new ArrayList<>(Arrays.asList(1, 2, 3, 2, 1)));
37 | assertTrue(sut.isPalindrome(head));
38 | }
39 |
40 | @Test
41 | void shouldReturnFalseWhenTheListIsNotAPalindrome() {
42 | head = ListNode.buildList(new ArrayList<>(Arrays.asList(1, 2, 3)));
43 | assertFalse(sut.isPalindrome(head));
44 |
45 | head = ListNode.buildList(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 2, 1)));
46 | assertFalse(sut.isPalindrome(head));
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/linkedlist/cyclenodeinlinkedlist/CycleNodeInLinkedListTest.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.cyclenodeinlinkedlist;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertNull;
5 |
6 | import coollime.common.objects.ListNode;
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class CycleNodeInLinkedListTest {
13 |
14 | private static Solution sut;
15 | private ListNode head;
16 |
17 | @BeforeEach
18 | void setUp() {
19 | sut = new Solution();
20 | head = null;
21 | }
22 |
23 | @Test
24 | void shouldNotFindTheNodeWhenTheListIsEmpty() {
25 | assertNull(sut.cycleNode(head));
26 | }
27 |
28 | @Test
29 | void shouldReturnTheHeadNodeWhenThereIsOnlyOneNode() {
30 | head = new ListNode(0);
31 | assertNull(sut.cycleNode(head));
32 | }
33 |
34 | @Test
35 | void shouldReturnTheCycleNode() {
36 | head =
37 | ListNode.buildCycleList(new ArrayList<>(Arrays.asList(3, 2, 0, -4)), 1);
38 | assertEquals(2, sut.cycleNode(head).value);
39 |
40 | head = ListNode.buildList(new ArrayList<>(Arrays.asList(3, 2, 0, -4)));
41 | assertNull(sut.cycleNode(head));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/linkedlist/mergesortlinkedlist/MergeSortLinkedListTest.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.mergesortlinkedlist;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import coollime.common.objects.ListNode;
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import org.junit.jupiter.api.BeforeEach;
9 | import org.junit.jupiter.api.Test;
10 |
11 | class MergeSortLinkedListTest {
12 |
13 | private static Solution sut;
14 | private ListNode head;
15 |
16 | @BeforeEach
17 | void setUp() {
18 | sut = new Solution();
19 | head = null;
20 | }
21 |
22 | @Test
23 | void shouldNotSortTheListWhenItIsEmpty() {
24 | assertEquals(head, sut.sortList(head));
25 | }
26 |
27 | @Test
28 | void shouldNotSortTheListWhenThereIsOnlyOneNode() {
29 | head = new ListNode(1);
30 | assertEquals(head, sut.sortList(head));
31 | }
32 |
33 | @Test
34 | void shouldSortTheLinkedList() {
35 | head = ListNode.buildList(new ArrayList<>(Arrays.asList(1, 2, 3)));
36 | assertEquals(
37 | ListNode.buildList(new ArrayList<>(Arrays.asList(1, 2, 3))),
38 | sut.sortList(head)
39 | );
40 |
41 | head = ListNode.buildList(new ArrayList<>(Arrays.asList(4, 2, 6, -3, 5)));
42 | assertEquals(
43 | ListNode.buildList(new ArrayList<>(Arrays.asList(-3, 2, 4, 5, 6))),
44 | sut.sortList(head)
45 | );
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/linkedlist/partitionlinkedlist/PartitionLinkedListTest.java:
--------------------------------------------------------------------------------
1 | package coollime.linkedlist.partitionlinkedlist;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import coollime.common.objects.ListNode;
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import org.junit.jupiter.api.AfterEach;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class PartitionLinkedListTest {
13 |
14 | private static Solution sut;
15 | private ListNode head;
16 | private int target;
17 |
18 | @BeforeEach
19 | void setUp() {
20 | sut = new Solution();
21 | this.head = null;
22 | this.target = 0;
23 | }
24 |
25 | @AfterEach
26 | void tearDown() {}
27 |
28 | @Test
29 | void shouldNotPartitionWhenTheListIsEmpty() {
30 | ListNode result = sut.partition(head, target);
31 | assertEquals(head, result);
32 | }
33 |
34 | @Test
35 | void shouldNotPartitionWhenThereIsOnlyOneNode() {
36 | head = new ListNode(0);
37 | ListNode result = sut.partition(head, target);
38 | assertEquals(head, result);
39 | }
40 |
41 | @Test
42 | void shouldPartitionTheList() {
43 | head = ListNode.buildList(new ArrayList<>(Arrays.asList(2, 4, 3, 5, 1)));
44 | target = 3;
45 | ListNode result = sut.partition(head, target);
46 | ListNode expected = ListNode.buildList(
47 | new ArrayList<>(Arrays.asList(2, 1, 4, 3, 5))
48 | );
49 | assertEquals(expected, result);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/queueandstack/queuebytwostacks/QueueByTwoStacksTest.java:
--------------------------------------------------------------------------------
1 | package coollime.queueandstack.queuebytwostacks;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertAll;
4 | import static org.junit.jupiter.api.Assertions.assertEquals;
5 | import static org.junit.jupiter.api.Assertions.assertFalse;
6 | import static org.junit.jupiter.api.Assertions.assertNotNull;
7 | import static org.junit.jupiter.api.Assertions.assertTrue;
8 |
9 | import org.junit.jupiter.api.AfterEach;
10 | import org.junit.jupiter.api.BeforeEach;
11 | import org.junit.jupiter.api.Test;
12 |
13 | class QueueByTwoStacksTest {
14 | private static Solution queue;
15 |
16 | @BeforeEach
17 | void setUp() {
18 | queue = new Solution();
19 | }
20 |
21 | @AfterEach
22 | void tearDown() {}
23 |
24 | @Test
25 | void test() {
26 | assertAll(
27 | "offer and test the rest",
28 | () -> {
29 | queue.offer(1);
30 | queue.offer(2);
31 | queue.offer(3);
32 | assertNotNull(queue);
33 | assertAll(
34 | "test all features",
35 | () -> assertFalse(queue.isEmpty()),
36 | () -> assertEquals(3, queue.size()),
37 | () -> assertEquals(Integer.valueOf(1), queue.poll()),
38 | () -> assertEquals(Integer.valueOf(2), queue.peek()),
39 | () -> assertEquals(2, queue.size()),
40 | () -> assertEquals(Integer.valueOf(2), queue.poll()),
41 | () -> assertEquals(Integer.valueOf(3), queue.poll()),
42 | () -> assertTrue(queue.isEmpty())
43 | );
44 | }
45 | );
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/queueandstack/sortwithtwostacks/SortWith2StacksTest.java:
--------------------------------------------------------------------------------
1 | package coollime.queueandstack.sortwithtwostacks;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertNull;
5 |
6 | import java.util.Arrays;
7 | import java.util.LinkedList;
8 | import org.junit.jupiter.api.BeforeEach;
9 | import org.junit.jupiter.api.Test;
10 |
11 | class SortWith2StacksTest {
12 | private static Solution sut;
13 | private LinkedList s1;
14 |
15 | @BeforeEach
16 | void setUp() {
17 | sut = new Solution();
18 | s1 = new LinkedList<>();
19 | }
20 |
21 | @Test
22 | void shouldNotSortWhenTheStackIsNull() {
23 | s1 = null;
24 | sut.sort(s1);
25 | assertNull(s1);
26 | }
27 |
28 | @Test
29 | void shouldNotSortWhenTheStackIsEmpty() {
30 | s1 = new LinkedList<>();
31 | sut.sort(s1);
32 | assertEquals(new LinkedList<>(), s1);
33 | }
34 |
35 | @Test
36 | void shouldSortTheElementsInTheStack() {
37 | s1.addAll(Arrays.asList(3, 2, 4, 1, 5));
38 | sut.sort(s1);
39 | assertEquals(new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5)), s1);
40 |
41 | s1.clear();
42 | s1.addAll(Arrays.asList(4, 2, 1, 1, 3, 2));
43 | sut.sort(s1);
44 | assertEquals(new LinkedList<>(Arrays.asList(1, 1, 2, 2, 3, 4)), s1);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/queueandstack/stackwithmin/StackWithMinTest.java:
--------------------------------------------------------------------------------
1 | package coollime.queueandstack.stackwithmin;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertNotNull;
5 |
6 | import org.junit.jupiter.api.AfterEach;
7 | import org.junit.jupiter.api.BeforeEach;
8 | import org.junit.jupiter.api.Test;
9 |
10 | class StackWithMinTest {
11 | private static Solution stack;
12 |
13 | @BeforeEach
14 | void setUp() {
15 | stack = new Solution();
16 | }
17 |
18 | @AfterEach
19 | void tearDown() {}
20 |
21 | @Test
22 | void test() {
23 | assertNotNull(stack);
24 | assertEquals(-1, stack.top());
25 | stack.push(3);
26 | stack.push(4);
27 | stack.push(2);
28 | stack.push(2);
29 | stack.push(2);
30 | stack.push(1);
31 | assertEquals(1, stack.min());
32 | assertEquals(1, stack.pop());
33 | assertEquals(2, stack.pop());
34 | assertEquals(2, stack.pop());
35 | assertEquals(2, stack.top());
36 | assertEquals(2, stack.min());
37 | assertEquals(2, stack.pop());
38 | assertEquals(3, stack.min());
39 | assertEquals(4, stack.top());
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/recursion/atothepowerofb/AToThePowerOfBTest.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.atothepowerofb;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.AfterEach;
6 | import org.junit.jupiter.api.BeforeAll;
7 | import org.junit.jupiter.api.Test;
8 |
9 | class AToThePowerOfBTest {
10 | private static Solution sut;
11 |
12 | @BeforeAll
13 | static void setUp() {
14 | sut = new Solution();
15 | }
16 |
17 | @AfterEach
18 | void tearDown() {}
19 |
20 | @Test
21 | void shouldReturnOneIfRaisedToPowerOfZero() {
22 | long result = sut.power(2, 0);
23 | assertEquals(1, result);
24 | long naiveResult = sut.naivePower(2, 0);
25 | assertEquals(1, naiveResult);
26 | }
27 |
28 | @Test
29 | void shouldReturnTheSameNumberIfRaisedToPowerOfOne() {
30 | long result = sut.power(2, 1);
31 | assertEquals(2, result);
32 | long naiveResult = sut.naivePower(2, 1);
33 | assertEquals(2, naiveResult);
34 | }
35 |
36 | @Test
37 | void shouldReturnTheCorrectResult() {
38 | long result = sut.power(2, 2);
39 | assertEquals(4, result);
40 | long naiveResult = sut.naivePower(2, 2);
41 | assertEquals(4, naiveResult);
42 |
43 | result = sut.power(0, 10);
44 | assertEquals(0, result);
45 | naiveResult = sut.naivePower(0, 10);
46 | assertEquals(0, naiveResult);
47 |
48 | result = sut.power(-2, 5);
49 | assertEquals(-32, result);
50 |
51 | naiveResult = sut.naivePower(-2, 5);
52 | assertEquals(-32, naiveResult);
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/recursion/binarytreepathsumtotargetiii/BinaryTreePathSumToTargetIIITest.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.binarytreepathsumtotargetiii;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import coollime.common.objects.TreeNode;
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import org.junit.jupiter.api.BeforeAll;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class BinaryTreePathSumToTargetIIITest {
13 |
14 | private static Solution sut;
15 | private TreeNode root;
16 | private int target;
17 |
18 | @BeforeAll
19 | static void setInstance() {
20 | sut = new Solution();
21 | }
22 |
23 | @BeforeEach
24 | void setUp() {
25 | root = null;
26 | target = 0;
27 | }
28 |
29 | @Test
30 | void shouldNotFindAPathWhenThereAreNoPathsSumUpToTarget() {
31 | assertFalse(sut.exist(root, target));
32 | }
33 |
34 | @Test
35 | void shouldFindAPathWhenThereIsAPathSumsUpToTarget() {
36 | root =
37 | TreeNode.buildTree(
38 | new ArrayList<>(Arrays.asList(5, 2, 11, null, null, 6, 14, 3))
39 | );
40 | target = 17;
41 | assertTrue(sut.exist(root, target));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/recursion/fibonaccinumber/FibonacciNumberTest.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.fibonaccinumber;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.AfterEach;
6 | import org.junit.jupiter.api.BeforeAll;
7 | import org.junit.jupiter.api.Test;
8 |
9 | class FibonacciNumberTest {
10 | private static Solution sut;
11 |
12 | @BeforeAll
13 | static void setUp() {
14 | sut = new Solution();
15 | }
16 |
17 | @AfterEach
18 | void tearDown() {}
19 |
20 | @Test
21 | void shouldReturnCorrectFibonacciNumber() {
22 | long result = sut.fibonacci(0);
23 | assertEquals(0, result);
24 |
25 | result = sut.fibonacci(1);
26 | assertEquals(1, result);
27 |
28 | result = sut.fibonacci(2);
29 | assertEquals(1, result);
30 |
31 | result = sut.fibonacci(3);
32 | assertEquals(2, result);
33 |
34 | result = sut.fibonacci(6);
35 | assertEquals(8, result);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/recursion/maximumpathsumbinarytreeiii/MaximumPathSumBinaryTreeIIITest.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.maximumpathsumbinarytreeiii;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import coollime.common.objects.TreeNode;
6 | import java.util.ArrayList;
7 | import java.util.Arrays;
8 | import org.junit.jupiter.api.BeforeAll;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class MaximumPathSumBinaryTreeIIITest {
13 |
14 | private static Solution sut;
15 | private TreeNode root;
16 |
17 | @BeforeAll
18 | static void setInstance() {
19 | sut = new Solution();
20 | }
21 |
22 | @BeforeEach
23 | void setUp() {
24 | root = null;
25 | }
26 |
27 | @Test
28 | void shouldReturnZeroWhenThereIsNoTree() {
29 | assertEquals(0, sut.maxPathSum(root));
30 | }
31 |
32 | @Test
33 | void shouldReturnTheSumOfTheMaxPath() {
34 | root =
35 | TreeNode.buildTree(
36 | new ArrayList<>(
37 | Arrays.asList(-5, 2, 11, null, null, 6, 14, null, null, -3)
38 | )
39 | );
40 | int actual = sut.maxPathSum(root);
41 | assertEquals(25, actual);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/recursion/nqueens/NQueensTest.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.nqueens;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.List;
8 | import org.junit.jupiter.api.AfterEach;
9 | import org.junit.jupiter.api.BeforeAll;
10 | import org.junit.jupiter.api.BeforeEach;
11 | import org.junit.jupiter.api.Test;
12 |
13 | class NQueensTest {
14 | private static Solution sut;
15 | private int n;
16 |
17 | @BeforeAll
18 | static void setInstance() {
19 | sut = new Solution();
20 | }
21 |
22 | @BeforeEach
23 | void setUp() {
24 | n = 0;
25 | }
26 |
27 | @AfterEach
28 | void tearDown() {}
29 |
30 | @Test
31 | void shouldNotReturnAnyResultWhenInputIsInvalid() {
32 | assertEquals(new ArrayList<>(), sut.nquees(n));
33 | n = -1;
34 | assertEquals(new ArrayList<>(), sut.nquees(n));
35 | }
36 |
37 | @Test
38 | void shouldReturnAllPossibleWays() {
39 | n = 4;
40 | List> expected = new ArrayList<>(
41 | Arrays.asList(
42 | new ArrayList<>(Arrays.asList(1, 3, 0, 2)),
43 | new ArrayList<>(Arrays.asList(2, 0, 3, 1))
44 | )
45 | );
46 | assertEquals(expected, sut.nquees(n));
47 |
48 | n = 3;
49 | assertEquals(new ArrayList<>(), sut.nquees(n));
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/recursion/spiralordertraverseii/SpiralOrderTraverseIITest.java:
--------------------------------------------------------------------------------
1 | package coollime.recursion.spiralordertraverseii;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import org.junit.jupiter.api.AfterEach;
8 | import org.junit.jupiter.api.BeforeAll;
9 | import org.junit.jupiter.api.BeforeEach;
10 | import org.junit.jupiter.api.Test;
11 |
12 | class SpiralOrderTraverseIITest {
13 | private static Solution sut;
14 | private int[][] matrix;
15 |
16 | @BeforeAll
17 | static void setInstance() {
18 | sut = new Solution();
19 | }
20 |
21 | @BeforeEach
22 | void setUp() {
23 | matrix = null;
24 | }
25 |
26 | @AfterEach
27 | void tearDown() {}
28 |
29 | @Test
30 | void shouldNotTraverseWhenTheMatrixIsInvalid() {
31 | assertEquals(new ArrayList<>(), sut.spiral(matrix));
32 |
33 | matrix = new int[][] {};
34 | assertEquals(new ArrayList<>(), sut.spiral(matrix));
35 | }
36 |
37 | @Test
38 | void shouldTraverseTheMatrix() {
39 | matrix = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
40 | assertEquals(
41 | new ArrayList<>(Arrays.asList(1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7)),
42 | sut.spiral(matrix)
43 | );
44 |
45 | matrix =
46 | new int[][] { { 1, 2, 3 }, { 10, 11, 4 }, { 9, 12, 5 }, { 8, 7, 6 } };
47 | assertEquals(
48 | new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)),
49 | sut.spiral(matrix)
50 | );
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/sortingalgorithms/quicksort/QuickSortTest.java:
--------------------------------------------------------------------------------
1 | package coollime.sortingalgorithms.quicksort;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.AfterEach;
6 | import org.junit.jupiter.api.BeforeEach;
7 | import org.junit.jupiter.api.Test;
8 |
9 | class QuickSortTest {
10 | private static Solution sut;
11 |
12 | @BeforeEach
13 | void setUp() {
14 | sut = new Solution();
15 | }
16 |
17 | @AfterEach
18 | void tearDown() {
19 | }
20 |
21 | @Test
22 | void shouldNotSortTheArrayIfItIsNull() {
23 | int[] result = sut.quickSort(null);
24 | assertArrayEquals(null, result);
25 | }
26 |
27 | @Test
28 | void shouldNotSortTheArrayIfItIsEmpty() {
29 | int[] result = sut.quickSort(new int[] {});
30 | assertArrayEquals(new int[] {}, result);
31 | }
32 |
33 | @Test
34 | void shouldSortTheArray() {
35 | int[] result = sut.quickSort(new int[] { 1 });
36 | assertArrayEquals(new int[] { 1 }, result);
37 |
38 | result = sut.quickSort(new int[] { 1, 2, 3 });
39 | assertArrayEquals(new int[] { 1, 2, 3 }, result);
40 |
41 | result = sut.quickSort(new int[] { 3, 2, 1 });
42 | assertArrayEquals(new int[] { 1, 2, 3 }, result);
43 |
44 | result = sut.quickSort(new int[] { 4, 2, -3, 6, 1 });
45 | assertArrayEquals(new int[] { -3, 1, 2, 4, 6 }, result);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/sortingalgorithms/rainbowsort/RainbowSortTest.java:
--------------------------------------------------------------------------------
1 | package coollime.sortingalgorithms.rainbowsort;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.BeforeAll;
6 | import org.junit.jupiter.api.BeforeEach;
7 | import org.junit.jupiter.api.Test;
8 |
9 | class RainbowSortTest {
10 | private static Solution sut;
11 | private int[] array;
12 |
13 | @BeforeAll
14 | static void setInstance() {
15 | sut = new Solution();
16 | }
17 |
18 | @BeforeEach
19 | void setUp() {
20 | array = null;
21 | }
22 |
23 | @Test
24 | void shouldNotSortTheArrayIfItIsNull() {
25 | int[] result = sut.rainbowSort(array);
26 | assertArrayEquals(array, result);
27 | }
28 |
29 | @Test
30 | void shouldNotSortTheArrayIfItIsEmpty() {
31 | array = new int[] {};
32 | int[] result = sut.rainbowSort(array);
33 | assertArrayEquals(array, result);
34 | }
35 |
36 | @Test
37 | void shouldSortTheArray() {
38 | array = new int[] { 1 };
39 | assertArrayEquals(array, sut.rainbowSort(array));
40 |
41 | array = new int[] { 1, 0 };
42 | assertArrayEquals(new int[] { 0, 1 }, sut.rainbowSort(array));
43 |
44 | array = new int[] { 1, 0, 1, -1, 0 };
45 | assertArrayEquals(new int[] { -1, 0, 0, 1, 1 }, sut.rainbowSort(array));
46 |
47 | array = new int[] { 1, 1, 0, -1, 0, 1, -1 };
48 | assertArrayEquals(new int[] { -1, -1, 0, 0, 1, 1, 1 }, sut.rainbowSort(array));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/coollime/src/test/java/coollime/sortingalgorithms/selectionsort/SelectionSortTest.java:
--------------------------------------------------------------------------------
1 | package coollime.sortingalgorithms.selectionsort;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | import org.junit.jupiter.api.AfterEach;
6 | import org.junit.jupiter.api.BeforeEach;
7 | import org.junit.jupiter.api.Test;
8 |
9 | class SelectionSortTest {
10 | private static Solution sut;
11 |
12 | @BeforeEach
13 | void setUp() {
14 | sut = new Solution();
15 | }
16 |
17 | @AfterEach
18 | void tearDown() {
19 | }
20 |
21 | @Test
22 | void shouldNotSortTheArrayIfItIsNull() {
23 | int[] result = sut.sort(null);
24 | assertArrayEquals(null, result);
25 | }
26 |
27 | @Test
28 | void shouldNotSortTheArrayIfItIsEmpty() {
29 | int[] result = sut.sort(new int[] {});
30 | assertArrayEquals(new int[] {}, result);
31 | }
32 |
33 | @Test
34 | void shouldSortTheArray() {
35 | int[] result = sut.sort(new int[] { 1 });
36 | assertArrayEquals(new int[] { 1 }, result);
37 |
38 | result = sut.sort(new int[] { 1, 2, 3 });
39 | assertArrayEquals(new int[] { 1, 2, 3 }, result);
40 |
41 | result = sut.sort(new int[] { 3, 2, 1 });
42 | assertArrayEquals(new int[] { 1, 2, 3 }, result);
43 |
44 | result = sut.sort(new int[] { 4, 2, -3, 6, 1 });
45 | assertArrayEquals(new int[] { -3, 1, 2, 4, 6 }, result);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/docs/binarysearch/README.md:
--------------------------------------------------------------------------------
1 | ## Binary Search
2 |
3 | 1. [Classical Binary Search](ClassicalBinarySearch)
4 | 2. [Search in Sorted Matrix I](SearchInSortedMatrixI)
5 | 3. [Closest in Sorted Array](ClosestInSortedArray)
6 | 4. [First Occurrence](FirstOccurrence)
7 | 5. [Last Occurrence](LastOccurrence)
8 | 6. [K Closest in Sorted Array](KClosestInSortedArray)
9 | 7. [Search in Unknown Sized Sorted Array](SearchInUnknownSizedSortedArray)
10 | 8. [Find Minimum in Rotated Sorted Array](FindMinimumInRotatedSortedArray)
11 |
--------------------------------------------------------------------------------
/docs/binarysearch/search_sorted_matrix.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/binarysearch/search_sorted_matrix.png
--------------------------------------------------------------------------------
/docs/binarytree/README.md:
--------------------------------------------------------------------------------
1 | ## Binary Tree
2 |
3 | 1. [In-order Traversal of Binary Tree](InorderTraversalOfBinaryTree)
4 | 2. [Pre-order Traversal of Binary Tree](PreorderTraversalOfBinaryTree)
5 | 3. [Post-order Traversal of Binary Tree](PostorderTraversalOfBinaryTree)
6 | 4. [Check if Binary Tree is Balanced](CheckIfBinaryTreeIsBalanced)
7 | 5. [Symmetric Binary Tree](SymmetricBinaryTree)
8 | 6. [Tweaked Identical Binary Trees](TweakedIdenticalBinaryTrees)
9 | 7. [Is Binary Search Tree or Not](IsBinarySearchTreeOrNot)
10 | 8. [Get Keys in Binary Search Tree in Given Range](GetKeysInBinarySearchTreeInGivenRange)
11 | 9. [Binary Tree Path Sum to Target I](BinaryTreePathSumToTargetI)
12 | 10. [Search in Binary Search Tree](SearchInBinarySearchTree)
13 | 11. [Insert in Binary Search Tree](InsertInBinarySearchTree)
14 |
--------------------------------------------------------------------------------
/docs/binarytree/Tweaked-Identical0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/binarytree/Tweaked-Identical0.png
--------------------------------------------------------------------------------
/docs/linkedlist/CycleNodeInLinkedList.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/linkedlist/CycleNodeInLinkedList.png
--------------------------------------------------------------------------------
/docs/linkedlist/README.md:
--------------------------------------------------------------------------------
1 | ## Linked List
2 |
3 | 1. [Reverse Linked List](ReverseLinkedList.md)
4 | 2. [Middle Node of Linked List](MiddleNodeOfLinkedList.md)
5 | 3. [Check if Linked List Has a Cycle](CheckIfLinkedListHasACycle.md)
6 | 4. [Insert in Sorted Linked List](InsertInSortedLinkedList.md)
7 | 5. [Merge Two Sorted Linked Lists](MergeTwoSortedLinkedLists.md)
8 | 6. [Reorder Linked List](ReOrderLinkedList.md)
9 | 7. [Partition Linked List](PartitionLinkedList.md)
10 | 8. [Add Two Numbers](AddTwoNumbers.md)
11 | 9. [Merge Sort Linked List](MergeSortLinkedList.md)
12 | 10. [Check if Linked List is Palindrome](CheckIfLinkedListIsPalindrome.md)
13 | 11. [Cycle Node in Linked List](CycleNodeInLinkedList.md)
14 |
--------------------------------------------------------------------------------
/docs/queueandstack/README.md:
--------------------------------------------------------------------------------
1 | ## Queue & Stack
2 |
3 | 1. [Sort with 3 Stacks](SortWith3Stacks.md)
4 | 2. [Queue by Two Stacks](QueueByTwoStacks.md)
5 | 3. [Stack with min()](StackWithMin.md)
6 | 4. [Sort with 2 Stacks](SortWith2Stacks.md)
7 |
--------------------------------------------------------------------------------
/docs/recursion/README.md:
--------------------------------------------------------------------------------
1 | ## Recursion
2 |
3 | 1. [Recursion I](i/README.md)
4 |
5 | 1. [Fibonacci Number](i/FibonacciNumber.md)
6 | 2. [A to the Power of B](i/AToThePowerOfB.md)
7 |
8 | 2. [Recursion II](ii/README.md)
9 | 1. [N Queens](ii/NQueens.md)
10 | 2. [Spiral Order Traverse I](ii/SpiralOrderTraverseI.md)
11 | 3. [Spiral Order Traverse II](ii/SpiralOrderTraverseII.md)
12 | 4. [Lowest Common Ancestor I](ii/LowestCommonAncestorI.md)
13 | 5. [Lowest Common Ancestor II](ii/LowestCommonAncestorII.md)
14 | 6. [Maximum Path Sum Binary Tree III](../../coollime/src/main/java/coollime/recursion/maximumpathsumbinarytreeiii/Solution.java)
15 | 7. [Maximum Path Sum Binary Tree II](ii/MaximumPathSumBinaryTreeII.md)
16 | 8. [Binary Tree Path Sum to Target III](ii/BinaryTreePathSumToTargetIII.md)
17 |
--------------------------------------------------------------------------------
/docs/recursion/i/README.md:
--------------------------------------------------------------------------------
1 | ## Recursion I
2 |
3 | 1. [Fibonacci Number](FibonacciNumber.md)
4 | 2. [A to the Power of B](AToThePowerOfB.md)
5 |
--------------------------------------------------------------------------------
/docs/recursion/i/improved_complexity.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/recursion/i/improved_complexity.png
--------------------------------------------------------------------------------
/docs/recursion/i/improved_method.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/recursion/i/improved_method.png
--------------------------------------------------------------------------------
/docs/recursion/i/naive_complexity.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/recursion/i/naive_complexity.png
--------------------------------------------------------------------------------
/docs/recursion/i/optimized_complexity.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/recursion/i/optimized_complexity.png
--------------------------------------------------------------------------------
/docs/recursion/ii/README.md:
--------------------------------------------------------------------------------
1 | ## Recursion II
2 |
3 | 1. [N Queens](NQueens.md)
4 | 2. [Spiral Order Traverse I](SpiralOrderTraverseI.md)
5 | 3. [Spiral Order Traverse II](SpiralOrderTraverseII.md)
6 | 4. [Lowest Common Ancestor I](LowestCommonAncestorI.md)
7 | 5. [Lowest Common Ancestor II](LowestCommonAncestorII.md)
8 | 6. [Maximum Path Sum Binary Tree III](../../../coollime/src/main/java/coollime/recursion/maximumpathsumbinarytreeiii/Solution.java)
9 | 7. [Maximum Path Sum Binary Tree II](MaximumPathSumBinaryTreeII.md)
10 | 8. [Binary Tree Path Sum to Target III](BinaryTreePathSumToTargetIII.md)
11 |
--------------------------------------------------------------------------------
/docs/recursion/ii/lca0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/recursion/ii/lca0.png
--------------------------------------------------------------------------------
/docs/recursion/ii/lca1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/recursion/ii/lca1.png
--------------------------------------------------------------------------------
/docs/recursion/ii/nqueens.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/recursion/ii/nqueens.png
--------------------------------------------------------------------------------
/docs/sortingalgorithms/README.md:
--------------------------------------------------------------------------------
1 | ## Sorting Algorithms
2 |
3 | 1. [Selection Sort](SelectionSort.md)
4 | 2. [Merge Sort](MergeSort.md)
5 | 3. [Quick Sort](QuickSort.md)
6 | 4. [Move 0's to the End I](Move0sToTheEndI.md)
7 | 5. [Rainbow Sort](RainbowSort.md)
8 |
--------------------------------------------------------------------------------
/docs/sortingalgorithms/merge_sort.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/sortingalgorithms/merge_sort.png
--------------------------------------------------------------------------------
/docs/sortingalgorithms/quick_sort1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/sortingalgorithms/quick_sort1.png
--------------------------------------------------------------------------------
/docs/sortingalgorithms/quick_sort2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/sortingalgorithms/quick_sort2.png
--------------------------------------------------------------------------------
/docs/sortingalgorithms/rainbowsort.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/docs/sortingalgorithms/rainbowsort.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "coding-practice",
3 | "version": "1.1.0",
4 | "description": "In depth analysis and solution to the coding problems on coding practice and challenge websites",
5 | "homepage": "https://github.com/publicclassoverflow/coding-practice#readme",
6 | "bugs": {
7 | "url": "https://github.com/publicclassoverflow/coding-practice/issues"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "git+https://github.com/publicclassoverflow/coding-practice.git"
12 | },
13 | "license": "MIT",
14 | "author": "MZ",
15 | "main": "README.md",
16 | "scripts": {
17 | "build": "cd coollime && mvn install",
18 | "clean": "cd coollime && mvn clean",
19 | "test": "cd coollime && mvn test",
20 | "validate": "cd coollime && mvn validate"
21 | },
22 | "husky": {
23 | "hooks": {
24 | "pre-commit": "git-branch-is -r \"^((?!master).)*$\" && lint-staged"
25 | }
26 | },
27 | "lint-staged": {
28 | "*.{java,json,md}": "prettier --write"
29 | },
30 | "devDependencies": {
31 | "git-branch-is": "~4.0.0",
32 | "husky": "~6.0.0",
33 | "lint-staged": "~10.5.4",
34 | "prettier": "~2.2.1",
35 | "prettier-plugin-java": "~1.0.2",
36 | "prettier-plugin-package": "~1.3.0",
37 | "prettier-plugin-packagejson": "~2.2.10"
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/G/HeapAndBFS/Medium/WallsAndGates/SolutionTest.java:
--------------------------------------------------------------------------------
1 | package G.HeapAndBFS.Medium.WallsAndGates;
2 |
3 | import org.junit.jupiter.api.BeforeEach;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class SolutionTest {
9 |
10 | private final int INF = Integer.MAX_VALUE;
11 |
12 | private Solution solution;
13 | private int[][] rooms;
14 |
15 | @BeforeEach
16 | void setUp() {
17 | solution = new Solution();
18 | rooms = null;
19 | }
20 |
21 | @Test
22 | void testNull_returnNull() {
23 | assertEquals(rooms, solution.wallsAndGates(rooms));
24 | }
25 |
26 | @Test
27 | void testEmpty_returnEmptyMatrix() {
28 | rooms = new int[][] {};
29 | assertEquals(rooms, solution.wallsAndGates(rooms));
30 | }
31 |
32 | @Test
33 | void testEmptyRow_returnEmpty2DMatrix() {
34 | rooms = new int[][] {{}};
35 | assertEquals(rooms, solution.wallsAndGates(rooms));
36 | }
37 |
38 | @Test
39 | void testExampleMatrix_returnExampleOutput() {
40 | rooms = new int[][] {
41 | {INF, -1, 0, INF},
42 | {INF, INF, INF, -1},
43 | {INF, -1, INF, -1},
44 | {0, -1, INF, INF}
45 | };
46 | int[][] expected = new int[][] {
47 | {3, -1, 0, 1},
48 | {2, 2, 1, -1},
49 | {1, -1, 2, -1},
50 | {0, -1, 3, 4}
51 | };
52 | assertEquals(expected, solution.wallsAndGates(rooms));
53 | }
54 | }
--------------------------------------------------------------------------------
/src/G/HeapAndBFS/README.md:
--------------------------------------------------------------------------------
1 | ## Heap & Breadth/Best First Search (BFS)
2 |
3 | 1. [K Smallest in Unsorted Array](Medium/KSmallestInUnsortedArray)
4 | 2. [Get Keys in Binary Tree Layer by Layer](Easy/GetKeysInBinaryTreeLayerByLayer)
5 | 3. [Bipartite](Hard/Bipartite)
6 | 4. [Check if Binary Tree is Completed](Medium/CheckIfBinaryTreeIsCompleted)
7 | 5. [Kth Smallest Number in Sorted Matrix](Medium/KthSmallestNumberInSortedMatrix)
8 | 6. [Number of Islands](Medium/NumberOfIslands)
9 | 7. [Walls and Gates](Medium/WallsAndGates)
--------------------------------------------------------------------------------
/src/H/DFS/I/Medium/CombinationsOfCoins/algorithm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/H/DFS/I/Medium/CombinationsOfCoins/algorithm.png
--------------------------------------------------------------------------------
/src/H/DFS/I/README.md:
--------------------------------------------------------------------------------
1 | ## Depth First Search (DFS) Part I
2 | 1. [All Subsets I](Medium/AllSubsetsI)
3 | 2. [All Valid Permutations of Parentheses I](Medium/AllValidPermutationsOfParenthesesI)
4 | 3. [Combinations of Coins](Medium/CombinationsOfCoins)
5 | 4. [All Permutations I](Medium/AllPermutationsI)
--------------------------------------------------------------------------------
/src/H/DFS/II/Hard/AllValidPermutationsOfParenthesesII/AllValidPermutationsOfParenthesesIITest.java:
--------------------------------------------------------------------------------
1 | package H.DFS.II.Hard.AllValidPermutationsOfParenthesesII;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import java.util.List;
10 |
11 | import static org.junit.jupiter.api.Assertions.*;
12 |
13 | class AllValidPermutationsOfParenthesesIITest {
14 | private static AllValidPermutationsOfParenthesesII instance;
15 | private int l, m, n;
16 |
17 | @BeforeAll
18 | static void setInstance() {
19 | instance = new AllValidPermutationsOfParenthesesII();
20 | }
21 |
22 | @BeforeEach
23 | void setUp() {
24 | }
25 |
26 | @Test
27 | void validParentheses() {
28 | assertEquals(new ArrayList<>(), instance.validParentheses(l, m, n));
29 |
30 | // Case 1: 1, 1, 0
31 | l = 1;
32 | m = 1;
33 | n = 0;
34 | List expected = new ArrayList<>(Arrays.asList("()<>", "(<>)", "<()>", "<>()"));
35 | List actual = instance.validParentheses(l, m, n);
36 | assertEquals(expected, actual);
37 | }
38 | }
--------------------------------------------------------------------------------
/src/H/DFS/II/Medium/AllSubsetsSizeOfK/AllSubsetsSizeOfKTest.java:
--------------------------------------------------------------------------------
1 | package H.DFS.II.Medium.AllSubsetsSizeOfK;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import java.util.Collections;
10 | import java.util.List;
11 |
12 | import static org.junit.jupiter.api.Assertions.*;
13 |
14 | class AllSubsetsSizeOfKTest {
15 | private static AllSubsetsSizeOfK instance;
16 | private String set;
17 | private int k;
18 |
19 | @BeforeAll
20 | static void setInstance() {
21 | instance = new AllSubsetsSizeOfK();
22 | }
23 |
24 | @BeforeEach
25 | void setUp() {
26 | set = null;
27 | k = 0;
28 | }
29 |
30 | @Test
31 | void subSets() {
32 | assertEquals(new ArrayList<>(), instance.subSets(set, k));
33 |
34 | set = "";
35 | assertEquals(new ArrayList<>(Collections.singletonList("")), instance.subSets(set, k));
36 |
37 | set = "abcd";
38 | k = 2;
39 | List expected = new ArrayList<>(Arrays.asList("ab", "ac", "ad", "bc", "bd", "cd"));
40 | List actual = instance.subSets(set, k);
41 | assertEquals(expected,actual);
42 | }
43 | }
--------------------------------------------------------------------------------
/src/H/DFS/II/README.md:
--------------------------------------------------------------------------------
1 | ## Depth First Search (DFS) II
2 |
3 | 1. [All Subsets II](Hard/AllSubsetsII)
4 | 2. [All Valid Permutations of Parentheses II](Hard/AllValidPermutationsOfParenthesesII)
5 | 3. [All Subsets Size of K](Medium/AllSubsetsSizeOfK)
6 |
--------------------------------------------------------------------------------
/src/H/DFS/README.md:
--------------------------------------------------------------------------------
1 | ## Depth First Search
2 |
3 | 1. [DFS I](I)
4 | 1. [All Subsets I](I/Medium/AllSubsetsI)
5 | 2. [All Valid Permutations of Parentheses I](I/Medium/AllValidPermutationsOfParenthesesI)
6 | 3. [Combinations of Coins](I/Medium/CombinationsOfCoins)
7 | 4. [All Permutations I](I/Medium/AllPermutationsI)
8 |
9 | 2. [DFS II](II)
10 | 1. [All Subsets II](II/Hard/AllSubsetsII)
11 | 2. [All Valid Permutations of Parentheses II](II/Hard/AllValidPermutationsOfParenthesesII)
12 | 3. [All Subsets Size of K](II/Medium/AllSubsetsSizeOfK)
13 |
--------------------------------------------------------------------------------
/src/I/HashTable/Medium/MissingNumberI/MissingNumberITest.java:
--------------------------------------------------------------------------------
1 | package I.HashTable.Medium.MissingNumberI;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class MissingNumberITest {
11 | private static MissingNumberI missingNumber;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | missingNumber = new MissingNumberI();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNull() {
30 | assertEquals(1, missingNumber.missing(array));
31 | }
32 |
33 | @Test
34 | void testEmpty() {
35 | array = new int[] {};
36 | assertEquals(1, missingNumber.missing(array));
37 | }
38 |
39 | @Test
40 | void testOne() {
41 | array = new int[] {1, 2, 3};
42 | assertEquals(4, missingNumber.missing(array));
43 | }
44 |
45 | @Test
46 | void testTwo() {
47 | array = new int[] {2, 1, 4};
48 | assertEquals(3, missingNumber.missing(array));
49 | }
50 |
51 | @Test
52 | void testThree() {
53 | array = new int[] {12, 11, 10, 9, 4, 5, 6, 7, 2, 3, 8};
54 | assertEquals(1, missingNumber.missing(array));
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/I/HashTable/README.md:
--------------------------------------------------------------------------------
1 | ## Hash Table
2 |
3 | 1. [Top K Frequent Words](Medium/TopKFrequentWords)
4 | 2. [Missing Number I](Medium/MissingNumberI)
5 | 3. [Common Numbers of Two Sorted Arrays](Easy/CommonNumbersOfTwoSortedArrays)
--------------------------------------------------------------------------------
/src/J/String/I/Easy/RemoveAdjacentRepeatedCharactersI/RemoveAdjacentRepeatedCharactersITest.java:
--------------------------------------------------------------------------------
1 | package J.String.I.Easy.RemoveAdjacentRepeatedCharactersI;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class RemoveAdjacentRepeatedCharactersITest {
11 | private static RemoveAdjacentRepeatedCharactersI removeAdjacent;
12 | private String input;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | removeAdjacent = new RemoveAdjacentRepeatedCharactersI();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | input = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(input, removeAdjacent.deDup(input));
31 | input = "";
32 | assertEquals(input, removeAdjacent.deDup(input));
33 | }
34 |
35 | @Test
36 | void testExample() {
37 | input = "aaaabbbc";
38 | assertEquals("abc", removeAdjacent.deDup(input));
39 | input = "abccde";
40 | assertEquals("abcde", removeAdjacent.deDup(input));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/J/String/I/Easy/RemoveSpaces/RemoveSpacesTest.java:
--------------------------------------------------------------------------------
1 | package J.String.I.Easy.RemoveSpaces;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class RemoveSpacesTest {
11 | private static RemoveSpaces removeSpaces;
12 | private String input;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | removeSpaces = new RemoveSpaces();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | input = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(input, removeSpaces.removeSpaces(input));
31 | assertEquals(input, removeSpaces.removeSpacesAlt(input));
32 | input = "";
33 | assertEquals(input, removeSpaces.removeSpaces(input));
34 | assertEquals(input, removeSpaces.removeSpacesAlt(input));
35 | }
36 |
37 | @Test
38 | void testSpace() {
39 | input = " ";
40 | assertEquals("", removeSpaces.removeSpaces(input));
41 | assertEquals("", removeSpaces.removeSpacesAlt(input));
42 | }
43 |
44 | @Test
45 | void testExamples() {
46 | input = " I Love Programming ";
47 | assertEquals("I Love Programming", removeSpaces.removeSpaces(input));
48 | assertEquals("I Love Programming", removeSpaces.removeSpacesAlt(input));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/J/String/I/Hard/RemoveAdjacentRepeatedCharactersIV/RemoveAdjacentRepeatedCharactersIVTest.java:
--------------------------------------------------------------------------------
1 | package J.String.I.Hard.RemoveAdjacentRepeatedCharactersIV;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class RemoveAdjacentRepeatedCharactersIVTest {
11 | private static RemoveAdjacentRepeatedCharactersIV removeAdjacent;
12 | private String input;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | removeAdjacent = new RemoveAdjacentRepeatedCharactersIV();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | input = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(input, removeAdjacent.deDup(input));
31 | input = "";
32 | assertEquals(input, removeAdjacent.deDup(input));
33 | }
34 |
35 | @Test
36 | void testExample() {
37 | input = "abbbaaccz";
38 | assertEquals("z", removeAdjacent.deDup(input));
39 | input = "aabccdc";
40 | assertEquals("bdc", removeAdjacent.deDup(input));
41 | input = "aababab";
42 | assertEquals("babab", removeAdjacent.deDup(input));
43 | input = "abbcddca";
44 | assertEquals("", removeAdjacent.deDup(input));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/J/String/I/Medium/DetermineIfOneStringIsAnothersSubstring/rabin_karp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/J/String/I/Medium/DetermineIfOneStringIsAnothersSubstring/rabin_karp.png
--------------------------------------------------------------------------------
/src/J/String/I/README.md:
--------------------------------------------------------------------------------
1 | ## String I
2 |
3 | 1. [Remove Certain Characters](Easy/RemoveCertainCharacters)
4 | 2. [Remove Spaces](Easy/RemoveSpaces)
5 | 3. [Remove Adjacent Repeated Characters I](Easy/RemoveAdjacentRepeatedCharactersI)
6 | 4. [Remove Adjacent Repeated Characters IV](Hard/RemoveAdjacentRepeatedCharactersIV)
7 | 5. [Determine if One String is Another's Substring](Medium/DetermineIfOneStringIsAnothersSubstring)
8 |
--------------------------------------------------------------------------------
/src/J/String/II/Easy/RightShiftByNCharacters/RightShiftByNCharacters.java:
--------------------------------------------------------------------------------
1 | package J.String.II.Easy.RightShiftByNCharacters;
2 |
3 | /**
4 | * https://app.laicode.io/app/problem/397
5 | *
6 | * Description
7 | * Right shift a given string by n characters.
8 | *
9 | * Assumptions
10 | *
11 | * The given string is not null.
12 | * n >= 0.
13 | */
14 |
15 | public class RightShiftByNCharacters {
16 | public String rightShift(String input, int n) {
17 | // Write your solution here
18 | if (input == null || input.length() <= 1) {
19 | return input;
20 | }
21 | int offset = n % input.length();
22 | char[] array = input.toCharArray();
23 | // Step 1: reverse the entire string
24 | reverse(array, 0, array.length - 1);
25 | // Step 2: reverse the two parts separated at index offset
26 | reverse(array, 0, offset - 1);
27 | reverse(array, offset, array.length - 1);
28 | return new String(array);
29 | }
30 |
31 | private void reverse(char[] array, int start, int end) {
32 | while (start < end) {
33 | char temp = array[start];
34 | array[start] = array[end];
35 | array[end] = temp;
36 | start++;
37 | end--;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/J/String/II/Easy/RightShiftByNCharacters/RightShiftByNCharactersTest.java:
--------------------------------------------------------------------------------
1 | package J.String.II.Easy.RightShiftByNCharacters;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class RightShiftByNCharactersTest {
11 | private static RightShiftByNCharacters rightShiftByNCharacters;
12 | private String input;
13 | private int n;
14 |
15 | @BeforeAll
16 | static void setInstance() {
17 | rightShiftByNCharacters = new RightShiftByNCharacters();
18 | }
19 |
20 | @BeforeEach
21 | void setUp() {
22 | input = null;
23 | n = 0;
24 | }
25 |
26 | @AfterEach
27 | void tearDown() {
28 | }
29 |
30 | @Test
31 | void testNullAndEmpty() {
32 | assertEquals(input, rightShiftByNCharacters.rightShift(input, n));
33 | input = "";
34 | assertEquals(input, rightShiftByNCharacters.rightShift(input, n));
35 | }
36 |
37 | @Test
38 | void testExamples() {
39 | input = "abcdef";
40 | n = 2;
41 | assertEquals("efabcd", rightShiftByNCharacters.rightShift(input, n));
42 | input = "abcdefg";
43 | n = 39;
44 | assertEquals("defgabc", rightShiftByNCharacters.rightShift(input, n));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/J/String/II/Hard/DecompressStringII/DecompressStringIITest.java:
--------------------------------------------------------------------------------
1 | package J.String.II.Hard.DecompressStringII;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class DecompressStringIITest {
11 | private static DecompressStringII decompressString;
12 | private String input;
13 | private String result;
14 |
15 | @BeforeAll
16 | static void setInstance() {
17 | decompressString = new DecompressStringII();
18 | }
19 |
20 | @BeforeEach
21 | void setUp() {
22 | input = null;
23 | result = null;
24 | }
25 |
26 | @AfterEach
27 | void tearDown() {
28 | }
29 |
30 | @Test
31 | void testNullAndEmpty() {
32 | assertEquals(input, decompressString.decompress(input));
33 | input = "";
34 | assertEquals(input, decompressString.decompress(input));
35 | }
36 |
37 | @Test
38 | void testExamples() {
39 | input = "a1c0b2c4";
40 | result = decompressString.decompress(input);
41 | printInfo(input, result);
42 | assertEquals("abbcccc", result);
43 |
44 | input = "x2y0i0z3";
45 | result = decompressString.decompress(input);
46 | printInfo(input, result);
47 | assertEquals("xxzzz", result);
48 | }
49 |
50 | private void printInfo(String input, String output) {
51 | System.out.format("%s is decompressed to %s\n", input, output);
52 | }
53 | }
--------------------------------------------------------------------------------
/src/J/String/II/Hard/ReOrderArray/ReOrderArrayTest.java:
--------------------------------------------------------------------------------
1 | package J.String.II.Hard.ReOrderArray;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class ReOrderArrayTest {
11 | private static ReOrderArray reOrderArray;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | reOrderArray = new ReOrderArray();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(array, reOrderArray.reorder(array));
31 | array = new int[] {};
32 | assertEquals(array, reOrderArray.reorder(array));
33 | }
34 |
35 | @Test
36 |
37 | void testExamples() {
38 | array = new int[] {1, 2, 3, 4, 5, 6};
39 | assertArrayEquals(new int[] {1, 4, 2, 5, 3, 6}, reOrderArray.reorder(array));
40 |
41 | array = new int[] {1, 2, 3, 4, 5, 6, 7};
42 | assertArrayEquals(new int[] {1, 4, 2, 5, 3, 6, 7}, reOrderArray.reorder(array));
43 | }
44 | }
--------------------------------------------------------------------------------
/src/J/String/II/Medium/AllAnagrams/AllAnagramsTest.java:
--------------------------------------------------------------------------------
1 | package J.String.II.Medium.AllAnagrams;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import java.util.ArrayList;
9 | import java.util.Arrays;
10 |
11 | import static org.junit.jupiter.api.Assertions.*;
12 |
13 | class AllAnagramsTest {
14 | private static AllAnagrams allAnagrams;
15 | private String sh;
16 | private String lo;
17 |
18 | @BeforeAll
19 | static void setInstance() {
20 | allAnagrams = new AllAnagrams();
21 | }
22 |
23 | @BeforeEach
24 | void setUp() {
25 | sh = null;
26 | lo = null;
27 | }
28 |
29 | @AfterEach
30 | void tearDown() {
31 | }
32 |
33 | @Test
34 | void testNullAndEmpty() {
35 | assertEquals(new ArrayList<>(), allAnagrams.allAnagrams(sh, lo));
36 |
37 | sh = "";
38 | lo = "";
39 | assertEquals(new ArrayList<>(), allAnagrams.allAnagrams(sh, lo));
40 |
41 | sh = "a";
42 | assertEquals(new ArrayList<>(), allAnagrams.allAnagrams(sh, lo));
43 | }
44 |
45 | @Test
46 | void testExamples() {
47 | sh = "ab";
48 | lo = "abcbac";
49 | assertEquals(new ArrayList<>(Arrays.asList(0, 3)), allAnagrams.allAnagrams(sh, lo));
50 |
51 | sh = "aab";
52 | lo = "ababacbbaac";
53 | assertEquals(new ArrayList<>(Arrays.asList(0, 2, 7)), allAnagrams.allAnagrams(sh, lo));
54 | }
55 | }
--------------------------------------------------------------------------------
/src/J/String/II/Medium/LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharactersTest.java:
--------------------------------------------------------------------------------
1 | package J.String.II.Medium.LongestSubstringWithoutRepeatingCharacters;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LongestSubstringWithoutRepeatingCharactersTest {
11 | private static LongestSubstringWithoutRepeatingCharacters longestSubstring;
12 | private String input;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | longestSubstring = new LongestSubstringWithoutRepeatingCharacters();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | input = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(0, longestSubstring.longest(input));
31 | input = "";
32 | assertEquals(0, longestSubstring.longest(input));
33 | }
34 |
35 | @Test
36 | void testExmaples() {
37 | input = "bcdfbd";
38 | assertEquals(4, longestSubstring.longest(input));
39 |
40 | input = "efhrgsayekasdanfev";
41 | assertEquals(9, longestSubstring.longest(input));
42 | }
43 | }
--------------------------------------------------------------------------------
/src/J/String/II/Medium/ReverseWordsInASentenceI/ReverseWordsInASentenceITest.java:
--------------------------------------------------------------------------------
1 | package J.String.II.Medium.ReverseWordsInASentenceI;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class ReverseWordsInASentenceITest {
11 | private static ReverseWordsInASentenceI reverseWordsInASentence;
12 | private String input;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | reverseWordsInASentence = new ReverseWordsInASentenceI();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | input = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(input, reverseWordsInASentence.reverseWords(input));
31 | input = "";
32 | assertEquals(input, reverseWordsInASentence.reverseWords(input));
33 | input = "a";
34 | assertEquals(input, reverseWordsInASentence.reverseWords(input));
35 | }
36 |
37 | @Test
38 | void testExamples() {
39 | input = "I love Google";
40 | assertEquals("Google love I", reverseWordsInASentence.reverseWords(input));
41 | input = "A B C D";
42 | assertEquals("D C B A", reverseWordsInASentence.reverseWords(input));
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/J/String/II/README.md:
--------------------------------------------------------------------------------
1 | ## String II
2 |
3 | 1. [Reverse String](Easy/ReverseString)
4 | 2. [Reverse Words in a Sentence I](Medium/ReverseWordsInASentenceI)
5 | 3. [Right Shift by N Characters](Easy/RightShiftByNCharacters)
6 | 4. [String Replace](Hard/StringReplace)
7 | 5. [ReOrder Array](Hard/ReOrderArray)
8 | 6. [All Permutations II](Hard/AllPermutationsII)
9 | 7. [Decompress String II](Hard/DecompressStringII)
10 | 8. [Longest Substring without Repeating Characters](Medium/LongestSubstringWithoutRepeatingCharacters)
11 | 9. [All Anagrams](Medium/AllAnagrams)
--------------------------------------------------------------------------------
/src/J/String/README.md:
--------------------------------------------------------------------------------
1 | ## String
2 |
3 | 1. [String I](I)
4 | 1. [Remove Certain Characters](I/Easy/RemoveCertainCharacters)
5 | 2. [Remove Spaces](I/Easy/RemoveSpaces)
6 | 3. [Remove Adjacent Repeated Characters I](I/Easy/RemoveAdjacentRepeatedCharactersI)
7 | 4. [Remove Adjacent Repeated Characters IV](I/Hard/RemoveAdjacentRepeatedCharactersIV)
8 | 5. [Determine if One String is Another's Substring](I/Medium/DetermineIfOneStringIsAnothersSubstring)
9 |
10 | 2. [String II](II)
11 | 1. [Reverse String](II/Easy/ReverseString)
12 | 2. [Reverse Words in a Sentence I](II/Medium/ReverseWordsInASentenceI)
13 | 3. [Right Shift by N Characters](II/Easy/RightShiftByNCharacters)
14 | 4. [String Replace](II/Hard/StringReplace)
15 | 5. [ReOrder Array](II/Hard/ReOrderArray)
16 | 6. [All Permutations II](II/Hard/AllPermutationsII)
17 | 7. [Decompress String II](II/Hard/DecompressStringII)
18 | 8. [Longest Substring without Repeating Characters](II/Medium/LongestSubstringWithoutRepeatingCharacters)
19 | 9. [All Anagrams](II/Medium/AllAnagrams)
--------------------------------------------------------------------------------
/src/K/Bit/Easy/HexadecimalRepresentation/HexadecimalRepresentationTest.java:
--------------------------------------------------------------------------------
1 | package K.Bit.Easy.HexadecimalRepresentation;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class HexadecimalRepresentationTest {
11 | private static HexadecimalRepresentation hexadecimalRepresentation;
12 |
13 | @BeforeAll
14 | static void setInstance() {
15 | hexadecimalRepresentation = new HexadecimalRepresentation();
16 | }
17 |
18 | @BeforeEach
19 | void setUp() {
20 | }
21 |
22 | @AfterEach
23 | void tearDown() {
24 | }
25 |
26 | @Test
27 | void test() {
28 | assertEquals("0x0", hexadecimalRepresentation.hex(0));
29 | assertEquals("0xFF", hexadecimalRepresentation.hex(255));
30 | assertEquals("0xF", hexadecimalRepresentation.hex(15));
31 | }
32 | }
--------------------------------------------------------------------------------
/src/K/Bit/Easy/HexadecimalRepresentation/hex_mod.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/K/Bit/Easy/HexadecimalRepresentation/hex_mod.png
--------------------------------------------------------------------------------
/src/K/Bit/Easy/PowerOfTwo/PowerOfTwo.java:
--------------------------------------------------------------------------------
1 | package K.Bit.Easy.PowerOfTwo;
2 |
3 | /**
4 | * https://app.laicode.io/app/problem/74
5 | *
6 | * Description
7 | * Determine if a given integer is power of 2.
8 | *
9 | * Examples
10 | *
11 | * 16 is power of 2 (2 ^ 4)
12 | * 3 is not
13 | * 0 is not
14 | * -1 is not
15 | */
16 |
17 | public class PowerOfTwo {
18 | public boolean isPowerOfTwo(int number) {
19 | // Write your solution here
20 | if (number <= 0) {
21 | return false;
22 | }
23 | int ones = 0;
24 | while (number > 0) {
25 | ones += (number & 1);
26 | number >>= 1;
27 | }
28 | return ones == 1;
29 | }
30 |
31 | public boolean isPowerOfTwoAlt(int number) {
32 | return number > 0 && (number & (number - 1)) == 0;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/K/Bit/Easy/PowerOfTwo/PowerOfTwoTest.java:
--------------------------------------------------------------------------------
1 | package K.Bit.Easy.PowerOfTwo;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class PowerOfTwoTest {
11 | private static PowerOfTwo powerOfTwo;
12 | private int number;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | powerOfTwo = new PowerOfTwo();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | number = 0;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testInvalid() {
30 | assertFalse(powerOfTwo.isPowerOfTwo(-1));
31 | }
32 |
33 | @Test
34 | void testExample() {
35 | assertFalse(powerOfTwo.isPowerOfTwo(0));
36 | assertFalse(powerOfTwo.isPowerOfTwoAlt(0));
37 | assertTrue(powerOfTwo.isPowerOfTwo(2));
38 | assertTrue(powerOfTwo.isPowerOfTwoAlt(2));
39 | assertFalse(powerOfTwo.isPowerOfTwo(13));
40 | assertFalse(powerOfTwo.isPowerOfTwoAlt(13));
41 | assertTrue(powerOfTwo.isPowerOfTwo(512));
42 | assertTrue(powerOfTwo.isPowerOfTwoAlt(512));
43 | }
44 | }
--------------------------------------------------------------------------------
/src/K/Bit/Medium/AllUniqueCharactersII/AllUniqueCharactersII.java:
--------------------------------------------------------------------------------
1 | package K.Bit.Medium.AllUniqueCharactersII;
2 |
3 | public class AllUniqueCharactersII {
4 | public boolean allUnique(String word) {
5 | // Write your solution here
6 | if (word == null || word.length() <= 1) {
7 | return true;
8 | }
9 | // Use an integer array that has enough bits to
10 | // represent the 256 ASCII characters
11 | int[] occurred = new int[256 / 32];
12 | for (int i = 0; i < word.length(); i++) {
13 | char ch = word.charAt(i);
14 | int row = ch / 32;
15 | int col = ch % 32;
16 | // See if the corresponding bit is 1
17 | if (((occurred[row] >> col) & 1) == 1) {
18 | return false;
19 | }
20 | // Mark the corresponding bit to 1
21 | occurred[row] |= 1 << col;
22 | }
23 | return true;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/K/Bit/Medium/AllUniqueCharactersII/AllUniqueCharactersIITest.java:
--------------------------------------------------------------------------------
1 | package K.Bit.Medium.AllUniqueCharactersII;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class AllUniqueCharactersIITest {
11 | private static AllUniqueCharactersII allUnique;
12 | private String word;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | allUnique = new AllUniqueCharactersII();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | word = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertTrue(allUnique.allUnique(word));
31 | word = "";
32 | assertTrue(allUnique.allUnique(word));
33 | }
34 |
35 | @Test
36 | void testExamples() {
37 | word = "abA+\\8";
38 | assertTrue(allUnique.allUnique(word));
39 |
40 | word = "abA+\\88";
41 | assertFalse(allUnique.allUnique(word));
42 |
43 | word = "\\n/b10{-aAM\\n/b90}{-MPO";
44 | assertFalse(allUnique.allUnique(word));
45 | }
46 | }
--------------------------------------------------------------------------------
/src/K/Bit/Medium/AllUniqueCharactersII/bit_vector.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/K/Bit/Medium/AllUniqueCharactersII/bit_vector.png
--------------------------------------------------------------------------------
/src/K/Bit/Medium/NumberOfDifferentBits/NumberOfDifferentBits.java:
--------------------------------------------------------------------------------
1 | package K.Bit.Medium.NumberOfDifferentBits;
2 |
3 | /**
4 | * https://app.laicode.io/app/problem/75
5 | *
6 | * Description
7 | * Determine the number of bits that are different for two given integers.
8 | *
9 | * Examples
10 | *
11 | * 5(“0101”) and 8(“1000”) has 3 different bits
12 | */
13 |
14 | public class NumberOfDifferentBits {
15 | public int diffBits(int a, int b) {
16 | // Write your solution here
17 | int result = a ^ b;
18 | int ones = 0;
19 | while (result != 0) {
20 | ones += result & 1;
21 | result = result >>> 1;
22 | }
23 | return ones;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/K/Bit/Medium/NumberOfDifferentBits/NumberOfDifferentBitsTest.java:
--------------------------------------------------------------------------------
1 | package K.Bit.Medium.NumberOfDifferentBits;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class NumberOfDifferentBitsTest {
11 | private static NumberOfDifferentBits numberOfDifferentBits;
12 |
13 | @BeforeAll
14 | static void setInstance() {
15 | numberOfDifferentBits = new NumberOfDifferentBits();
16 | }
17 |
18 | @BeforeEach
19 | void setUp() {
20 | }
21 |
22 | @AfterEach
23 | void tearDown() {
24 | }
25 |
26 | @Test
27 | void test() {
28 | assertEquals(3, numberOfDifferentBits.diffBits(5, 8));
29 | assertEquals(2, numberOfDifferentBits.diffBits(2, 4));
30 | assertEquals(1, numberOfDifferentBits.diffBits(-1, Integer.MAX_VALUE));
31 | }
32 | }
--------------------------------------------------------------------------------
/src/K/Bit/README.md:
--------------------------------------------------------------------------------
1 | ## Bit Representations & Operations
2 |
3 | 1. [Power of Two](Easy/PowerOfTwo)
4 | 2. [Number of Different Bits](Medium/NumberOfDifferentBits)
5 | 3. [All Unique Characters II](Medium/AllUniqueCharactersII)
6 | 4. [Hexadecimal Representation](Easy/HexadecimalRepresentation)
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/I/Easy/LongestAscendingSubArray/LongestAscendingSubArray.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.I.Easy.LongestAscendingSubArray;
2 |
3 | public class LongestAscendingSubArray {
4 | public int longest(int[] array) {
5 | // Write your solution here
6 | if (array == null || array.length == 0) {
7 | return 0;
8 | }
9 | int[] subarrayLength = new int[array.length];
10 | subarrayLength[0] = 1;
11 | int longest = 1;
12 | for (int i = 1; i < array.length; i++) {
13 | if (array[i] > array[i - 1]) {
14 | subarrayLength[i] = subarrayLength[i - 1] + 1;
15 | longest = Math.max(longest, subarrayLength[i]);
16 | } else {
17 | subarrayLength[i] = 1;
18 | }
19 | }
20 | return longest;
21 | }
22 |
23 | public int longestAlt(int[] array) {
24 | if (array == null || array.length == 0) {
25 | return 0;
26 | }
27 | int length = 1;
28 | int longest = 1;
29 | for (int i = 1; i < array.length; i++) {
30 | if (array[i] > array[i - 1]) {
31 | length++;
32 | longest = Math.max(longest, length);
33 | } else {
34 | length = 1;
35 | }
36 | }
37 | return longest;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/I/Medium/ArrayHopperI/ArrayHopperI.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.I.Medium.ArrayHopperI;
2 |
3 | public class ArrayHopperI {
4 | public boolean canJump(int[] array) {
5 | // Write your solution here
6 | if (array == null || array.length == 0) {
7 | return false;
8 | }
9 | boolean canHop[] = new boolean[array.length];
10 | // Base case: when we are hopping at the end
11 | canHop[array.length - 1] = true;
12 | for (int i = array.length - 2; i >= 0; i--) {
13 | // If the max number of hops at the current
14 | // position makes it out of bounds
15 | // We are guaranteed to reach the end
16 | if (i + array[i] >= array.length - 1) {
17 | canHop[i] = true;
18 | } else {
19 | // For each array[i], the possible number of
20 | // hops are from 1 to array[i]
21 | for (int j = 1; j <= array[i]; j++) {
22 | if (canHop[i + j]) {
23 | canHop[i] = true;
24 | break;
25 | }
26 | }
27 | }
28 | }
29 | return canHop[0];
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/I/Medium/ArrayHopperI/ArrayHopperITest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.I.Medium.ArrayHopperI;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class ArrayHopperITest {
11 | private static ArrayHopperI arrayHopperI;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | arrayHopperI = new ArrayHopperI();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertFalse(arrayHopperI.canJump(array));
31 | array = new int[] {};
32 | assertFalse(arrayHopperI.canJump(array));
33 | }
34 |
35 | @Test
36 | void testExamples() {
37 | array = new int[] {1, 3, 2, 0, 3};
38 | assertTrue(arrayHopperI.canJump(array));
39 |
40 | array = new int[] {2, 1, 1, 0, 2};
41 | assertFalse(arrayHopperI.canJump(array));
42 | }
43 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/I/Medium/ArrayHopperI/notes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/I/Medium/ArrayHopperI/notes.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/I/Medium/MaxProductOfCuttingRope/MaxProductOfCuttingRopeTest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.I.Medium.MaxProductOfCuttingRope;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.assertEquals;
7 |
8 | class MaxProductOfCuttingRopeTest {
9 | private static MaxProductOfCuttingRope maxProductOfCuttingRope;
10 |
11 | @BeforeAll
12 | static void setInstance() {
13 | maxProductOfCuttingRope = new MaxProductOfCuttingRope();
14 | }
15 |
16 | @Test
17 | void testCornerCases() {
18 | assertEquals(0, maxProductOfCuttingRope.maxProduct(0));
19 | assertEquals(0, maxProductOfCuttingRope.maxProductBetter(0));
20 | assertEquals(0, maxProductOfCuttingRope.maxProduct(1));
21 | assertEquals(0, maxProductOfCuttingRope.maxProductBetter(1));
22 | }
23 |
24 | @Test
25 | void testExamples() {
26 | assertEquals(4, maxProductOfCuttingRope.maxProduct(4));
27 | assertEquals(4, maxProductOfCuttingRope.maxProductBetter(4));
28 | assertEquals(6, maxProductOfCuttingRope.maxProduct(5));
29 | assertEquals(6, maxProductOfCuttingRope.maxProductBetter(5));
30 | assertEquals(81, maxProductOfCuttingRope.maxProduct(12));
31 | assertEquals(81, maxProductOfCuttingRope.maxProductBetter(12));
32 | }
33 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/I/Medium/MaxProductOfCuttingRope/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/I/Medium/MaxProductOfCuttingRope/example.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/I/README.md:
--------------------------------------------------------------------------------
1 | ## Dynamic Programming I
2 |
3 | 1. [Longest Ascending SubArray](Easy/LongestAscendingSubArray)
4 | 2. [Max Product of Cutting Rope](Medium/MaxProductOfCuttingRope)
5 | 3. [Array Hopper I](Medium/ArrayHopperI)
6 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Hard/LargestSquareOfOnes/LargestSquareOfOnes.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.II.Hard.LargestSquareOfOnes;
2 |
3 | public class LargestSquareOfOnes {
4 | public int largest(int[][] matrix) {
5 | // Write your solution here
6 | if (matrix == null || matrix.length == 0 ||
7 | matrix[0] == null || matrix[0].length == 0) {
8 | return 0;
9 | }
10 | // The size of the matrix is N x N
11 | int n = matrix.length;
12 | int[][] length = new int[n][n];
13 | // length[i][j] represents the length of the side
14 | // of the largest square whose bottom right
15 | // corner is at index (i, j)
16 | for (int i = 0; i < n; i++) {
17 | length[i][0] = matrix[i][0];
18 | length[0][i] = matrix[0][i];
19 | }
20 | // For each index (i, j), we check its three previous
21 | // neighbors and pick the smallest among them
22 | int maxLength = length[0][0];
23 | for (int i = 1; i < n; i++) {
24 | for (int j = 1; j < n; j++) {
25 | if (matrix[i][j] == 0) {
26 | length[i][j] = 0;
27 | } else {
28 | length[i][j] = 1 + Math.min(length[i - 1][j - 1],
29 | Math.min(length[i][j - 1],
30 | length[i - 1][j]));
31 | maxLength = Math.max(maxLength, length[i][j]);
32 | }
33 | }
34 | }
35 | return maxLength;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Hard/LargestSquareOfOnes/notes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/II/Hard/LargestSquareOfOnes/notes.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/ArrayHopperII/ArrayHopperIITest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.II.Medium.ArrayHopperII;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class ArrayHopperIITest {
11 | private static ArrayHopperII arrayHopperII;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | arrayHopperII = new ArrayHopperII();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(-1, arrayHopperII.minJump(array));
31 | array = new int[] {};
32 | assertEquals(-1, arrayHopperII.minJump(array));
33 | }
34 |
35 | @Test
36 | void testExamples() {
37 | array = new int[] {3, 3, 1, 0, 4};
38 | assertEquals(2, arrayHopperII.minJump(array));
39 |
40 | array = new int[] {2, 1, 1, 0, 2};
41 | assertEquals(-1, arrayHopperII.minJump(array));
42 | }
43 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/DictionaryWordI/dictionary_word.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/II/Medium/DictionaryWordI/dictionary_word.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/EditDistance/EditDistanceTest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.II.Medium.EditDistance;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class EditDistanceTest {
11 | private static EditDistance editDistance;
12 | private String one, two;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | editDistance = new EditDistance();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | one = null;
22 | two = null;
23 | }
24 |
25 | @AfterEach
26 | void tearDown() {
27 | }
28 |
29 | @Test
30 | void testNullAndEmpty() {
31 | assertEquals(-1, editDistance.editDistance(one, two));
32 | one = "";
33 | assertEquals(-1, editDistance.editDistance(one, two));
34 | }
35 |
36 | @Test
37 | void testExamples() {
38 | one = "sigh";
39 | two = "asith";
40 | assertEquals(2, editDistance.editDistance(one, two));
41 |
42 | one = "abcde";
43 | two = "fghij";
44 | assertEquals(5, editDistance.editDistance(one, two));
45 | }
46 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/EditDistance/edit_distance00.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/II/Medium/EditDistance/edit_distance00.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/EditDistance/edit_distance01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/II/Medium/EditDistance/edit_distance01.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/EditDistance/edit_distance02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/II/Medium/EditDistance/edit_distance02.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/LargestSubArraySum/LargestSubArraySum.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.II.Medium.LargestSubArraySum;
2 |
3 | public class LargestSubArraySum {
4 | public int largestSum(int[] array) {
5 | // Write your solution here
6 | if (array == null || array.length == 0) {
7 | return 0;
8 | }
9 | int[] sum = new int[array.length];
10 | // sum[i] represents the sum of the first i elements
11 | sum[0] = array[0];
12 | int maxSum = array[0];
13 | for (int i = 1; i < array.length; i++) {
14 | sum[i] = Math.max(array[i], array[i] + sum[i - 1]);
15 | maxSum = Math.max(maxSum, sum[i]);
16 | }
17 | return maxSum;
18 | }
19 |
20 | public int largestSumOptimized(int[] array) {
21 | // Same time complexity
22 | // But O(1) space instead of O(n)
23 | if (array == null || array.length == 0) {
24 | return 0;
25 | }
26 | // sum represents the sum of the first i elements
27 | int sum = array[0];
28 | int maxSum = array[0];
29 | for (int i = 1; i < array.length; i++) {
30 | sum = Math.max(array[i], sum + array[i]);
31 | maxSum = Math.max(maxSum, sum);
32 | }
33 | return maxSum;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/Medium/LargestSubArraySum/LargestSubArraySumTest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.II.Medium.LargestSubArraySum;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LargestSubArraySumTest {
11 | private static LargestSubArraySum largestSubArraySum;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | largestSubArraySum = new LargestSubArraySum();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(0, largestSubArraySum.largestSum(array));
31 | assertEquals(0, largestSubArraySum.largestSumOptimized(array));
32 | array = new int[] {};
33 | assertEquals(0, largestSubArraySum.largestSum(array));
34 | assertEquals(0, largestSubArraySum.largestSumOptimized(array));
35 | }
36 |
37 | @Test
38 | void testExamples() {
39 | array = new int[] {2, -1, 4, -2, 1};
40 | assertEquals(5, largestSubArraySum.largestSum(array));
41 | assertEquals(5, largestSubArraySum.largestSumOptimized(array));
42 |
43 | array = new int[] {-2, -1, -3};
44 | assertEquals(-1, largestSubArraySum.largestSum(array));
45 | assertEquals(-1, largestSubArraySum.largestSumOptimized(array));
46 | }
47 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/II/README.md:
--------------------------------------------------------------------------------
1 | ## Dynamic Programming II
2 |
3 | 1. [Array Hopper II](Medium/ArrayHopperII)
4 | 2. [Largest SubArray Sum](Medium/LargestSubArraySum)
5 | 3. [Dictionary Word I](Medium/DictionaryWordI)
6 | 4. [Edit Distance](Medium/EditDistance)
7 | 5. [Largest Square of 1s](Hard/LargestSquareOfOnes)
8 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Easy/LongestConsecutiveOnes/LongestConsecutiveOnes.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.III.Easy.LongestConsecutiveOnes;
2 |
3 | public class LongestConsecutiveOnes {
4 | public int longest(int[] array) {
5 | // Write your solution here
6 | if (array == null || array.length == 0) {
7 | return 0;
8 | }
9 | int ones = array[0];
10 | int maxOnes = array[0];
11 | for (int i = 1; i < array.length; i++) {
12 | if (array[i] == 1) {
13 | maxOnes = Math.max(maxOnes, ++ones);
14 | } else {
15 | ones = 0;
16 | }
17 | }
18 | return maxOnes;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Easy/LongestConsecutiveOnes/LongestConsecutiveOnesTest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.III.Easy.LongestConsecutiveOnes;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LongestConsecutiveOnesTest {
11 | private static LongestConsecutiveOnes longestConsecutiveOnes;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | longestConsecutiveOnes = new LongestConsecutiveOnes();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(0, longestConsecutiveOnes.longest(array));
31 |
32 | array = new int[] {};
33 | assertEquals(0, longestConsecutiveOnes.longest(array));
34 | }
35 |
36 | @Test
37 | void testExamples() {
38 | array = new int[] {0, 1, 0, 1, 1, 1, 0};
39 | assertEquals(3, longestConsecutiveOnes.longest(array));
40 | array = new int[] {1, 0, 1, 0, 0, 1, 1, 1, 1, 0};
41 | assertEquals(4, longestConsecutiveOnes.longest(array));
42 | }
43 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/LargestSubMatrixSumTest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.III.Hard.LargestSubMatrixSum;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LargestSubMatrixSumTest {
11 | private static LargestSubMatrixSum largestSubMatrixSum;
12 | private int[][] matrix;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | largestSubMatrixSum = new LargestSubMatrixSum();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | matrix = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(0, largestSubMatrixSum.largest(matrix));
31 |
32 | matrix = new int[][] {};
33 | assertEquals(0, largestSubMatrixSum.largest(matrix));
34 |
35 | matrix = new int[][] {new int[] {}};
36 | assertEquals(0, largestSubMatrixSum.largest(matrix));
37 | }
38 |
39 | @Test
40 | void testExamples() {
41 | matrix = new int[][] {
42 | {1, -2, -1, 4},
43 | {1, -1, 1, 1},
44 | {0, -1, -1, 1},
45 | {0, 0, 1, 1}
46 | };
47 | assertEquals(7, largestSubMatrixSum.largest(matrix));
48 |
49 | matrix = new int [][] {
50 | {-1}
51 | };
52 | assertEquals(-1, largestSubMatrixSum.largest(matrix));
53 | }
54 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum1.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum2.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum2.1.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum2.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum2.2.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/III/Hard/LargestSubMatrixSum/prefix_sum3.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Hard/LongestCrossOfOnes/LongestCrossOfOnesTest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.III.Hard.LongestCrossOfOnes;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LongestCrossOfOnesTest {
11 | private static LongestCrossOfOnes longestCrossOfOnes;
12 | private int[][] matrix;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | longestCrossOfOnes = new LongestCrossOfOnes();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | matrix = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(0, longestCrossOfOnes.largest(matrix));
31 |
32 | matrix = new int[][] {};
33 | assertEquals(0, longestCrossOfOnes.largest(matrix));
34 |
35 | matrix = new int[][] {new int[] {}};
36 | assertEquals(0, longestCrossOfOnes.largest(matrix));
37 | }
38 |
39 | @Test
40 | void testExamples() {
41 | matrix = new int[][] {
42 | {0, 0, 0, 0},
43 | {1, 1, 1, 1},
44 | {0, 1, 1, 1},
45 | {1, 0, 1, 1}
46 | };
47 | assertEquals(2, longestCrossOfOnes.largest(matrix));
48 | }
49 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Hard/LongestCrossOfOnes/longestcross.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/L/DynamicProgramming/III/Hard/LongestCrossOfOnes/longestcross.png
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Medium/LargestSubarraySum/LargestSubarraySum.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.III.Medium.LargestSubarraySum;
2 |
3 | public class LargestSubarraySum {
4 | public int[] largestSum(int[] array) {
5 | // Write your solution here
6 | if (array == null || array.length == 0) {
7 | return new int[] {};
8 | }
9 | int currentSum = array[0];
10 | int maxSum = array[0];
11 | int currentStart = 0;
12 | int maxStart = 0;
13 | int maxEnd = 0;
14 | for (int currentEnd = 1; currentEnd < array.length; currentEnd++) {
15 | if (currentSum < 0) {
16 | currentSum = array[currentEnd];
17 | currentStart = currentEnd;
18 | } else {
19 | currentSum += array[currentEnd];
20 | }
21 | if (currentSum > maxSum) {
22 | maxSum = currentSum;
23 | maxStart = currentStart;
24 | maxEnd = currentEnd;
25 | }
26 | }
27 | return new int[] {maxSum, maxStart, maxEnd};
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/Medium/LargestSubarraySum/LargestSubarraySumTest.java:
--------------------------------------------------------------------------------
1 | package L.DynamicProgramming.III.Medium.LargestSubarraySum;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LargestSubarraySumTest {
11 | private static LargestSubarraySum largestSubarraySum;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | largestSubarraySum = new LargestSubarraySum();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertEquals(new int[] {}, largestSubarraySum.largestSum(array));
31 |
32 | array = new int[] {};
33 | assertEquals(new int[] {}, largestSubarraySum.largestSum(array));
34 | }
35 |
36 | @Test
37 | void testExample() {
38 | array = new int[] {2, -1, 4, -2, 1};
39 | assertArrayEquals(new int[] {5, 0, 2}, largestSubarraySum.largestSum(array));
40 |
41 | array = new int[] {-2, -1, -3};
42 | assertArrayEquals(new int[] {-1, 1, 1}, largestSubarraySum.largestSum(array));
43 | }
44 | }
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/III/README.md:
--------------------------------------------------------------------------------
1 | ## Dynamic Programming III
2 |
3 | 1. [Largest SubArray Sum](Medium/LargestSubarraySum)
4 | 2. [Longest Consecutive 1's](Easy/LongestConsecutiveOnes)
5 | 3. [Longest Cross of 1's](Hard/LongestCrossOfOnes)
6 | 4. [Largest X of 1's](Hard/LargestXOf1s)
7 | 5. [Largest SubMatrix Sum](Hard/LargestSubMatrixSum)
8 |
--------------------------------------------------------------------------------
/src/L/DynamicProgramming/README.md:
--------------------------------------------------------------------------------
1 | ## Dynamic Programming (DP)
2 | 1. [DP I](I)
3 | 1. [Longest Ascending SubArray](I/Easy/LongestAscendingSubArray)
4 | 2. [Max Product of Cutting Rope](I/Medium/MaxProductOfCuttingRope)
5 | 3. [Array Hopper I](I/Medium/ArrayHopperI)
6 |
7 | 2. [DP II](II)
8 | 1. [Array Hopper II](II/Medium/ArrayHopperII)
9 | 2. [Largest SubArray Sum](II/Medium/LargestSubArraySum)
10 | 3. [Dictionary Word I](II/Medium/DictionaryWordI)
11 | 4. [Edit Distance](II/Medium/EditDistance)
12 | 5. [Largest Square of 1s](II/Hard/LargestSquareOfOnes)
13 |
14 | 3. [DP III](III)
15 | 1. [Largest SubArray Sum](III/Medium/LargestSubarraySum)
16 | 2. [Longest Consecutive 1's](III/Easy/LongestConsecutiveOnes)
17 | 3. [Longest Cross of 1's](III/Hard/LongestCrossOfOnes)
18 | 4. [Largest X of 1's](III/Hard/LargestXOf1s)
19 | 5. [Largest SubMatrix Sum](III/Hard/LargestSubMatrixSum)
20 |
21 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/MedianTracker/MedianTrackerTest.java:
--------------------------------------------------------------------------------
1 | package M.Probability.Medium.MedianTracker;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.*;
7 |
8 | class MedianTrackerTest {
9 | private static MedianTracker medianTracker;
10 |
11 | @BeforeAll
12 | static void setInstance() {
13 | medianTracker = new MedianTracker();
14 | }
15 |
16 | @Test
17 | void test() {
18 | medianTracker.read(1);
19 | assertEquals(Double.valueOf(1.0), medianTracker.median());
20 |
21 | medianTracker.read(2);
22 | assertEquals(Double.valueOf(1.5), medianTracker.median());
23 |
24 | medianTracker.read(3);
25 | assertEquals(Double.valueOf(2.0), medianTracker.median());
26 |
27 | medianTracker.read(10);
28 | assertEquals(Double.valueOf(2.5), medianTracker.median());
29 | }
30 | }
--------------------------------------------------------------------------------
/src/M/Probability/Medium/MedianTracker/median_tracker.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/MedianTracker/median_tracker.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/NinetyFivePercentile.java:
--------------------------------------------------------------------------------
1 | package M.Probability.Medium.NinetyFivePercentile;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * NinetyFivePercentile
7 | *
8 | * @author meng
9 | * @date 1/21/19
10 | */
11 | public class NinetyFivePercentile {
12 | /**
13 | *
14 | * @param lengths a list of URL lengths
15 | * @return URL length of the 95th percentile
16 | *
17 | */
18 | public int percentile95(List lengths) {
19 | // Write your solution here
20 | if (lengths == null || lengths.isEmpty()) {
21 | return 0;
22 | }
23 | // The max length of valid URL is 4096
24 | int maxLength = 4096;
25 | int[] count = new int[maxLength + 1];
26 | for (int length : lengths) {
27 | count[length]++;
28 | }
29 | int sum = 0;
30 | while (sum <= 0.05 * lengths.size()) {
31 | sum += count[maxLength--];
32 | }
33 | return maxLength + 1;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/allclasses-frame.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | All Classes
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
17 |
18 |
19 |
20 |
21 | All Classes
22 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/allclasses-noframe.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | All Classes
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
17 |
18 |
19 |
20 |
21 | All Classes
22 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/element-list:
--------------------------------------------------------------------------------
1 | M.Probability.Medium.NinetyFivePercentile
2 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_flat_0_aaaaaa_40x100.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_flat_75_ffffff_40x100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_flat_75_ffffff_40x100.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_55_fbf9ee_1x400.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_55_fbf9ee_1x400.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_65_ffffff_1x400.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_65_ffffff_1x400.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_75_dadada_1x400.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_75_dadada_1x400.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_75_e6e6e6_1x400.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_75_e6e6e6_1x400.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_95_fef1ec_1x400.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_glass_95_fef1ec_1x400.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_highlight-soft_75_cccccc_1x100.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-bg_highlight-soft_75_cccccc_1x100.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_222222_256x240.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_222222_256x240.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_2e83ff_256x240.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_2e83ff_256x240.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_454545_256x240.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_454545_256x240.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_888888_256x240.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_888888_256x240.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_cd0a0a_256x240.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/jquery/images/ui-icons_cd0a0a_256x240.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/member-search-index.js:
--------------------------------------------------------------------------------
1 | memberSearchIndex = [{"p":"N.Probability.Medium.NinetyFivePercentile","c":"NinetyFivePercentile","l":"NinetyFivePercentile()"},{"p":"N.Probability.Medium.NinetyFivePercentile","c":"NinetyFivePercentile","l":"percentile95(List)","url":"percentile95-java.util.List-"}]
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/member-search-index.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/member-search-index.zip
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/package-search-index.js:
--------------------------------------------------------------------------------
1 | packageSearchIndex = [{"l":"N.Probability.Medium.NinetyFivePercentile"}]
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/package-search-index.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/package-search-index.zip
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/resources/glass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/resources/glass.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/resources/x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/resources/x.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/type-search-index.js:
--------------------------------------------------------------------------------
1 | typeSearchIndex = [{"p":"N.Probability.Medium.NinetyFivePercentile","l":"NinetyFivePercentile"}]
--------------------------------------------------------------------------------
/src/M/Probability/Medium/NinetyFivePercentile/javadoc/type-search-index.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/NinetyFivePercentile/javadoc/type-search-index.zip
--------------------------------------------------------------------------------
/src/M/Probability/Medium/PerfectShuffle/PerfectShuffle.java:
--------------------------------------------------------------------------------
1 | package M.Probability.Medium.PerfectShuffle;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * PerfectShuffle
7 | *
8 | * @author meng
9 | * @date 1/21/19
10 | */
11 | public class PerfectShuffle {
12 | public void shuffle(int[] array) {
13 | // Write your solution here.
14 | if (array == null || array.length <= 1) {
15 | return;
16 | }
17 | Random random = new Random();
18 | int n = array.length;
19 | for (int i = 0; i < n; i++) {
20 | // Generate a random index from i to n
21 | int rand = random.nextInt(n - i) + i;
22 | // [0, index) are shuffled section
23 | // [index, end] are yet to be shuffled
24 | // Swap the shuffled card to the result section
25 | int temp = array[i];
26 | array[i] = array[rand];
27 | array[rand] = temp;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/PerfectShuffle/perfect_shuffle1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/PerfectShuffle/perfect_shuffle1.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/PerfectShuffle/perfect_shuffle2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/PerfectShuffle/perfect_shuffle2.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/Random1000UsingRandom5/Random1000UsingRandom5.java:
--------------------------------------------------------------------------------
1 | package M.Probability.Medium.Random1000UsingRandom5;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * Random1000UsingRandom5
7 | *
8 | * @author meng
9 | * @date 1/21/19
10 | */
11 | public class Random1000UsingRandom5 {
12 | public int random1000() {
13 | // Write your solution here
14 | // You can use RandomFive.random5() for generating
15 | // 0 - 4 with equal probability
16 | // Method: count the number of digits of radix 5 numbers needed
17 | // ==> the first power of 5 that exceeds 1000
18 | int digits = 1;
19 | int base = 5;
20 | while (base < 1000) {
21 | digits++;
22 | base *= base;
23 | }
24 | while (true) {
25 | int num = 0;
26 | for (int i = 0; i <= digits; i++) {
27 | num = num * 5 + RandomFive.random5();
28 | }
29 | // If the number falls in the range [0, 5^digits > 1000)
30 | if (num < 1000) {
31 | return num % 1000;
32 | }
33 | }
34 | }
35 | }
36 |
37 | /**
38 | * Manually implement a RandomFive.random5()
39 | */
40 | class RandomFive {
41 | private static Random random;
42 |
43 | RandomFive() {
44 | random = new Random();
45 | }
46 |
47 | static int random5() {
48 | return random.nextInt(5);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/Random7UsingRandom5/Random7UsingRandom5.java:
--------------------------------------------------------------------------------
1 | package M.Probability.Medium.Random7UsingRandom5;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * Random7UsingRandom5
7 | *
8 | * @author meng
9 | * @date 1/21/19
10 | */
11 | public class Random7UsingRandom5 {
12 | public int random7() {
13 | // Write your solution here
14 | // You can use RandomFive.random5() for generating
15 | // 0 - 4 with equal probability
16 | int result = 0;
17 | while (true) {
18 | int rand = 5 * RandomFive.random5() + RandomFive.random5();
19 | if (rand < 21) {
20 | result = rand % 7;
21 | break;
22 | }
23 | }
24 | return result;
25 | }
26 | }
27 |
28 | /**
29 | * Manually implement a RandomFive.random5()
30 | */
31 | class RandomFive {
32 | private static Random random;
33 |
34 | RandomFive() {
35 | random = new Random();
36 | }
37 |
38 | static int random5() {
39 | return random.nextInt(5);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/Random7UsingRandom5/random7.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/Random7UsingRandom5/random7.1.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/Random7UsingRandom5/random7.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/Random7UsingRandom5/random7.2.png
--------------------------------------------------------------------------------
/src/M/Probability/Medium/ReservoirSampling/ReservoirSampling.java:
--------------------------------------------------------------------------------
1 | package M.Probability.Medium.ReservoirSampling;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * ReservoirSampling
7 | *
8 | * @author meng
9 | * @date 1/21/19
10 | */
11 | public class ReservoirSampling {
12 | private int count;
13 | private Integer sample;
14 |
15 | public ReservoirSampling() {
16 | // Write your constructor code here if necessary
17 | // Variable count records the total number of input read so far
18 | count = 0;
19 | // Variable sample represents the current sample
20 | sample = null;
21 | }
22 |
23 | public void read(int value) {
24 | // Write your implementation here
25 | // One call to the read() method == one input read
26 | count++;
27 | // With the updated number of inputs read so far
28 | // Generate a random number between [0, count)
29 | Random random = new Random();
30 | int prob = random.nextInt(count);
31 | // The probability of any one number gets generated
32 | // is 1/count. Therefore, let the prob variable to be
33 | // any one of them, and the probability of this current
34 | // read value is the current sample is 1/count
35 | if (prob == 0) {
36 | sample = value;
37 | }
38 | }
39 |
40 | public Integer sample() {
41 | // Write your implementation here
42 | return sample;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/M/Probability/Medium/ReservoirSampling/reservoir_sampling.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/M/Probability/Medium/ReservoirSampling/reservoir_sampling.png
--------------------------------------------------------------------------------
/src/M/Probability/README.md:
--------------------------------------------------------------------------------
1 | ## Probability, Sampling & Randomization
2 |
3 | 1. [Perfect Shuffle](Medium/PerfectShuffle)
4 | 2. [Reservoir Sampling](Medium/ReservoirSampling)
5 | 3. [Random7 Using Random5](Medium/Random7UsingRandom5)
6 | 4. [Random1000 Using Random5](Medium/Random1000UsingRandom5)
7 | 5. [Median Tracker](Medium/MedianTracker)
8 | 6. [95 Percentile](Medium/NinetyFivePercentile)
9 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Easy/ArrayDeduplicationI/ArrayDeduplicationI.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Easy.ArrayDeduplicationI;
2 |
3 | /**
4 | * ArrayDeduplicationI
5 | *
6 | * @author meng
7 | * @date 1/23/19
8 | */
9 | public class ArrayDeduplicationI {
10 | /**
11 | * Remove the duplicate elements from an array with in-place operations
12 | *
13 | * @param array The input array
14 | * @return Array with duplicate elements removed
15 | */
16 | public int[] dedup(int[] array) {
17 | // Write your solution here
18 | if (array == null || array.length <= 1) {
19 | return array;
20 | }
21 | // Two pointers:
22 | // 1. array[0, slow]: processed for result
23 | // 2. array(slow, fast): processed useless
24 | // 3. array[fast, end]: yet to be processed
25 | int slow = 0;
26 | for (int fast = 1; fast < array.length; fast++) {
27 | // We are only interested in the case
28 | // when two elements are different
29 | if (array[slow] != array[fast]) {
30 | array[++slow] = array[fast];
31 | }
32 | }
33 | // array[0, slow] is the part for result
34 | int[] result = new int[slow + 1];
35 | /*
36 | for (int i = 0; i <= slow; i++) {
37 | result[i] = array[i];
38 | }
39 | */
40 | // Array copy can also be done by:
41 | System.arraycopy(array, 0, result, 0, slow + 1);
42 | return result;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Easy/ArrayDeduplicationI/ArrayDeduplicationITest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Easy.ArrayDeduplicationI;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import static org.junit.jupiter.api.Assertions.*;
8 |
9 | class ArrayDeduplicationITest {
10 | private static ArrayDeduplicationI arrayDedup;
11 | private int[] array;
12 |
13 | @BeforeAll
14 | static void setInstance() {
15 | arrayDedup = new ArrayDeduplicationI();
16 | }
17 |
18 | @BeforeEach
19 | void setUp() {
20 | array = null;
21 | }
22 |
23 | @Test
24 | void testNullAndEmpty() {
25 | assertEquals(array, arrayDedup.dedup(array));
26 |
27 | array = new int[] {};
28 | assertEquals(array, arrayDedup.dedup(array));
29 | }
30 |
31 | @Test
32 | void testExamples() {
33 | array = new int[] {1, 2, 2, 3, 3, 3};
34 | assertArrayEquals(new int[] {1, 2, 3}, arrayDedup.dedup(array));
35 |
36 | array = new int[] {1, 1, 1};
37 | assertArrayEquals(new int[] {1}, arrayDedup.dedup(array));
38 | }
39 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Easy/ArrayDeduplicationI/arraydedup0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/N/CrossTraining/I/Easy/ArrayDeduplicationI/arraydedup0.png
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Easy/ArrayDeduplicationI/arraydedup1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/N/CrossTraining/I/Easy/ArrayDeduplicationI/arraydedup1.png
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Easy/TwoSum/Solution.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Easy.TwoSum;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class Solution {
7 | public boolean existSum(int[] array, int target) {
8 | // Write your solution here
9 | if (array == null || array.length == 0) {
10 | return false;
11 | }
12 | // Use a set that stores the corresponding pair number of the
13 | // current number that is being processed
14 | // target - current number = corresponding pair
15 | Set set = new HashSet<>(array.length);
16 | for (int i = 0; i < array.length; i++) {
17 | if (set.contains(array[i])) {
18 | return true;
19 | }
20 | set.add(target - array[i]);
21 | }
22 | return false;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Hard/ArrayDeduplicationIV/ArrayDeduplicationIV.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Hard.ArrayDeduplicationIV;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * ArrayDeduplicationIV
7 | *
8 | * @author meng
9 | * @date 1/24/19
10 | */
11 | public class ArrayDeduplicationIV {
12 | /**
13 | * Repeatedly remove duplicate elements from a sorted array
14 | * Keep no copies of elements of the same value
15 | *
16 | * @param array the input array
17 | * @return array without duplications*/
18 | public int[] dedup(int[] array) {
19 | // Write your solution here
20 | if (array == null || array.length <= 1) {
21 | return array;
22 | }
23 | // Use a pointer to make array[0, stack] work like a real stack
24 | int stack = 0;
25 | for (int i = 1; i < array.length; i++) {
26 | if (stack < 0 || array[i] != array[stack]) {
27 | // As if we were doing stack.push(array[i])
28 | array[++stack] = array[i];
29 | } else {
30 | // Skip consecutive duplications and pop the element from stack
31 | while (i < array.length - 1 && array[i] == array[i + 1]) {
32 | i++;
33 | }
34 | stack--;
35 | }
36 | }
37 | // Array[0, stack]
38 | return Arrays.copyOf(array, stack + 1);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Hard/ArrayDeduplicationIV/ArrayDeduplicationIVTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Hard.ArrayDeduplicationIV;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import static org.junit.jupiter.api.Assertions.*;
8 |
9 | class ArrayDeduplicationIVTest {
10 | private static ArrayDeduplicationIV arrayDedup;
11 | private int[] array;
12 |
13 | @BeforeAll
14 | static void setInstance() {
15 | arrayDedup = new ArrayDeduplicationIV();
16 | }
17 |
18 | @BeforeEach
19 | void setUp() {
20 | array = null;
21 | }
22 |
23 | @Test
24 | void testNullAndEmpty() {
25 | assertArrayEquals(array, arrayDedup.dedup(array));
26 |
27 | array = new int[] {};
28 | assertArrayEquals(array, arrayDedup.dedup(array));
29 | }
30 |
31 | @Test
32 | void dedup() {
33 | array = new int[] {1, 2, 3, 3, 3, 2, 2};
34 | assertArrayEquals(new int[] {1}, arrayDedup.dedup(array));
35 |
36 | array = new int[] {1, 2, 3, 3, 3, 2, 2, 1};
37 | assertArrayEquals(new int[] {}, arrayDedup.dedup(array));
38 | }
39 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/ArrayDeduplicationII/ArrayDeduplicationII.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.ArrayDeduplicationII;
2 |
3 | /**
4 | * ArrayDeduplicationII
5 | *
6 | * @author meng
7 | * @date 1/23/19
8 | */
9 | public class ArrayDeduplicationII {
10 | /**
11 | * Remove duplicate elements from a sorted array
12 | * Keep at most two copies of the same elements
13 | *
14 | * @param array The input array
15 | * @return An array with at most two copies of the same elements
16 | */
17 | public int[] dedup(int[] array) {
18 | // Write your solution here
19 | if (array == null || array.length <= 2) {
20 | return array;
21 | }
22 | // Two pointers
23 | // 1. array[0, slow]: processed for result
24 | // 2. array[fast, end]: yet to be processed
25 | // Because the array is sorted and we can keep at most two copies
26 | // of the duplicate elements
27 | // We can just compare array[fast] with array[slow - 1]
28 | int slow = 1;
29 | for (int fast = 2; fast < array.length; fast++) {
30 | if (array[fast] != array[slow - 1]) {
31 | array[++slow] = array[fast];
32 | }
33 | }
34 | int[] result = new int[slow + 1];
35 | System.arraycopy(array, 0, result, 0, slow + 1);
36 | return result;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/ArrayDeduplicationII/ArrayDeduplicationIITest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.ArrayDeduplicationII;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import static org.junit.jupiter.api.Assertions.*;
8 |
9 | class ArrayDeduplicationIITest {
10 | private static ArrayDeduplicationII arrayDedup;
11 | private int[] array;
12 |
13 | @BeforeAll
14 | static void setInstance() {
15 | arrayDedup = new ArrayDeduplicationII();
16 | }
17 |
18 | @BeforeEach
19 | void setUp() {
20 | array = null;
21 | }
22 |
23 | @Test
24 | void testNullAndEmpty() {
25 | assertArrayEquals(array, arrayDedup.dedup(array));
26 |
27 | array = new int[] {};
28 | assertArrayEquals(array, arrayDedup.dedup(array));
29 | }
30 |
31 | @Test
32 | void testExamples() {
33 | array = new int[] {1, 2, 2, 3, 3, 3};
34 | assertArrayEquals(new int[] {1, 2, 2, 3, 3}, arrayDedup.dedup(array));
35 |
36 | array = new int[] {1, 1, 2, 3, 3, 3, 4, 5, 5, 5};
37 | assertArrayEquals(new int[] {1, 1, 2, 3, 3, 4, 5, 5}, arrayDedup.dedup(array));
38 |
39 | array = new int[] {1, 1, 1};
40 | assertArrayEquals(new int[] {1, 1}, arrayDedup.dedup(array));
41 | }
42 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/ArrayDeduplicationIII/ArrayDeduplicationIIITest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.ArrayDeduplicationIII;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class ArrayDeduplicationIIITest {
11 | private static ArrayDeduplicationIII arrayDedup;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | arrayDedup = new ArrayDeduplicationIII();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void testNullAndEmpty() {
30 | assertArrayEquals(array, arrayDedup.dedup(array));
31 |
32 | array = new int[] {};
33 | assertArrayEquals(array, arrayDedup.dedup(array));
34 | }
35 |
36 | @Test
37 | void testExamples() {
38 | array = new int[] {1, 2, 2, 3, 3, 3};
39 | assertArrayEquals(new int[] {1}, arrayDedup.dedup(array));
40 |
41 | array = new int[] {1, 1, 2, 3, 3, 4, 5, 5, 5};
42 | assertArrayEquals(new int[] {2, 4}, arrayDedup.dedup(array));
43 | }
44 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/BinaryTreeZigZagTraversal/zigzag.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/N/CrossTraining/I/Medium/BinaryTreeZigZagTraversal/zigzag.png
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/LargestAndSecondLargest/LargestAndSecondLargestTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.LargestAndSecondLargest;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LargestAndSecondLargestTest {
11 | private static LargestAndSecondLargest largestAndSecondLargest;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | largestAndSecondLargest = new LargestAndSecondLargest();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void largestAndSecond() {
30 | assertArrayEquals(new int[] {}, largestAndSecondLargest.largestAndSecond(array));
31 | array = new int[] {};
32 | assertArrayEquals(new int[] {}, largestAndSecondLargest.largestAndSecond(array));
33 |
34 | array = new int[] {2 ,1, 5, 4, 3};
35 | assertArrayEquals(new int[] {5, 4}, largestAndSecondLargest.largestAndSecond(array));
36 |
37 | array = new int[] {3, 3, 3};
38 | assertArrayEquals(new int[] {3, 3}, largestAndSecondLargest.largestAndSecond(array));
39 | }
40 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/LargestAndSecondLargest/largest_second.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/N/CrossTraining/I/Medium/LargestAndSecondLargest/largest_second.png
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/LargestAndSmallest/LargestAndSmallestTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.LargestAndSmallest;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class LargestAndSmallestTest {
11 | private static LargestAndSmallest largestAndSmallest;
12 | private int[] array;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | largestAndSmallest = new LargestAndSmallest();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | array = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 | }
27 |
28 | @Test
29 | void largestAndSmallest() {
30 | assertArrayEquals(new int[] {}, largestAndSmallest.largestAndSmallest(array));
31 | array = new int[] {};
32 | assertArrayEquals(new int[] {}, largestAndSmallest.largestAndSmallest(array));
33 |
34 | array = new int[] {2, 1, 5, 4, 3};
35 | assertArrayEquals(new int[] {5, 1}, largestAndSmallest.largestAndSmallest(array));
36 |
37 | array = new int[] {3, 3, 3, 3, 3};
38 | assertArrayEquals(new int[] {3, 3}, largestAndSmallest.largestAndSmallest(array));
39 | }
40 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/RotateMatrix/RotateMatrixTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.RotateMatrix;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.*;
9 |
10 | class RotateMatrixTest {
11 | private static RotateMatrix rotation;
12 | private int[][] matrix;
13 |
14 | @BeforeAll
15 | static void setInstance() {
16 | rotation = new RotateMatrix();
17 | }
18 |
19 | @BeforeEach
20 | void setUp() {
21 | matrix = null;
22 | }
23 |
24 | @AfterEach
25 | void tearDown() {
26 |
27 | }
28 |
29 | @Test
30 | void rotate() {
31 | int[][] original = matrix;
32 | rotation.rotate(matrix);
33 | assertArrayEquals(original, matrix);
34 |
35 | matrix = new int[][] {};
36 | original = matrix;
37 | rotation.rotate(matrix);
38 | assertArrayEquals(original, matrix);
39 |
40 | matrix = new int[][] {
41 | {1, 2, 3},
42 | {8, 9, 4},
43 | {7, 6, 5}
44 | };
45 | rotation.rotate(matrix);
46 | int[][] expected = new int[][] {
47 | {7, 8, 1},
48 | {6, 9, 2},
49 | {5, 4, 3}
50 | };
51 | assertArrayEquals(expected, matrix);
52 | }
53 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/ThreeSum/SolutionTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.ThreeSum;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import java.util.Collections;
10 | import java.util.List;
11 |
12 | import static org.junit.jupiter.api.Assertions.*;
13 |
14 | class SolutionTest {
15 | private static Solution solution;
16 | private int[] array;
17 | private int target;
18 |
19 | @BeforeAll
20 | static void setInstance() {
21 | solution = new Solution();
22 | }
23 |
24 | @BeforeEach
25 | void setUp() {
26 | array = null;
27 | target = 0;
28 | }
29 |
30 | @Test
31 | void allTriples() {
32 | assertEquals(new ArrayList<>(), solution.allTriples(array, target));
33 |
34 | array = new int[] {1, 2, 2, 3, 2, 4};
35 | target = 8;
36 | List> expected = new ArrayList<>(
37 | Arrays.asList(
38 | Arrays.asList(1, 3, 4),
39 | Arrays.asList(2, 2, 4)
40 | )
41 | );
42 | assertEquals(expected, solution.allTriples(array, target));
43 |
44 | array = new int[] {1, 1, 1};
45 | target = 3;
46 | expected = new ArrayList<>(Arrays.asList(Arrays.asList(1, 1, 1)));
47 | assertEquals(expected, solution.allTriples(array, target));
48 | }
49 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/TwoSumPairI/Solution.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.TwoSumPairI;
2 |
3 | import java.util.*;
4 |
5 | public class Solution {
6 | public List> allPairs(int[] array, int target) {
7 | // Write your solution here
8 | List> result = new ArrayList<>();
9 | if (array == null || array.length == 0) {
10 | return result;
11 | }
12 | // Use a HashMap to store the relationship
13 | Map> map = new HashMap<>();
14 | for (int i = 0; i < array.length; i++) {
15 | List indexes = map.getOrDefault(array[i], new ArrayList<>());
16 | // If this number is one of the processed number's remaining target
17 | // They are a pair
18 | if (!indexes.isEmpty()) {
19 | for (int index : indexes) {
20 | result.add(new ArrayList<>(Arrays.asList(index, i)));
21 | }
22 | }
23 | // Add the current index to the current number's remaining target's indexes list
24 | int remain = target - array[i];
25 | List otherIndexes = map.getOrDefault(remain, new ArrayList<>());
26 | otherIndexes.add(i);
27 | map.put(remain, otherIndexes);
28 | }
29 | return result;
30 | }
31 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/Medium/TwoSumPairII/Solution.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.I.Medium.TwoSumPairII;
2 |
3 | import java.util.*;
4 |
5 | public class Solution {
6 | public List> allPairs(int[] array, int target) {
7 | // Write your solution here
8 | List> result = new ArrayList<>();
9 | if (array == null || array.length == 0) {
10 | return result;
11 | }
12 | Set occurred = new HashSet<>();
13 | Set inResult = new HashSet<>();
14 | for (int i = 0; i < array.length; i++) {
15 | // Avoid duplicate pairs being added to the result
16 | if (inResult.contains(array[i])) {
17 | continue;
18 | }
19 | int diff = target - array[i];
20 | if (occurred.contains(diff)) {
21 | result.add(new ArrayList<>(Arrays.asList(array[i], diff)));
22 | // Add both of them to set 2
23 | inResult.add(array[i]);
24 | inResult.add(diff);
25 | }
26 | // The current element has occurred
27 | occurred.add(array[i]);
28 | }
29 | return result;
30 | }
31 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/I/README.md:
--------------------------------------------------------------------------------
1 | ## Cross Training I
2 | 1. [Array Deduplication I](Easy/ArrayDeduplicationI)
3 | 2. [Array Deduplication II](Medium/ArrayDeduplicationII)
4 | 3. [Array Deduplication III](Medium/ArrayDeduplicationIII)
5 | 4. [Array Deduplication IV](Hard/ArrayDeduplicationIV)
6 | 5. [Move 0's to the End II](Easy/Move0sToTheEndII)
7 | 6. [Largest and Smallest](Medium/LargestAndSmallest)
8 | 7. [Largest and Second Largest](Medium/LargestAndSecondLargest)
9 | 8. [Get Keys in Binary Tree Layer by Layer Zig-Zag Order](Medium/BinaryTreeZigZagTraversal)
10 | 9. [Rotate Matrix](Medium/RotateMatrix)
11 | 10. [Two Sum](Easy/TwoSum)
12 | 11. [Two Sum All Pair I](Medium/TwoSumPairI)
13 | 12. [Two Sum All Pair II](Medium/TwoSumPairII)
14 | 13. [Three Sum](Medium/ThreeSum)
15 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/II/Medium/ClosestNumberInBinarySearchTree/ClosestNumberInBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.II.Medium.ClosestNumberInBinarySearchTree;
2 |
3 | import helper.TreeNode.TreeNode;
4 |
5 | /**
6 | * ClosestNumberInBinarySearchTree
7 | *
8 | * @author meng
9 | * @date 1/28/19
10 | */
11 | public class ClosestNumberInBinarySearchTree {
12 | /**
13 | * In a BST, find the node containing the closest number to the given target number
14 | *
15 | * @param root The root of the BST
16 | * @param target The target number
17 | * @return The key that is closest to the target number
18 | */
19 | public int closest(TreeNode root, int target) {
20 | // Write your solution here
21 | if (root == null) {
22 | return -1;
23 | }
24 | TreeNode current = root;
25 | TreeNode closest = root;
26 | int minDiff = Integer.MAX_VALUE;
27 | while (current != null) {
28 | if (current.key == target) {
29 | return current.key;
30 | }
31 | // Update minDiff and solution
32 | int diff = Math.abs(current.key - target);
33 | if (diff < minDiff) {
34 | minDiff = diff;
35 | closest = current;
36 | }
37 | // Update the traversing direction
38 | if (current.key < target) {
39 | current = current.right;
40 | } else {
41 | current = current.left;
42 | }
43 | }
44 | return closest.key;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/II/Medium/ClosestNumberInBinarySearchTree/ClosestNumberInBinarySearchTreeTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.II.Medium.ClosestNumberInBinarySearchTree;
2 |
3 | import helper.TreeNode.TreeNode;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import java.util.ArrayList;
9 | import java.util.Arrays;
10 |
11 | import static org.junit.jupiter.api.Assertions.*;
12 |
13 | class ClosestNumberInBinarySearchTreeTest {
14 | private static ClosestNumberInBinarySearchTree closestNumber;
15 | private TreeNode root;
16 | private int target;
17 |
18 | @BeforeAll
19 | static void setInstance() {
20 | closestNumber = new ClosestNumberInBinarySearchTree();
21 | }
22 |
23 | @BeforeEach
24 | void setUp() {
25 | root = null;
26 | target = -1;
27 | }
28 |
29 | @Test
30 | void closest() {
31 | assertEquals(-1, closestNumber.closest(root, target));
32 |
33 | root = TreeNode.buildTree(new ArrayList<>(Arrays.asList(5, 2, 11, null, null, 6, 14)));
34 | // Test 1
35 | target = 4;
36 | assertEquals(5, closestNumber.closest(root, target));
37 | // Test 2
38 | target = 10;
39 | assertEquals(11, closestNumber.closest(root, target));
40 | // Test 3
41 | target = 6;
42 | assertEquals(6, closestNumber.closest(root, target));
43 | }
44 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/II/Medium/LargestNumberSmallerInBinarySearchTree/LargestNumberSmallerInBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.II.Medium.LargestNumberSmallerInBinarySearchTree;
2 |
3 | import helper.TreeNode.TreeNode;
4 |
5 | /**
6 | * LargestNumberSmallerInBinarySearchTree
7 | *
8 | * @author meng
9 | * @date 1/28/19
10 | */
11 | public class LargestNumberSmallerInBinarySearchTree {
12 | /**
13 | * In a binary search tree, find the node containing the largest number smaller than
14 | * the given target number.
15 | *
16 | * @param root The root of the given BST
17 | * @param target The target number
18 | * @return The key of the node that is the largest number smaller than the target
19 | */
20 | public int largestSmaller(TreeNode root, int target) {
21 | // Write your solution here
22 | int result = Integer.MIN_VALUE;
23 | while (root != null) {
24 | if (root.key < target) {
25 | // Case 1: update the result
26 | result = root.key;
27 | root = root.right;
28 | } else {
29 | // Case 2: look for a smaller root
30 | root = root.left;
31 | }
32 | }
33 | return result;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/II/Medium/MergeKSortedArrays/MergeKSortedArraysTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.II.Medium.MergeKSortedArrays;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import static org.junit.jupiter.api.Assertions.*;
8 |
9 | class MergeKSortedArraysTest {
10 | private static MergeKSortedArrays kWayMerge;
11 | private int[][] arrayOfArrays;
12 |
13 | @BeforeAll
14 | static void setInstance() {
15 | kWayMerge = new MergeKSortedArrays();
16 | }
17 |
18 | @BeforeEach
19 | void setUp() {
20 | arrayOfArrays = null;
21 | }
22 |
23 | @Test
24 | void merge() {
25 | assertArrayEquals(new int[] {}, kWayMerge.merge(arrayOfArrays));
26 |
27 | arrayOfArrays = new int[][] {};
28 | assertArrayEquals(new int[] {}, kWayMerge.merge(arrayOfArrays));
29 |
30 | arrayOfArrays = new int[][] {
31 | {4, 5, 8, 12},
32 | {2},
33 | {7, 9, 10, 11, 13, 19},
34 | {1, 3, 5},
35 | {6},
36 | {0, 11, 15, 18}
37 | };
38 | assertArrayEquals(
39 | new int[] {0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 15, 18, 19},
40 | kWayMerge.merge(arrayOfArrays)
41 | );
42 | }
43 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/II/Medium/MergeKSortedArrays/algorithm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/risetarnished/coding-practice/92888e79a3cd149b7c9f55cf844e88953e0b97e8/src/N/CrossTraining/II/Medium/MergeKSortedArrays/algorithm.png
--------------------------------------------------------------------------------
/src/N/CrossTraining/II/README.md:
--------------------------------------------------------------------------------
1 | ## Cross Training II
2 |
3 | 1. [Deep Copy Linked List with Random Pointer](Medium/DeepCopyLinkedListWithRandomPointer)
4 | 2. [Deep Copy Undirected Graph](Medium/DeepCopyUndirectedGraph)
5 | 3. [Merge K Sorted Arrays](Medium/MergeKSortedArrays)
6 | 4. [Merge K Sorted Lists](Medium/MergeKSortedLists)
7 | 5. [Closest Number in Binary Search Tree](Medium/ClosestNumberInBinarySearchTree)
8 | 6. [Largest Number Smaller in Binary Search Tree](Medium/LargestNumberSmallerInBinarySearchTree)
9 | 7. [Delete in Binary Search Tree](Medium/DeleteInBinarySearchTree)
10 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/III/README.md:
--------------------------------------------------------------------------------
1 | ## Cross Training III
2 |
3 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/IV/Easy/MajorityNumberI/MajorityNumberI.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.IV.Easy.MajorityNumberI;
2 |
3 | public class MajorityNumberI {
4 | public int majority(int[] array) {
5 | // Write your solution here
6 | // Corner cases check based on the assumption
7 | if (array == null || array.length == 0) {
8 | return Integer.MIN_VALUE;
9 | }
10 | // candidate is the element to be compared against
11 | // count is the # of occurrence of the candidate
12 | int candidate = array[0];
13 | int count = 0;
14 | for (int i = 1; i < array.length; i++) {
15 | if (count == 0) {
16 | // 1. The candidate's count has been balanced out
17 | candidate = array[i];
18 | count++;
19 | } else if (candidate == array[i]) {
20 | // 2. The incoming element is a new instance of the candidate
21 | count++;
22 | } else {
23 | // 3. The incoming element is different from the candidate
24 | count--;
25 | }
26 | }
27 | return candidate;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/IV/Hard/KthSmallestInTwoSortedArrays/KthSmallestInTwoSortedArraysTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.IV.Hard.KthSmallestInTwoSortedArrays;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import static org.junit.jupiter.api.Assertions.*;
8 |
9 | class KthSmallestInTwoSortedArraysTest {
10 | private static KthSmallestInTwoSortedArrays instance;
11 | private int[] a;
12 | private int[] b;
13 | private int k;
14 |
15 | @BeforeAll
16 | static void setInstance() {
17 | instance = new KthSmallestInTwoSortedArrays();
18 | }
19 |
20 | @BeforeEach
21 | void setUp() {
22 | a = null;
23 | b = null;
24 | k = 0;
25 | }
26 |
27 | @Test
28 | void kth() {
29 | assertEquals(Integer.MIN_VALUE, instance.kth(a, b, k));
30 |
31 | a = new int[] {1, 4, 6};
32 | b = new int[] {2, 3};
33 | k = 3;
34 | assertEquals(3, instance.kth(a, b, k));
35 |
36 | a = new int[] {1, 4, 5, 5, 8, 12, 12, 12};
37 | b = new int[] {2, 2, 3, 7, 9, 9, 9};
38 | k = 14;
39 | assertEquals(12, instance.kth(a, b, k));
40 | }
41 |
42 | @Test
43 | void kthImproved() {
44 | assertEquals(Integer.MIN_VALUE, instance.kthImproved(a, b, k));
45 |
46 | a = new int[] {1, 4, 6};
47 | b = new int[] {2, 3};
48 | k = 3;
49 | assertEquals(3, instance.kthImproved(a, b, k));
50 |
51 | a = new int[] {1, 4, 5, 5, 8, 12, 12, 12};
52 | b = new int[] {2, 2, 3, 7, 9, 9, 9};
53 | k = 14;
54 | assertEquals(12, instance.kthImproved(a, b, k));
55 | }
56 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/IV/Medium/MaximumValuesOfSizeKSlidingWindows/MaximumValuesOfSizeKSlidingWindowsTest.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.IV.Medium.MaximumValuesOfSizeKSlidingWindows;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import java.util.ArrayList;
8 | import java.util.Arrays;
9 | import java.util.Collections;
10 | import java.util.List;
11 |
12 | import static org.junit.jupiter.api.Assertions.*;
13 |
14 | class MaximumValuesOfSizeKSlidingWindowsTest {
15 | private static MaximumValuesOfSizeKSlidingWindows instance;
16 | private int[] array;
17 | private int k;
18 |
19 | @BeforeAll
20 | static void setInstance() {
21 | instance = new MaximumValuesOfSizeKSlidingWindows();
22 | }
23 |
24 | @BeforeEach
25 | void setUp() {
26 | array = null;
27 | k = 0;
28 | }
29 |
30 | @Test
31 | void maxWindows() {
32 | assertEquals(new ArrayList<>(), instance.maxWindows(array, k));
33 |
34 | array = new int[] {1, 2, 3, 2, 4, 2, 1};
35 | k = 3;
36 | List expected = new ArrayList<>(Arrays.asList(3, 3, 4, 4, 4));
37 | assertEquals(expected, instance.maxWindows(array, k));
38 |
39 | array = new int[] {1};
40 | k = 1;
41 | expected = new ArrayList<>(Collections.singletonList(1));
42 | assertEquals(expected, instance.maxWindows(array, k));
43 |
44 | array = new int[] {2, 1};
45 | k = 1;
46 | expected = new ArrayList<>(Arrays.asList(2, 1));
47 | assertEquals(expected, instance.maxWindows(array, k));
48 | }
49 | }
--------------------------------------------------------------------------------
/src/N/CrossTraining/IV/README.md:
--------------------------------------------------------------------------------
1 | ## Cross Training IV
2 |
3 | 1. [Kth Smallest in Two Sorted Arrays](Hard/KthSmallestInTwoSortedArrays)
4 | 2. [Maximum Values of Size K Sliding Windows](Medium/MaximumValuesOfSizeKSlidingWindows)
5 | 3. [Implement LRU Cache](Medium/ImplementLRUCache)
6 | 4. [First Non-Repeating Character in Stream](Medium/FirstNonRepeatingCharacterInStream)
7 | 5. [Majority Number I](Easy/MajorityNumberI)
8 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/VI/Medium/LongestAscendingSubsequence/LongestAscendingSubsequence.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.VI.Medium.LongestAscendingSubsequence;
2 |
3 | public class LongestAscendingSubsequence {
4 | public int longest(int[] array) {
5 | // Write your solution here
6 | if (array == null || array.length == 0) {
7 | return 0;
8 | }
9 | // longest[i] represents the length of the longest ascending subsequence
10 | // that ends at index i
11 | int[] longest = new int[array.length];
12 | longest[0] = 1;
13 | // Keep a record of the largest length among all for result
14 | int maxLen = 1;
15 | // For the element at index i, compare its previous elements at index j
16 | // where j is in (i, 1] and array[j] < array[i]
17 | // longest[i] = max(longest[j]) + 1
18 | for (int i = 1; i < array.length; i++) {
19 | longest[i] = 1;
20 | for (int j = i - 1; j >= 0; j--) {
21 | if (array[i] > array[j]) {
22 | longest[i] = Math.max(longest[i], longest[j] + 1);
23 | }
24 | }
25 | maxLen = Math.max(maxLen, longest[i]);
26 | }
27 | return maxLen;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/VI/Medium/LongestCommonSubstring/LongestCommonSubstring.java:
--------------------------------------------------------------------------------
1 | package N.CrossTraining.VI.Medium.LongestCommonSubstring;
2 |
3 | public class LongestCommonSubstring {
4 | public String longestCommon(String source, String target) {
5 | // Write your solution here
6 | if (source == null || target == null) {
7 | return null;
8 | }
9 | // Keep track of the length and the starting index of the longest common substring
10 | int longest = 0;
11 | int start = 0;
12 | // common[i][j] represents the length of the longest common substring of
13 | // the first i characters in source and the first j characters in target
14 | int[][] common = new int[source.length()][target.length()];
15 | for (int i = 0; i < source.length(); i++) {
16 | for (int j = 0; j < target.length(); j++) {
17 | if (source.charAt(i) == target.charAt(j)) {
18 | if (i == 0 || j == 0) {
19 | common[i][j] = 1;
20 | } else {
21 | common[i][j] = common[i - 1][j - 1] + 1;
22 | }
23 | // Update global max and the starting index
24 | if (common[i][j] > longest) {
25 | longest = common[i][j];
26 | // i is pointing to the end so far and the length is "longest"
27 | start = i - longest + 1;
28 | }
29 | }
30 | }
31 | }
32 | // source[start, start + longest] is the result
33 | return source.substring(start, start + longest);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/N/CrossTraining/VI/README.md:
--------------------------------------------------------------------------------
1 | ## Cross Training VI
2 |
3 | 1. [Longest Ascending Subsequence](Medium/LongestAscendingSubsequence)
4 | 2. [Longest Common Substring](Medium/LongestCommonSubstring)
5 |
--------------------------------------------------------------------------------
/src/Z/FreePractice/Easy/PalindromePermutation/PalindromePermutation.java:
--------------------------------------------------------------------------------
1 | package Z.FreePractice.Easy.PalindromePermutation;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class PalindromePermutation {
7 | public boolean canPermutePalindrome(String input) {
8 | // Write your solution here
9 | // Corner cases according to the assumptions
10 | if (input == null) {
11 | return false;
12 | } else if (input.length() <= 1) {
13 | return true;
14 | }
15 | Map frequency = new HashMap<>();
16 | for (int i = 0; i < input.length(); i++) {
17 | char ch = input.charAt(i);
18 | frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
19 | }
20 | // For all letters in the input, if there is at most one letter that
21 | // has an odd number of occurrences ⇒ true
22 | int odd = 0;
23 | for (Map.Entry entry : frequency.entrySet()) {
24 | if (entry.getValue() % 2 != 0 && ++odd > 1) {
25 | return false;
26 | }
27 | }
28 | return true;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/Z/FreePractice/Easy/PalindromePermutation/PalindromePermutationTest.java:
--------------------------------------------------------------------------------
1 | package Z.FreePractice.Easy.PalindromePermutation;
2 |
3 | import static org.junit.jupiter.api.Assertions.*;
4 |
5 | class PalindromePermutationTest {
6 | private static PalindromePermutation instance;
7 | private String input;
8 |
9 | @org.junit.jupiter.api.BeforeAll
10 | static void setInstance() {
11 | instance = new PalindromePermutation();
12 | }
13 |
14 | @org.junit.jupiter.api.BeforeEach
15 | void setUp() {
16 | input = null;
17 | }
18 |
19 | @org.junit.jupiter.api.AfterEach
20 | void tearDown() {
21 | }
22 |
23 | @org.junit.jupiter.api.Test
24 | void canPermutePalindrome() {
25 | assertFalse(instance.canPermutePalindrome(input));
26 |
27 | input = "";
28 | assertTrue(instance.canPermutePalindrome(input));
29 |
30 | input = "code";
31 | assertFalse(instance.canPermutePalindrome(input));
32 |
33 | input = "aab";
34 | assertTrue(instance.canPermutePalindrome(input));
35 | }
36 | }
--------------------------------------------------------------------------------
/src/Z/FreePractice/Easy/PlusOne/PlusOne.java:
--------------------------------------------------------------------------------
1 | package Z.FreePractice.Easy.PlusOne;
2 |
3 | public class PlusOne {
4 | public int[] plus(int[] digits) {
5 | // Write your solution here
6 | if (digits == null || digits.length == 0) {
7 | return digits;
8 | }
9 | // carry represents the fact whether the previous digits yielded a carry-over 10
10 | boolean hasCarry = false;
11 | for (int i = digits.length - 1; i >= 0; i--) {
12 | // Add 1 to the digit if
13 | // 1. it is the least significant digit
14 | // 2. there was a carry
15 | if (i == digits.length - 1 || hasCarry) {
16 | digits[i] += 1;
17 | }
18 | hasCarry = digits[i] >= 10;
19 | digits[i] %= 10;
20 | }
21 | // Post-processing
22 | // If the most significant digit yielded a carry-over
23 | // We need to create a new digit and expand the array
24 | if (hasCarry) {
25 | int[] expanded = new int[digits.length + 1];
26 | for (int i = 0; i < expanded.length; i++) {
27 | if (i == 0) {
28 | expanded[i] = 1;
29 | } else {
30 | expanded[i] = digits[i - 1];
31 | }
32 | }
33 | digits = expanded;
34 | }
35 | return digits;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Z/FreePractice/Medium/CloneGraph/CloneGraphTest.java:
--------------------------------------------------------------------------------
1 | package Z.FreePractice.Medium.CloneGraph;
2 |
3 | import org.junit.jupiter.api.BeforeAll;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import java.util.ArrayList;
8 |
9 | import static org.junit.jupiter.api.Assertions.*;
10 |
11 | class CloneGraphTest {
12 | private static CloneGraph instance;
13 | private Node node;
14 |
15 | @BeforeAll
16 | static void setInstance() {
17 | instance = new CloneGraph();
18 | }
19 |
20 | @BeforeEach
21 | void setUp() {
22 | node = null;
23 | }
24 |
25 | @Test
26 | void cloneGraph() {
27 | node = new Node(1, new ArrayList<>());
28 | Node two = new Node(2, new ArrayList<>());
29 | Node three = new Node(3, new ArrayList<>());
30 | Node four = new Node(4, new ArrayList<>());
31 | node.neighbors.add(two);
32 | two.neighbors.add(three);
33 | three.neighbors.add(four);
34 | four.neighbors.add(node);
35 |
36 | Node copied = instance.cloneGraph(node);
37 | assertNotNull(copied);
38 | }
39 | }
--------------------------------------------------------------------------------
/src/Z/FreePractice/Medium/PalindromePermutationII/PalindromePermutationIITest.java:
--------------------------------------------------------------------------------
1 | package Z.FreePractice.Medium.PalindromePermutationII;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeAll;
5 | import org.junit.jupiter.api.BeforeEach;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import java.util.ArrayList;
9 | import java.util.Arrays;
10 | import java.util.Collections;
11 |
12 | import static org.junit.jupiter.api.Assertions.assertEquals;
13 |
14 | class PalindromePermutationIITest {
15 | private static PalindromePermutationII instance;
16 | private String input;
17 |
18 | @BeforeAll
19 | static void setInstance() {
20 | instance = new PalindromePermutationII();
21 | }
22 |
23 | @BeforeEach
24 | void setUp() {
25 | input = null;
26 | }
27 |
28 | @AfterEach
29 | void tearDown() {
30 | }
31 |
32 | @Test
33 | void generatePalindromes() {
34 | assertEquals(new ArrayList<>(), instance.generatePalindromes(input));
35 |
36 | input = "";
37 | assertEquals(new ArrayList<>(Collections.singletonList("")), instance.generatePalindromes(input));
38 |
39 | input = "aabb";
40 | assertEquals(new ArrayList<>(Arrays.asList("abba", "baab")), instance.generatePalindromes(input));
41 |
42 | input = "abc";
43 | assertEquals(new ArrayList<>(), instance.generatePalindromes(input));
44 | }
45 | }
--------------------------------------------------------------------------------
/src/Z/FreePractice/README.md:
--------------------------------------------------------------------------------
1 | ## Free Practice
2 | ### Flow of consciousness training
3 |
4 | 1. [Palindrome Permutation](Easy/PalindromePermutation)
5 | 2. [Palindrome Permutation II](Medium/PalindromePermutationII)
6 | 3. [Plus One](Easy/PlusOne)
7 | 4. [Clone Graph](Medium/CloneGraph)
8 |
--------------------------------------------------------------------------------