├── .github ├── FUNDING.yml └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main └── java │ ├── codility │ ├── ambitious │ │ └── IdenticalPairOfIndices.java │ └── painless │ │ ├── BinaryGap.java │ │ ├── CroppedMessage.java │ │ ├── CyclicRotation.java │ │ └── OddOccurencesInAnArray.java │ ├── hackerrank │ ├── algorithms │ │ ├── dynamicprogramming │ │ │ ├── Equal.java │ │ │ ├── LongestCommonSubstring.java │ │ │ └── SherLockAndCost.java │ │ ├── implementation │ │ │ ├── BetweenTwoSets.java │ │ │ ├── NumberLineJumps.java │ │ │ └── RepeatedString.java │ │ ├── search │ │ │ ├── MinimumLoss.java │ │ │ ├── MissingNumbers.java │ │ │ └── Pairs.java │ │ ├── sorting │ │ │ └── InsertionSortPartOne.java │ │ ├── strings │ │ │ ├── BetterCompression.java │ │ │ ├── CamelCase.java │ │ │ ├── MakeAnagrams.java │ │ │ ├── SherlockAndTheValidString.java │ │ │ ├── SuperReducedString.java │ │ │ ├── TwoCharacters.java │ │ │ └── TwoStrings.java │ │ └── warmup │ │ │ └── BirthdayCakeCandles.java │ ├── datastructures │ │ ├── arrays │ │ │ └── LeftRotation.java │ │ ├── linkedlists │ │ │ ├── CycleDetection.java │ │ │ ├── PrintInReverse.java │ │ │ ├── RemoveDuplicates.java │ │ │ └── ReverseALinkedList.java │ │ ├── queues │ │ │ └── QueueUsingTwoStacks.java │ │ ├── stacks │ │ │ ├── BalancedBrackets.java │ │ │ ├── EqualStacks.java │ │ │ └── GameOfTwoStacks.java │ │ └── trees │ │ │ ├── HeightOfABinaryTree.java │ │ │ └── IsBinarySearchTree.java │ ├── expedia │ │ ├── Braces.java │ │ ├── LongestVowelSubsequence.java │ │ └── ReachableEmployees.java │ └── projecteuler │ │ ├── Problem1.java │ │ ├── Problem2.java │ │ ├── Problem3.java │ │ ├── Problem4.java │ │ ├── Problem5.java │ │ ├── Problem6.java │ │ └── Problem7.java │ ├── leetcode │ ├── AddDigits.java │ ├── AddTwoNumbers.java │ ├── AlmostPalindromes.java │ ├── ArrayNesting.java │ ├── ArrayPartition1.java │ ├── AsciiDistance.java │ ├── AssignCookies.java │ ├── AverageOfLevelsInBinaryTree.java │ ├── BaseballGame.java │ ├── BinaryNumberWithAlternatingBits.java │ ├── BinaryTreeInOrderTraversal.java │ ├── BinaryTreeRightSIdeView.java │ ├── Brackets.java │ ├── ConstructRectangle.java │ ├── ConstructStringFromBinaryTree.java │ ├── ConvertSortedArrayToBinarySearchTree.java │ ├── CopyListWithRandomPointer.java │ ├── CountBinaryStrings.java │ ├── DetectCapital.java │ ├── DiameterOfBinaryTree.java │ ├── DistributeCandies.java │ ├── DoubleListNode.java │ ├── EmployeeImportance.java │ ├── EncodeDecodeTinyUrl.java │ ├── ExcelSheetColumnNumber.java │ ├── FinKthLargest.java │ ├── FindAllNumbersDisappearedInArray.java │ ├── FindAnagramMappings.java │ ├── FindComplement.java │ ├── FindTheDifference.java │ ├── FirstUniqueCharacterInString.java │ ├── FizzBuzz.java │ ├── FloodFill.java │ ├── FourLetterWords.java │ ├── HammingDistance.java │ ├── IntersectionOfTwoArrays.java │ ├── InvertBinaryTree.java │ ├── IslandPerimeter.java │ ├── JewelsAndStones.java │ ├── JudgeRouteCircle.java │ ├── KeyboardRow.java │ ├── LeafSimilar.java │ ├── LengthOfLongestPalindrome.java │ ├── LetterCombinations.java │ ├── LoggerRateLimiter.java │ ├── LongestUncommonSubsequence1.java │ ├── MaxAreaOfIsland.java │ ├── MaxConsecutiveOnes.java │ ├── MaximumSumTwoNonOverlappingSubarrays.java │ ├── MergeTwoSortedLists.java │ ├── MinStack.java │ ├── MinimumMovesToEqualArrayElements.java │ ├── MissingNumber.java │ ├── MovingAverage.java │ ├── NextGreaterElement1.java │ ├── NimGame.java │ ├── NotBoring.sql │ ├── NumberComplement.java │ ├── NumberOfEquivalentDominoes.java │ ├── NumberOfIslands.java │ ├── NumberOfLinesToWriteString.java │ ├── PeakIndexInAMountainArray.java │ ├── RandomizedSet.java │ ├── RangeAddition2.java │ ├── RansomeNote.java │ ├── ReshapeTheMatrix.java │ ├── ReverseLinkedList.java │ ├── ReverseString.java │ ├── RomanToInteger.java │ ├── SmallestLetterGreaterThanTarget.java │ ├── StringCompression.java │ ├── StringToInteger.java │ ├── SumOfLeftLeaves.java │ ├── ThreeSum.java │ ├── ToeplitzMatrix.java │ ├── TrimABinarySearchTree.java │ ├── TwoSumIV.java │ ├── UnionFind.java │ ├── UniqueMorseCodeWords.java │ ├── WordBreak.java │ ├── WordLadder.java │ ├── WordLadderII.java │ ├── ZombieClusters.java │ ├── easy │ │ ├── AverageOfLevelsInBinaryTree.java │ │ ├── BackspaceStringCompare.java │ │ ├── BalancedBinaryTree.java │ │ ├── BestTimeToBuyAndSellAStock.java │ │ ├── BestTimeToBuyAndSellAStockII.java │ │ ├── CheckIfPangram.java │ │ ├── ClimbingStairs.java │ │ ├── ContainsDuplicate.java │ │ ├── ContainsDuplicateII.java │ │ ├── ConvertBstToGreaterTree.java │ │ ├── CountCompleteTreeNodes.java │ │ ├── CountPrimes.java │ │ ├── DayOfTheYear.java │ │ ├── DiameterOfABinaryTree.java │ │ ├── FibonacciNumber.java │ │ ├── FindAllNumbersDisappearedInAnArray.java │ │ ├── FindCommonCharacters.java │ │ ├── FindPivotIndex.java │ │ ├── FindWordsThatCanBeFormedByCharacters.java │ │ ├── FirstUniqueCharacterInAString.java │ │ ├── HappyNumber.java │ │ ├── IntersectionOfTwoArraysII.java │ │ ├── IntersectionOfTwoLinkedLists.java │ │ ├── InvertTree.java │ │ ├── IsSubsequence.java │ │ ├── IsomorphicStrings.java │ │ ├── JewelsAndStones.java │ │ ├── KthMissingPositiveNumber.java │ │ ├── LastStoneWeight.java │ │ ├── LeftAndRightSumDifferences.java │ │ ├── LengthOfLastWord.java │ │ ├── LinkedListCycle.java │ │ ├── LongestCommonPrefix.java │ │ ├── LowestCommonAncestorOfBinarySearchTree.java │ │ ├── MajorityElement.java │ │ ├── MatrixDiagonalSum.java │ │ ├── MaxConsecutiveOnes.java │ │ ├── MaximumAverageSubarrayI.java │ │ ├── MaximumDepthOfABinaryTree.java │ │ ├── MaximumOddBinaryNumber.java │ │ ├── MaximumSubarray.java │ │ ├── MergeSortedArray.java │ │ ├── MergeTwoBinaryTrees.java │ │ ├── MergeTwoSortedLists.java │ │ ├── MiddleOfTheLinkedList.java │ │ ├── MinCostClimbingStairs.java │ │ ├── MinimumDepthBinaryTree.java │ │ ├── MoveZeroes.java │ │ ├── MyQueue.java │ │ ├── MyStack.java │ │ ├── NextGreaterElementI.java │ │ ├── NumberOf1Bits.java │ │ ├── NumberOfGoodPairs.java │ │ ├── NumbersSmallerThanTheCurrentNumber.java │ │ ├── PalindromeLinkedList.java │ │ ├── PascalTriangleII.java │ │ ├── PascalsTriangle.java │ │ ├── PathSum.java │ │ ├── RangeSumOfBST.java │ │ ├── RansomNote.java │ │ ├── RemoveLinkedListElements.java │ │ ├── ReorderDataInLogFiles.java │ │ ├── ReverseOnlyLetters.java │ │ ├── ReversePrefixOfWord.java │ │ ├── ReverseWordsInAString3.java │ │ ├── ReverseWordsInAStringIII.java │ │ ├── RotateArray.java │ │ ├── SameTree.java │ │ ├── SearchInsertPosition.java │ │ ├── ShuffleString.java │ │ ├── SingleNumber.java │ │ ├── SortingTheSentence.java │ │ ├── SquaresOfSortedArray.java │ │ ├── StringCompression.java │ │ ├── SumOfUniqueElements.java │ │ ├── SymmetricTree.java │ │ ├── TwoSum.java │ │ ├── TwoSumII.java │ │ ├── UglyNumber.java │ │ ├── ValidAnagram.java │ │ ├── ValidPalindrome.java │ │ ├── ValidPalindromeII.java │ │ ├── ValidParantheses.java │ │ └── ValidPerfectSquare.java │ ├── hard │ │ ├── LongestValidParentheses.java │ │ ├── MedianOfTwoSortedArrays.java │ │ ├── MergeKSortedLists.java │ │ ├── MinimumWindowSubstring.java │ │ ├── SerializeAndDeserializeABinaryTree.java │ │ ├── SlidingWindowMaximum.java │ │ ├── TrappingRainWater.java │ │ └── TrappingRainWaterII.java │ └── medium │ │ ├── AddTwoNumbers.java │ │ ├── AddTwoNumbersII.java │ │ ├── BinaryTreeFromPreorderInOrderTraversal.java │ │ ├── BinaryTreeLevelOrderTraversal.java │ │ ├── BinaryTreeRightSideView.java │ │ ├── BinaryTreeZigzagLevelOrderTraversal.java │ │ ├── BoatsToSavePeople.java │ │ ├── CapacityToShipPackagesWithinDDays.java │ │ ├── CoinChange.java │ │ ├── CompareVersionNumbers.java │ │ ├── ContainerWithMostWater.java │ │ ├── ContiguousArray.java │ │ ├── CopyListWithRandomPointer.java │ │ ├── CountServersThatCommunicate.java │ │ ├── DailyTemperatures.java │ │ ├── DecodeString.java │ │ ├── DecodeWays.java │ │ ├── DeleteDuplicatesFromSortedListII.java │ │ ├── EditDistance.java │ │ ├── FindAllAnagramsInAString.java │ │ ├── FindAllDuplicatesInAnArray.java │ │ ├── FindMinimumInRotatedSortedArray.java │ │ ├── FindTheDuplicateNumber.java │ │ ├── FirstAndLastPositionOfElementInSortedArray.java │ │ ├── FruitIntoBaskets.java │ │ ├── GasStation.java │ │ ├── GenerateParantheses.java │ │ ├── GroupAnagrams.java │ │ ├── HouseRobber.java │ │ ├── HouseRobberII.java │ │ ├── HouseRobberIII.java │ │ ├── InsertInterval.java │ │ ├── JumpGame.java │ │ ├── JumpGameII.java │ │ ├── JumpGameIII.java │ │ ├── KClosestPointsToOrigin.java │ │ ├── KokoEatingBananas.java │ │ ├── LRUCache.java │ │ ├── LengthOfLongestFibonacciSubsequence.java │ │ ├── LinkedListCycleII.java │ │ ├── LongestCommonSubsequence.java │ │ ├── LongestConsecutiveSequence.java │ │ ├── LongestIncreasingSubsequence.java │ │ ├── LongestPalindromicSubstring.java │ │ ├── LongestRepeatingCharacterReplacement.java │ │ ├── LongestSubstringWithoutRepeatingCharacters.java │ │ ├── LowestCommonAncestorOfBinaryTree.java │ │ ├── MaxConsecutiveOnesIII.java │ │ ├── MaximalSquare.java │ │ ├── MaximumBinaryTree.java │ │ ├── MaximumLengthOfRepeatedSubarray.java │ │ ├── MaximumLevelSumOfABinaryTree.java │ │ ├── MaximumProductAfterKIncrements.java │ │ ├── MaximumProductSubarray.java │ │ ├── MaximumVowelsInASubstring.java │ │ ├── MergeIntervals.java │ │ ├── MinStack.java │ │ ├── MinimumDominoRotationsForEqualRow.java │ │ ├── MinimumIncrementToMakeArrayUnique.java │ │ ├── MinimumSizeSubarraySum.java │ │ ├── NonOverlappingIntervals.java │ │ ├── NumberOfDiceRollsWIthTargetSum.java │ │ ├── NumberOfIslands.java │ │ ├── OddEvenLinkedList.java │ │ ├── OnlineStockSpan.java │ │ ├── PalindromicSubstrings.java │ │ ├── PartitionLabels.java │ │ ├── Permutations.java │ │ ├── PermutationsII.java │ │ ├── ProductOfArrayExceptSelf.java │ │ ├── RemoveNthNodeFromEndOfList.java │ │ ├── ReorderList.java │ │ ├── ReorganizeString.java │ │ ├── ReverseLinkedListII.java │ │ ├── ReverseWordsInAString.java │ │ ├── RotateImage.java │ │ ├── RottingOranges.java │ │ ├── SearchA2DMatrix.java │ │ ├── SearchA2DMatrixII.java │ │ ├── SearchInRotatedSortedArray.java │ │ ├── SetMatrixZeroes.java │ │ ├── SortColors.java │ │ ├── SpiralMatrix.java │ │ ├── SubArraySumDivisibleByK.java │ │ ├── SubArraySumEqualsK.java │ │ ├── Subsets.java │ │ ├── SubsetsII.java │ │ ├── SubtreeOfAnotherTree.java │ │ ├── SumOfSquareNumbers.java │ │ ├── SwapForLongestRepeatedCharacterSubstring.java │ │ ├── SwapNodesInPairs.java │ │ ├── TargetSum.java │ │ ├── ThreeSum.java │ │ ├── ThreeSumClosest.java │ │ ├── TicTacToe.java │ │ ├── TimeMap.java │ │ ├── TopKFrequentElements.java │ │ ├── TopKFrequentWords.java │ │ ├── Triangle.java │ │ ├── UniquePaths.java │ │ ├── UpdateMatrix.java │ │ ├── ValidSudoku.java │ │ ├── ValidTicTacToeState.java │ │ └── WordBreak.java │ └── util │ ├── AdjacencyListGraph.java │ ├── AdjacencyMatrixGraph.java │ ├── BinarySearch.java │ ├── BucketSort.java │ ├── CountingSort.java │ ├── DijkstraShortestPath.java │ ├── DoubleListNode.java │ ├── GenerateIntegers.java │ ├── GraphColoring.java │ ├── GraphEdge.java │ ├── HashMapExample.java │ ├── HashSetExample.java │ ├── LinearSearch.java │ ├── ListNode.java │ ├── MergeSort.java │ ├── MinimumSpanningTree.java │ ├── Node.java │ ├── QuickSort.java │ ├── RadixSort.java │ ├── ReadFromFile.java │ ├── StackUsingLinkedList.java │ ├── TreeNode.java │ ├── WeightedGraph.java │ └── WriteToFile.java └── test └── java ├── codility ├── ambitious │ └── IdenticalPairOfIndicesTest.java └── painless │ └── BinaryGapTest.java ├── hackerrank ├── algorithms │ ├── dynamicprogramming │ │ ├── EqualTest.java │ │ ├── LongestCommonSubstringTest.java │ │ └── SherLockAndCostTest.java │ ├── implementation │ │ ├── BetweenTwoSetsTest.java │ │ ├── NumberLineJumpsTest.java │ │ └── RepeatedStringTest.java │ ├── search │ │ ├── MinimumLossTest.java │ │ ├── MissingNumbersTest.java │ │ └── PairsTest.java │ ├── strings │ │ ├── BetterCompressionTest.java │ │ ├── CamelCaseTest.java │ │ ├── MakeAnagramsTest.java │ │ ├── SherlockAndTheValidStringTest.java │ │ ├── SuperReducedStringTest.java │ │ ├── TwoCharactersTest.java │ │ └── TwoStringsTest.java │ └── warmup │ │ └── BirthdayCakeCandlesTest.java └── datastructures │ ├── arrays │ └── LeftRotationTest.java │ ├── linkedlists │ ├── CycleDetectionTest.java │ ├── PrintInReverseTest.java │ ├── RemoveDuplicatesTest.java │ └── ReverseALinkedListTest.java │ ├── queues │ └── QueueUsingTwoStacksTest.java │ ├── stacks │ ├── BalancedBracketsTest.java │ ├── EqualStacksTest.java │ └── GameOfTwoStacksTest.java │ └── trees │ ├── HeightOfABinaryTreeTest.java │ └── IsBinarySearchTreeTest.java ├── leetcode ├── MissingNumberTest.java ├── easy │ ├── AverageOfLevelsInBinaryTreeTest.java │ ├── BackspaceStringCompareTest.java │ ├── BestTimeToBuyAndSellAStockIITest.java │ ├── BestTimeToBuyAndSellAStockTest.java │ ├── CheckIfPangramTest.java │ ├── ClimbingStairsTest.java │ ├── ContainsDuplicateIITest.java │ ├── ContainsDuplicateTest.java │ ├── CountCompleteTreeNodesTest.java │ ├── DiameterOfABinaryTreeTest.java │ ├── FibonacciNumberTest.java │ ├── FindAllNumbersDisappearedInAnArrayTest.java │ ├── FindCommonCharactersTest.java │ ├── FindPivotIndexTest.java │ ├── FirstUniqueCharacterInAStringTest.java │ ├── HappyNumberTest.java │ ├── IntersectionOfTwoArraysIITest.java │ ├── IntersectionOfTwoLinkedListsTest.java │ ├── InvertTreeTest.java │ ├── IsSubsequenceTest.java │ ├── IsomorphicStringsTest.java │ ├── JewelsAndStonesTest.java │ ├── KthMissingPositiveNumberTest.java │ ├── LastStoneWeightTest.java │ ├── LeftAndRightSumDifferencesTest.java │ ├── LengthOfLastWordTest.java │ ├── LongestCommonPrefixTest.java │ ├── MajorityElementTest.java │ ├── MatrixDiagonalSumTest.java │ ├── MaxConsecutiveOnesTest.java │ ├── MaximumAverageSubarrayITest.java │ ├── MaximumDepthOfABinaryTreeTest.java │ ├── MaximumOddBinaryNumberTest.java │ ├── MaximumSubarrayTest.java │ ├── MergeTwoSortedListsTest.java │ ├── MiddleOfTheLinkedListTest.java │ ├── MinCostClimbingStairsTest.java │ ├── MinimumDepthBinaryTreeTest.java │ ├── MoveZeroesTest.java │ ├── NextGreaterElementITest.java │ ├── NumberOf1BitsTest.java │ ├── NumberOfGoodPairsTest.java │ ├── NumbersSmallerThanTheCurrentNumberTest.java │ ├── PalindromeLinkedListTest.java │ ├── PascalsTriangleTest.java │ ├── PathSumTest.java │ ├── RangeSumOfBSTTest.java │ ├── RansomNoteTest.java │ ├── RemoveLinkedListElementsTest.java │ ├── ReorderDataInLogFilesTest.java │ ├── ReverseOnlyLettersTest.java │ ├── ReversePrefixOfWordTest.java │ ├── ReverseWordsInAString3Test.java │ ├── ReverseWordsInAStringIIITest.java │ ├── SameTreeTest.java │ ├── SearchInsertPositionTest.java │ ├── ShuffleStringTest.java │ ├── SingleNumberTest.java │ ├── SortingTheSentenceTest.java │ ├── SquaresOfSortedArrayTest.java │ ├── SumOfUniqueElementsTest.java │ ├── SymmetricTreeTest.java │ ├── TwoSumTest.java │ ├── UglyNumberTest.java │ ├── ValidAnagramTest.java │ ├── ValidPalindromeIITest.java │ ├── ValidPalindromeTest.java │ ├── ValidParanthesesTest.java │ └── ValidPerfectSquareTest.java ├── hard │ ├── LongestValidParenthesesTest.java │ ├── MedianOfTwoSortedArraysTest.java │ ├── MinimumWindowSubstringTest.java │ ├── SerializeAndDeserializeABinaryTreeTest.java │ ├── TrappingRainWaterIITest.java │ └── TrappingRainWaterTest.java └── medium │ ├── AddTwoNumbersIITest.java │ ├── AddTwoNumbersTest.java │ ├── BinaryTreeFromPreorderInOrderTraversalTest.java │ ├── BinaryTreeRightSideViewTest.java │ ├── BinaryTreeZigzagLevelOrderTraversalTest.java │ ├── BoatsToSavePeopleTest.java │ ├── CapacityToShipPackagesWithinDDaysTest.java │ ├── CoinChangeTest.java │ ├── ContainerWithMostWaterTest.java │ ├── ContiguousArrayTest.java │ ├── CopyListWithRandomPointerTest.java │ ├── CountServersThatCommunicateTest.java │ ├── DailyTemperaturesTest.java │ ├── DecodeStringTest.java │ ├── DecodeWaysTest.java │ ├── DeleteDuplicatesFromSortedListIITest.java │ ├── EditDistanceTest.java │ ├── FindAllAnagramsInAStringTest.java │ ├── FindAllDuplicatesInAnArrayTest.java │ ├── FindMinimumInRotatedSortedArrayTest.java │ ├── FindTheDuplicateNumberTest.java │ ├── FirstAndLastPositionOfElementInSortedArrayTest.java │ ├── FruitIntoBasketsTest.java │ ├── GasStationTest.java │ ├── GenerateParanthesesTest.java │ ├── GroupAnagramsTest.java │ ├── HouseRobberIIITest.java │ ├── HouseRobberIITest.java │ ├── HouseRobberTest.java │ ├── InsertIntervalTest.java │ ├── JumpGameIIITest.java │ ├── JumpGameIITest.java │ ├── JumpGameTest.java │ ├── KokoEatingBananasTest.java │ ├── LRUCacheTest.java │ ├── LengthOfLongestFibonacciSubsequenceTest.java │ ├── LongestCommonSubsequenceTest.java │ ├── LongestConsecutiveSequenceTest.java │ ├── LongestIncreasingSubsequenceTest.java │ ├── LongestPalindromicSubstringTest.java │ ├── LongestRepeatingCharacterReplacementTest.java │ ├── LongestSubstringWithoutRepeatingCharactersTest.java │ ├── LowestCommonAncestorOfBinaryTreeTest.java │ ├── MaxConsecutiveOnesIIITest.java │ ├── MaximalSquareTest.java │ ├── MaximumBinaryTreeTest.java │ ├── MaximumLengthOfRepeatedSubarrayTest.java │ ├── MaximumProductAfterKIncrementsTest.java │ ├── MaximumProductSubarrayTest.java │ ├── MaximumVowelsInASubstringTest.java │ ├── MergeIntervalsTest.java │ ├── MinStackTest.java │ ├── MinimumDominoRotationsForEqualRowTest.java │ ├── MinimumIncrementToMakeArrayUniqueTest.java │ ├── MinimumSizeSubarraySumTest.java │ ├── NonOverlappingIntervalsTest.java │ ├── NumberOfIslandsTest.java │ ├── OddEvenLinkedListTest.java │ ├── OnlineStockSpanTest.java │ ├── PalindromicSubstringsTest.java │ ├── PartitionLabelsTest.java │ ├── PermutationsIITest.java │ ├── PermutationsTest.java │ ├── ProductOfArrayExceptSelfTest.java │ ├── RemoveNthNodeFromEndOfListTest.java │ ├── ReorderListTest.java │ ├── ReorganizeStringTest.java │ ├── ReverseLinkedListIITest.java │ ├── ReverseWordsInAStringTest.java │ ├── RotateImageTest.java │ ├── RottingOrangesTest.java │ ├── SearchA2DMatrixTest.java │ ├── SearchInRotatedSortedArrayTest.java │ ├── SetMatrixZeroesTest.java │ ├── SortColorsTest.java │ ├── SpiralMatrixTest.java │ ├── SubsetsIITest.java │ ├── SubsetsTest.java │ ├── SubtreeOfAnotherTreeTest.java │ ├── SumOfSquareNumbersTest.java │ ├── SwapNodesInPairsTest.java │ ├── TargetSumTest.java │ ├── ThreeSumClosestTest.java │ ├── ThreeSumTest.java │ ├── TicTacToeTest.java │ ├── TimeMapTest.java │ ├── TopKFrequentElementsTest.java │ ├── TopKFrequentWordsTest.java │ ├── TriangleTest.java │ ├── UniquePathsTest.java │ ├── UpdateMatrixTest.java │ ├── ValidSudokuTest.java │ ├── ValidTicTacToeStateTest.java │ └── WordBreakTest.java └── util ├── BinarySearchTest.java ├── BucketSortTest.java ├── CountingSortTest.java ├── LinearSearchTest.java ├── MergeSortTest.java ├── QuickSortTest.java └── RadixSortTest.java /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [nikoo28] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: ['buymeacoffee.com/studyalgorithms'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /src/main/java/codility/painless/BinaryGap.java: -------------------------------------------------------------------------------- 1 | package codility.painless; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-08-25 16:31 5 | */ 6 | 7 | class BinaryGap { 8 | 9 | int solution(int n) { 10 | // write your code in Java SE 8 11 | 12 | String binaryString = Integer.toBinaryString(n); 13 | // System.out.println(binaryString); 14 | 15 | int largestGap = 0; 16 | for (int i = 1; i < binaryString.length(); i++) { 17 | int gap = 0; 18 | while (binaryString.charAt(i) == '0') { 19 | gap++; 20 | i++; 21 | 22 | if (i == binaryString.length()) { 23 | gap = 0; 24 | break; 25 | } 26 | } 27 | 28 | if (gap > largestGap) 29 | largestGap = gap; 30 | } 31 | 32 | return largestGap; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/codility/painless/CyclicRotation.java: -------------------------------------------------------------------------------- 1 | package codility.painless; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-08-25 20:03 5 | */ 6 | 7 | class CyclicRotation { 8 | 9 | public int[] solution(int[] nums, int k) { 10 | // write your code in Java SE 8 11 | 12 | if (nums.length == 0) 13 | return nums; 14 | 15 | k %= nums.length; 16 | reverse(nums, 0, nums.length - 1); 17 | reverse(nums, 0, k - 1); 18 | reverse(nums, k, nums.length - 1); 19 | 20 | return nums; 21 | } 22 | 23 | private void reverse(int[] nums, int start, int end) { 24 | while (start < end) { 25 | int temp = nums[start]; 26 | nums[start] = nums[end]; 27 | nums[end] = temp; 28 | start++; 29 | end--; 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/codility/painless/OddOccurencesInAnArray.java: -------------------------------------------------------------------------------- 1 | package codility.painless; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-08-25 19:51 5 | */ 6 | 7 | class OddOccurencesInAnArray { 8 | 9 | public int solution(int[] A) { 10 | // write your code in Java SE 8 11 | 12 | int answer = 0; 13 | for (int i : A) { 14 | answer = answer ^ i; 15 | } 16 | 17 | return answer; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/dynamicprogramming/Equal.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.dynamicprogramming; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by nikoo28 on 2/14/21 12:48 AM 7 | */ 8 | 9 | public class Equal { 10 | 11 | int equal(int[] arr) { 12 | 13 | // Store all the possibilities 14 | int[] possibilities = new int[5]; 15 | 16 | // Start with the minimum element 17 | int minimum = Arrays.stream(arr).min().getAsInt(); 18 | 19 | for (int i = 0; i < possibilities.length; i++) { 20 | 21 | for (int k : arr) { 22 | int diff = k - minimum; 23 | int stepsRequired = diff / 5 + (diff % 5) / 2 + ((diff % 5) % 2) / 1; 24 | possibilities[i] += stepsRequired; 25 | } 26 | minimum--; 27 | } 28 | 29 | // Return the minimum number out of all the possibilities 30 | return Arrays.stream(possibilities).min().getAsInt(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/dynamicprogramming/LongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.dynamicprogramming; 2 | 3 | public class LongestCommonSubstring { 4 | 5 | int longestCommonSubstring(String m, String n) { 6 | char[] str1 = m.toCharArray(); 7 | char[] str2 = n.toCharArray(); 8 | 9 | int[][] dp = new int[str1.length + 1][str2.length + 1]; 10 | 11 | int max = 0; 12 | 13 | // Iterate over each position in the matrix 14 | for (int i = 1; i <= str1.length; i++) 15 | for (int j = 1; j <= str2.length; j++) 16 | 17 | // If characters are equal 18 | if (str1[i - 1] == str2[j - 1]) { 19 | // Get the number from diagonally opposite 20 | // and add 1 21 | dp[i][j] = dp[i - 1][j - 1] + 1; 22 | 23 | max = Math.max(dp[i][j], max); 24 | } 25 | 26 | return max; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/implementation/NumberLineJumps.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.implementation; 2 | 3 | /** 4 | * Created by nikoo28 on 3/14/21 6:30 PM 5 | */ 6 | 7 | public class NumberLineJumps { 8 | 9 | String kangaroo(int x1, int v1, int x2, int v2) { 10 | 11 | if (v1 <= v2) 12 | return "NO"; 13 | 14 | if ((x2 - x1) % (v1 - v2) == 0) 15 | return "YES"; 16 | else 17 | return "NO"; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/implementation/RepeatedString.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.implementation; 2 | 3 | /** 4 | * Created by nikoo28 on 3/14/21 4:34 PM 5 | */ 6 | 7 | public class RepeatedString { 8 | 9 | long repeatedString(String s, long n) { 10 | 11 | long strLength = s.length(); 12 | 13 | // Count the number of 'a' in the given string 14 | int count = 0; 15 | for (int i = 0; i < strLength; i++) { 16 | if (s.charAt(i) == 'a') { 17 | ++count; 18 | } 19 | } 20 | 21 | long repeatedTimes = n / strLength; 22 | 23 | // Find the length of string left after repetitions 24 | long stringLeftLength = n - (strLength * repeatedTimes); 25 | 26 | // Count the remaining repetitions 27 | int extra = 0; 28 | for (int i = 0; i < stringLeftLength; i++) { 29 | if (s.charAt(i) == 'a') { 30 | ++extra; 31 | } 32 | } 33 | 34 | long totalCount = (repeatedTimes * count) + extra; 35 | 36 | return totalCount; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/search/MinimumLoss.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.search; 2 | 3 | import java.util.*; 4 | 5 | public class MinimumLoss { 6 | 7 | public int minimumLoss(List prices) { 8 | 9 | // Index all the elements 10 | Map priceIndexMap = new HashMap<>(); 11 | for (int i = 0; i < prices.size(); i++) { 12 | priceIndexMap.put(prices.get(i), i); 13 | } 14 | 15 | Collections.sort(prices); 16 | long minimumLoss = Long.MAX_VALUE; 17 | 18 | // Start from the end 19 | for (int i = prices.size() - 1; i > 0 ; i--) { 20 | 21 | // Reject the invalid values 💣 22 | if (priceIndexMap.get(prices.get(i)) > 23 | priceIndexMap.get(prices.get(i-1))) 24 | continue; 25 | 26 | long dayLoss = prices.get(i) - prices.get(i-1); 27 | minimumLoss = Math.min(dayLoss, minimumLoss); 28 | } 29 | 30 | return (int) minimumLoss; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/search/Pairs.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.search; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by nikoo28 on 10/1/20 10:23 PM 7 | */ 8 | 9 | public class Pairs { 10 | 11 | private boolean binarySearch(int[] arr, int numberToFind) { 12 | int left = 0, right = arr.length - 1; 13 | while (left <= right) { 14 | int mid = left + (right - left) / 2; 15 | if (arr[mid] == numberToFind) return true; 16 | if (arr[mid] < numberToFind) left = mid + 1; 17 | else right = mid - 1; 18 | } 19 | return false; 20 | } 21 | 22 | public int pairs(int k, int[] arr) { 23 | 24 | // Sort the array 25 | Arrays.sort(arr); 26 | 27 | int result = 0; 28 | for (int i : arr) { 29 | int numberToSearch = i - k; 30 | if (binarySearch(arr, numberToSearch)) { 31 | result++; 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/strings/CamelCase.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.strings; 2 | 3 | public class CamelCase { 4 | 5 | public int camelcase(String s) { 6 | int numberOfWords = 0; 7 | 8 | for (int i = 0; i < s.length(); i++) { 9 | // Get the character 10 | char c = s.charAt(i); 11 | 12 | // Check if the character is a capital letter 13 | if (c >= 'A' && c <= 'Z') { 14 | // This is a start of new word 15 | numberOfWords++; 16 | } 17 | } 18 | 19 | // Since the first word starts with a small letter 20 | numberOfWords = numberOfWords + 1; 21 | 22 | return numberOfWords; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/algorithms/strings/MakeAnagrams.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.strings; 2 | 3 | /** 4 | * Created by nikoo28 on 2/21/21 3:59 AM 5 | */ 6 | 7 | public class MakeAnagrams { 8 | 9 | int makingAnagrams(String s1, String s2) { 10 | 11 | int[] c = new int[26]; 12 | s1 = s1.toLowerCase(); 13 | s2 = s2.toLowerCase(); 14 | 15 | for (int i = 0; i < s1.length(); i++) { 16 | c[s1.charAt(i) - 'a']++; 17 | } 18 | 19 | for (int i = 0; i < s2.length(); i++) { 20 | c[s2.charAt(i) - 'a']--; 21 | } 22 | 23 | int total = 0; 24 | for (int i : c) { 25 | total += Math.abs(i); 26 | } 27 | 28 | return total; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/datastructures/linkedlists/PrintInReverse.java: -------------------------------------------------------------------------------- 1 | package hackerrank.datastructures.linkedlists; 2 | 3 | import util.ListNode; 4 | 5 | import java.util.Stack; 6 | 7 | /** 8 | * Created by nikoo28 on 3/21/21 12:00 AM 9 | */ 10 | 11 | public class PrintInReverse { 12 | 13 | void reversePrintUsingStack(ListNode head) { 14 | 15 | Stack valueStack = new Stack<>(); 16 | 17 | // Add all the elements to the stack 18 | while (head != null) { 19 | valueStack.push(head.val); 20 | head = head.next; 21 | } 22 | 23 | // Actually print the elements 24 | while (!valueStack.isEmpty()) { 25 | System.out.println(valueStack.pop()); 26 | } 27 | } 28 | 29 | void reversePrintUsingRecursion(ListNode head) { 30 | 31 | // Terminating condition 32 | if (head.next == null) 33 | return; 34 | 35 | // Recursive call 36 | reversePrintUsingRecursion(head.next); 37 | 38 | // Actually print the value 39 | System.out.println(head.val); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/datastructures/linkedlists/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | package hackerrank.datastructures.linkedlists; 2 | 3 | import util.ListNode; 4 | 5 | public class RemoveDuplicates { 6 | 7 | ListNode removeDuplicates(ListNode head) { 8 | 9 | ListNode prev = head; 10 | ListNode temp = prev.next; 11 | 12 | while (temp != null) { 13 | if (temp.val == prev.val) { 14 | temp = temp.next; 15 | continue; 16 | } 17 | 18 | prev.next = temp; 19 | prev = temp; 20 | temp = temp.next; 21 | } 22 | 23 | prev.next = null; 24 | return head; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/datastructures/queues/QueueUsingTwoStacks.java: -------------------------------------------------------------------------------- 1 | package hackerrank.datastructures.queues; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * Created by nikoo28 on 12/26/20 5:58 PM 7 | */ 8 | 9 | public class QueueUsingTwoStacks { 10 | 11 | private Stack input = new Stack(); 12 | private Stack output = new Stack(); 13 | 14 | public void enqueue(int x) { 15 | input.push(x); 16 | } 17 | 18 | public int dequeue() { 19 | peek(); 20 | return output.pop(); 21 | } 22 | 23 | public int peek() { 24 | if (output.empty()) 25 | while (!input.empty()) 26 | output.push(input.pop()); 27 | return output.peek(); 28 | } 29 | 30 | public boolean isEmpty() { 31 | return input.empty() && output.empty(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/projecteuler/Problem2.java: -------------------------------------------------------------------------------- 1 | package hackerrank.projecteuler; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by nikhil.lohia on 08/04/2017. 7 | */ 8 | class Problem2 { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int t = in.nextInt(); 13 | for (int a0 = 0; a0 < t; a0++) { 14 | long n = in.nextLong(); 15 | System.out.println(solve(n)); 16 | } 17 | } 18 | 19 | private static long solve(long n) { 20 | long sum = 0; 21 | long a = 1; 22 | long b = 2; 23 | long temp = 0; 24 | while (temp < n) { 25 | if (b % 2 == 0) { 26 | sum += b; 27 | } 28 | temp = a + b; 29 | a = b; 30 | b = temp; 31 | } 32 | return sum; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/projecteuler/Problem3.java: -------------------------------------------------------------------------------- 1 | package hackerrank.projecteuler; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created by nikhil.lohia on 08/07/2017. 7 | */ 8 | 9 | class Problem3 { 10 | 11 | public static void main(String[] args) { 12 | 13 | Scanner scanner = new Scanner(System.in); 14 | int cases = scanner.nextInt(); 15 | for (int i = 0; i < cases; i++) { 16 | 17 | long N = scanner.nextLong(); 18 | 19 | long lastFactor = 0; 20 | while (N % 2 == 0) { 21 | N /= 2; 22 | lastFactor = 2; 23 | } 24 | 25 | for (long j = 3; j <= Math.sqrt(N); j += 2) { 26 | while (N % j == 0) { 27 | N /= j; 28 | lastFactor = j; 29 | } 30 | } 31 | 32 | if (N > 2) 33 | System.out.println(N); 34 | else 35 | System.out.println(lastFactor); 36 | } 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/projecteuler/Problem6.java: -------------------------------------------------------------------------------- 1 | package hackerrank.projecteuler; 2 | 3 | import java.util.Scanner; 4 | 5 | class Problem6 { 6 | 7 | public static void main(String[] args) { 8 | 9 | Scanner in = new Scanner(System.in); 10 | int t = in.nextInt(); 11 | for (int a0 = 0; a0 < t; a0++) { 12 | int n = in.nextInt(); 13 | 14 | long answer = n * (n - 1) * (n + 1) * (3 * n + 2) / 12; 15 | System.out.println(answer); 16 | } 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/leetcode/AddDigits.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/17/17 5 | */ 6 | class AddDigits { 7 | 8 | public int addDigits(int num) { 9 | return 1 + (num - 1) % 9; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/leetcode/AlmostPalindromes.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/15/17 5 | */ 6 | class AlmostPalindromes { 7 | 8 | public static int almost_palindromes(String str) { 9 | 10 | StringBuilder sb = new StringBuilder(str); 11 | String reversed = sb.reverse().toString(); 12 | 13 | int count = 0; 14 | 15 | for (int i = 0; i < str.length(); i++) { 16 | if (str.charAt(i) != reversed.charAt(i)) 17 | count++; 18 | } 19 | 20 | return count; 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ArrayNesting.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 6/3/19 1:43 AM 5 | */ 6 | 7 | class ArrayNesting { 8 | 9 | private int findSetS(int[] nums) { 10 | boolean[] visited = new boolean[nums.length]; 11 | int res = 0; 12 | for (int i = 0; i < nums.length; i++) { 13 | if (!visited[i]) { 14 | int start = nums[i], count = 0; 15 | do { 16 | start = nums[start]; 17 | count++; 18 | visited[start] = true; 19 | } while (start != nums[i]); 20 | res = Math.max(res, count); 21 | } 22 | } 23 | return res; 24 | } 25 | 26 | public static void main(String[] args) { 27 | 28 | ArrayNesting arrayNesting = new ArrayNesting(); 29 | 30 | int[] arr = new int[]{5, 4, 0, 3, 1, 6, 2}; 31 | System.out.println(arrayNesting.findSetS(arr)); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ArrayPartition1.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * @author nikoo28 on 9/10/17 7 | */ 8 | class ArrayPartition1 { 9 | 10 | public int arrayPairSum(int[] nums) { 11 | 12 | Arrays.sort(nums); 13 | 14 | int sum = 0; 15 | for (int i = 0; i < nums.length; i += 2) { 16 | sum += Math.min(nums[i], nums[i + 1]); 17 | } 18 | 19 | return sum; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/leetcode/AssignCookies.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by nikoo28 on 12/17/17 8:50 PM 7 | */ 8 | 9 | class AssignCookies { 10 | 11 | public int findContentChildren(int[] g, int[] s) { 12 | Arrays.sort(g); 13 | Arrays.sort(s); 14 | 15 | int count = 0; 16 | 17 | for (int i = 0; i < s.length; i++) { 18 | 19 | if (count == g.length) break; 20 | 21 | while (g[count] > s[i]) { 22 | i++; 23 | if (i == s.length) 24 | break; 25 | } 26 | 27 | if (i == s.length) break; 28 | count++; 29 | } 30 | 31 | return count; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/AverageOfLevelsInBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | import java.util.Queue; 9 | 10 | /** 11 | * @author nikoo28 on 9/10/17 12 | */ 13 | class AverageOfLevelsInBinaryTree { 14 | 15 | public List averageOfLevels(TreeNode root) { 16 | List result = new ArrayList<>(); 17 | Queue q = new LinkedList<>(); 18 | 19 | if (root == null) return result; 20 | q.add(root); 21 | while (!q.isEmpty()) { 22 | int n = q.size(); 23 | double sum = 0.0; 24 | for (int i = 0; i < n; i++) { 25 | TreeNode node = q.poll(); 26 | sum += node.val; 27 | if (node.left != null) q.offer(node.left); 28 | if (node.right != null) q.offer(node.right); 29 | } 30 | result.add(sum / n); 31 | } 32 | return result; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/BinaryNumberWithAlternatingBits.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/16/17 10:43 PM 5 | */ 6 | 7 | class BinaryNumberWithAlternatingBits { 8 | 9 | public boolean hasAlternatingBits(int n) { 10 | 11 | if (n == 0) 12 | return true; 13 | 14 | int prev = n % 2; 15 | n = n / 2; 16 | 17 | while (n > 0) { 18 | 19 | int x = n % 2; 20 | if (x == prev) 21 | return false; 22 | else 23 | prev = x; 24 | 25 | n = n / 2; 26 | } 27 | 28 | return true; 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/BinaryTreeInOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Stack; 8 | 9 | /** 10 | * Created by nikoo28 on 12/19/17 1:22 AM 11 | */ 12 | 13 | class BinaryTreeInOrderTraversal { 14 | 15 | public List inorderTraversal(TreeNode root) { 16 | 17 | List list = new ArrayList<>(); 18 | 19 | Stack stack = new Stack<>(); 20 | TreeNode cur = root; 21 | 22 | while (cur != null || !stack.empty()) { 23 | while (cur != null) { 24 | stack.add(cur); 25 | cur = cur.left; 26 | } 27 | cur = stack.pop(); 28 | list.add(cur.val); 29 | cur = cur.right; 30 | } 31 | 32 | return list; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/Brackets.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * @author nikoo28 on 9/15/17 7 | */ 8 | class Brackets { 9 | 10 | public static int bracketMatch(String bracketString) { 11 | 12 | Stack chars = new Stack<>(); 13 | 14 | for (int i = 0; i < bracketString.length(); i++) { 15 | 16 | if (bracketString.charAt(i) == '(') 17 | chars.push('('); 18 | 19 | else 20 | chars.pop(); 21 | } 22 | 23 | return chars.size(); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ConstructRectangle.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 3:23 AM 5 | */ 6 | 7 | class ConstructRectangle { 8 | 9 | public int[] constructRectangle(int area) { 10 | 11 | int w = (int) Math.sqrt(area); 12 | while (area % w != 0) w--; 13 | return new int[]{area / w, w}; 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ConstructStringFromBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | /** 6 | * Created by nikoo28 on 12/17/17 3:01 AM 7 | */ 8 | 9 | class ConstructStringFromBinaryTree { 10 | 11 | private String tree2str(TreeNode t) { 12 | 13 | if (t == null) 14 | return ""; 15 | 16 | String result = t.val + ""; 17 | 18 | String left = tree2str(t.left); 19 | String right = tree2str(t.right); 20 | 21 | if (left.equals("") && right.equals("")) return result; 22 | if (left.equals("")) return result + "()" + "(" + right + ")"; 23 | if (right.equals("")) return result + "(" + left + ")"; 24 | return result + "(" + left + ")" + "(" + right + ")"; 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ConvertSortedArrayToBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | /** 6 | * Created by nikoo28 on 9/23/18 12:57 PM 7 | */ 8 | 9 | class ConvertSortedArrayToBinarySearchTree { 10 | 11 | public TreeNode sortedArrayToBst(int[] nums) { 12 | 13 | if (nums.length == 0) 14 | return null; 15 | 16 | return helper(nums, 0, nums.length - 1); 17 | } 18 | 19 | private TreeNode helper(int[] nums, int low, int high) { 20 | if (low > high) 21 | return null; 22 | 23 | int mid = (low + high) / 2; 24 | TreeNode node = new TreeNode(mid); 25 | node.left = helper(nums, low, mid - 1); 26 | node.right = helper(nums, mid + 1, high); 27 | return node; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/CountBinaryStrings.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 1:50 AM 5 | */ 6 | 7 | class CountBinaryStrings { 8 | 9 | private int countBinarySubstrings(String s) { 10 | 11 | int prevRunLength = 0, curRunLength = 1, res = 0; 12 | for (int i = 1; i < s.length(); i++) { 13 | if (s.charAt(i) == s.charAt(i - 1)) curRunLength++; 14 | else { 15 | prevRunLength = curRunLength; 16 | curRunLength = 1; 17 | } 18 | if (prevRunLength >= curRunLength) res++; 19 | } 20 | return res; 21 | 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(new CountBinaryStrings().countBinarySubstrings("00110011")); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/DetectCapital.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/17/17 5 | */ 6 | class DetectCapital { 7 | 8 | public boolean detectCapitalUse(String word) { 9 | return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+"); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/leetcode/DiameterOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | /** 6 | * Created by nikoo28 on 9/23/18 11:07 PM 7 | */ 8 | 9 | class DiameterOfBinaryTree { 10 | 11 | private int ans; 12 | 13 | public int diameterOfBinaryTree(TreeNode root) { 14 | 15 | ans = 1; 16 | depth(root); 17 | return ans - 1; 18 | } 19 | 20 | private int depth(TreeNode root) { 21 | if (root == null) 22 | return 0; 23 | 24 | int left = depth(root.left); 25 | int right = depth(root.right); 26 | ans = Math.max(ans, left + right + 1); 27 | return Math.max(left, right) + 1; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/DistributeCandies.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * @author nikoo28 on 9/10/17 8 | */ 9 | class DistributeCandies { 10 | 11 | public int distributeCandies(int[] candies) { 12 | 13 | Set kinds = new HashSet<>(); 14 | for (int candy : candies) { 15 | kinds.add(candy); 16 | } 17 | return Math.min(kinds.size(), candies.length / 2); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/leetcode/DoubleListNode.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 10:41 PM 5 | */ 6 | 7 | public class DoubleListNode { 8 | public int key; 9 | public int val; 10 | public DoubleListNode next; 11 | public DoubleListNode prev; 12 | } -------------------------------------------------------------------------------- /src/main/java/leetcode/EncodeDecodeTinyUrl.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by nikoo28 on 2019-07-20 17:36 8 | */ 9 | 10 | class EncodeDecodeTinyUrl { 11 | 12 | private Map map = new HashMap<>(); 13 | private int i = 0; 14 | 15 | public String encode(String longUrl) { 16 | map.put(i, longUrl); 17 | return "http://tinyurl.com/" + i++; 18 | } 19 | 20 | public String decode(String shortUrl) { 21 | return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""))); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ExcelSheetColumnNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 2:40 PM 5 | */ 6 | 7 | class ExcelSheetColumnNumber { 8 | 9 | public int titleToNumber(String s) { 10 | 11 | int power = 0; 12 | char[] cell = s.toCharArray(); 13 | int col = 0; 14 | for (int i = cell.length - 1; i >= 0; i--) { 15 | 16 | int factor = (int) Math.pow(26.0, power++); 17 | col += (factor * (cell[i] - 'A' + 1)); 18 | } 19 | 20 | return col; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FinKthLargest.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by nikoo28 on 7/18/19 2:32 AM 7 | */ 8 | 9 | class FinKthLargest { 10 | 11 | public int fingKthLargest(int[] nums, int k) { 12 | final int N = nums.length; 13 | Arrays.sort(nums); 14 | return nums[N - k]; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FindAllNumbersDisappearedInArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author nikoo28 on 9/17/17 8 | */ 9 | class FindAllNumbersDisappearedInArray { 10 | 11 | public List findDisappearedNumbers(int[] nums) { 12 | 13 | List ret = new ArrayList<>(); 14 | 15 | for (int i = 0; i < nums.length; i++) { 16 | int val = Math.abs(nums[i]) - 1; 17 | if (nums[val] > 0) { 18 | nums[val] = -nums[val]; 19 | } 20 | } 21 | 22 | for (int i = 0; i < nums.length; i++) { 23 | if (nums[i] > 0) { 24 | ret.add(i + 1); 25 | } 26 | } 27 | return ret; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FindAnagramMappings.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * Created by nikoo28 on 9/22/18 5:17 PM 7 | */ 8 | 9 | class FindAnagramMappings { 10 | 11 | public int[] anagramMappings(int[] A, int[] B) { 12 | 13 | HashMap integerLocationMap = new HashMap<>(); 14 | 15 | for (int i = 0; i < A.length; i++) { 16 | integerLocationMap.put(A[i], i); 17 | } 18 | 19 | int[] P = new int[A.length]; 20 | for (int i = 0; i < B.length; i++) { 21 | P[i] = integerLocationMap.get(B[i]); 22 | } 23 | 24 | return P; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FindComplement.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by nikoo28 on 12/16/17 2:08 PM 8 | */ 9 | 10 | class FindComplement { 11 | 12 | public int findComplement(int num) { 13 | 14 | List binary = new ArrayList<>(); 15 | while (num > 0) { 16 | binary.add(num % 2 == 0 ? 1 : 0); 17 | num /= 2; 18 | } 19 | 20 | int complement = 0; 21 | int counter = 0; 22 | 23 | for (Integer bin : binary) { 24 | complement += (Math.pow(2, counter++) * bin); 25 | } 26 | 27 | return complement; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FindTheDifference.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/17/17 5 | */ 6 | class FindTheDifference { 7 | 8 | public char findTheDifference(String s, String t) { 9 | 10 | int[] freq = new int[26]; 11 | for (int i = 0; i < s.length(); i++) { 12 | freq[s.charAt(i) - 'a']++; 13 | } 14 | 15 | for (int i = 0; i < t.length(); i++) { 16 | freq[t.charAt(i) - 'a']--; 17 | if (freq[t.charAt(i) - 'a'] == -1) 18 | return t.charAt(i); 19 | } 20 | 21 | return 'a'; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FirstUniqueCharacterInString.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 9:01 PM 5 | */ 6 | 7 | class FirstUniqueCharacterInString { 8 | 9 | public int firstUniqChar(String s) { 10 | 11 | int[] freq = new int[26]; 12 | for (int i = 0; i < s.length(); i++) freq[s.charAt(i) - 'a']++; 13 | for (int i = 0; i < s.length(); i++) if (freq[s.charAt(i) - 'a'] == 1) return i; 14 | return -1; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author nikoo28 on 9/10/17 8 | */ 9 | class FizzBuzz { 10 | public List fizzBuzz(int n) { 11 | 12 | List resultList = new ArrayList<>(); 13 | 14 | for (int i = 1, fizz = 0, buzz = 0; i <= n; i++) { 15 | fizz++; 16 | buzz++; 17 | 18 | if (fizz == 3 && buzz == 5) { 19 | resultList.add("FizzBuzz"); 20 | fizz = 0; 21 | buzz = 0; 22 | continue; 23 | } 24 | 25 | if (fizz == 3) { 26 | resultList.add("Fizz"); 27 | fizz = 0; 28 | continue; 29 | } 30 | 31 | if (buzz == 5) { 32 | resultList.add("Buzz"); 33 | buzz = 0; 34 | continue; 35 | } 36 | resultList.add(Integer.toString(i)); 37 | } 38 | 39 | return resultList; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/FourLetterWords.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/15/17 5 | */ 6 | class FourLetterWords { 7 | 8 | public static int four_letter_words(String sentence) { 9 | String[] split = sentence.split(" "); 10 | int count = 0; 11 | for (String s : split) { 12 | if (s.length() == 4) 13 | count++; 14 | } 15 | return count; 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/leetcode/HammingDistance.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | class HammingDistance { 4 | 5 | public int hammingDistance(int x, int y) { 6 | 7 | return Integer.bitCount(x ^ y); 8 | } 9 | 10 | } -------------------------------------------------------------------------------- /src/main/java/leetcode/IntersectionOfTwoArrays.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by nikoo28 on 12/17/17 3:03 PM 8 | */ 9 | 10 | class IntersectionOfTwoArrays { 11 | 12 | public int[] intersection(int[] nums1, int[] nums2) { 13 | 14 | Set set1 = new HashSet<>(); 15 | Set result = new HashSet<>(); 16 | 17 | for (int num : nums1) set1.add(num); 18 | for (int num : nums2) if (set1.contains(num)) result.add(num); 19 | 20 | int[] intersection = new int[result.size()]; 21 | int idx = 0; 22 | for (Integer num : result) intersection[idx++] = num; 23 | 24 | return intersection; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.Deque; 6 | import java.util.LinkedList; 7 | 8 | /** 9 | * @author nikoo28 on 9/17/17 10 | */ 11 | class InvertBinaryTree { 12 | 13 | public TreeNode invertTree(TreeNode root) { 14 | 15 | if (root == null) { 16 | return null; 17 | } 18 | 19 | final Deque stack = new LinkedList<>(); 20 | stack.push(root); 21 | 22 | while (!stack.isEmpty()) { 23 | final TreeNode node = stack.pop(); 24 | final TreeNode left = node.left; 25 | node.left = node.right; 26 | node.right = left; 27 | 28 | if (node.left != null) { 29 | stack.push(node.left); 30 | } 31 | if (node.right != null) { 32 | stack.push(node.right); 33 | } 34 | } 35 | return root; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/leetcode/JewelsAndStones.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Created by nikoo28 on 7/16/19 2:27 AM 7 | */ 8 | 9 | class JewelsAndStones { 10 | 11 | public int numJewelsInStones(String J, String S) { 12 | 13 | HashSet Jset = new HashSet<>(); 14 | for (char j : J.toCharArray()) 15 | Jset.add(j); 16 | 17 | int ans = 0; 18 | for (char s : S.toCharArray()) 19 | if (Jset.contains(s)) 20 | ans++; 21 | return ans; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/JudgeRouteCircle.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | class JudgeRouteCircle { 4 | 5 | public boolean judgeCircle(String moves) { 6 | 7 | int x = 0; 8 | int y = 0; 9 | 10 | for (int i = 0; i < moves.length(); i++) { 11 | 12 | switch (moves.charAt(i)) { 13 | 14 | case 'U': 15 | y++; 16 | break; 17 | 18 | case 'D': 19 | y--; 20 | break; 21 | 22 | case 'L': 23 | x--; 24 | break; 25 | 26 | case 'R': 27 | x++; 28 | break; 29 | } 30 | } 31 | 32 | return x == 0 && y == 0; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/LeafSimilar.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * Created by nikoo28 on 9/22/18 7:28 PM 10 | */ 11 | 12 | class LeafSimilar { 13 | 14 | public boolean leafSimilar(TreeNode root1, TreeNode root2) { 15 | 16 | List leafSequence1 = new ArrayList<>(); 17 | List leafSequence2 = new ArrayList<>(); 18 | 19 | traverse(leafSequence1, root1); 20 | traverse(leafSequence2, root2); 21 | 22 | return leafSequence1.equals(leafSequence2); 23 | } 24 | 25 | private void traverse(List leafSequence, TreeNode root) { 26 | 27 | if (root == null) 28 | return; 29 | 30 | if (root.left == null && root.right == null) { 31 | leafSequence.add(root.val); 32 | return; 33 | } 34 | 35 | traverse(leafSequence, root.left); 36 | traverse(leafSequence, root.right); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/leetcode/LengthOfLongestPalindrome.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Created by nikoo28 on 4/30/18 7:54 PM 7 | */ 8 | 9 | class LengthOfLongestPalindrome { 10 | 11 | private static int longestPalindrome(String s) { 12 | 13 | if (s == null || s.length() == 0) 14 | return 0; 15 | 16 | HashSet hs = new HashSet<>(); 17 | int count = 0; 18 | 19 | for (int i = 0; i < s.length(); i++) { 20 | if (hs.contains(s.charAt(i))) { 21 | hs.remove(s.charAt(i)); 22 | count++; 23 | } else { 24 | hs.add(s.charAt(i)); 25 | } 26 | } 27 | if (!hs.isEmpty()) 28 | return count * 2 + 1; 29 | 30 | return count * 2; 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(longestPalindrome("abcda")); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/leetcode/LetterCombinations.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by nikoo28 on 7/18/19 3:21 AM 8 | */ 9 | 10 | class LetterCombinations { 11 | 12 | public static List letterCombinations(String digits) { 13 | String[] digitletter = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 14 | List result = new ArrayList<>(); 15 | 16 | if (digits.length()==0) return result; 17 | 18 | result.add(""); 19 | for (int i=0; i combine(String digit, List l) { 26 | List result = new ArrayList<>(); 27 | 28 | for (int i=0; i messageTime; 13 | 14 | public LoggerRateLimiter() { 15 | messageTime = new HashMap<>(); 16 | } 17 | 18 | public boolean shouldPrintMessage(int timestamp, String message) { 19 | if (!messageTime.containsKey(message)) 20 | return true; 21 | 22 | int lastTime = messageTime.get(message); 23 | if (timestamp - lastTime < 10) { 24 | messageTime.replace(message, timestamp); 25 | return false; 26 | } 27 | 28 | messageTime.replace(message, timestamp); 29 | return true; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/LongestUncommonSubsequence1.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/16/17 5 | */ 6 | class LongestUncommonSubsequence1 { 7 | 8 | public int findLUSlength(String a, String b) { 9 | 10 | return a.equals(b) ? -1 : Math.max(a.length(), b.length()); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/leetcode/MaxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/16/17 5 | */ 6 | class MaxConsecutiveOnes { 7 | 8 | public int findMaxConsecutiveOnes(int[] nums) { 9 | 10 | int maxHere = 0, max = 0; 11 | for (int n : nums) 12 | max = Math.max(max, maxHere = n == 0 ? 0 : maxHere + 1); 13 | return max; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/leetcode/MinStack.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * Created by nikoo28 on 7/19/19 2:36 AM 7 | */ 8 | 9 | class MinStack { 10 | 11 | private Stack mStack = new Stack<>(); 12 | private Stack mMinStack = new Stack<>(); 13 | 14 | public void push(int x) { 15 | mStack.push(x); 16 | if (mMinStack.size() != 0) { 17 | int min = mMinStack.peek(); 18 | if (x <= min) { 19 | mMinStack.push(x); 20 | } 21 | } else { 22 | mMinStack.push(x); 23 | } 24 | } 25 | 26 | public void pop() { 27 | int x = mStack.pop(); 28 | if (mMinStack.size() != 0) { 29 | if (x == mMinStack.peek()) { 30 | mMinStack.pop(); 31 | } 32 | } 33 | } 34 | 35 | public int top() { 36 | return mStack.peek(); 37 | } 38 | 39 | public int getMin() { 40 | return mMinStack.peek(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/leetcode/MinimumMovesToEqualArrayElements.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | /** 6 | * Created by nikoo28 on 12/17/17 2:44 PM 7 | */ 8 | 9 | class MinimumMovesToEqualArrayElements { 10 | 11 | public int minMoves(int[] nums) { 12 | return IntStream.of(nums).sum() - nums.length * IntStream.of(nums).min().getAsInt(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/leetcode/MissingNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 9/23/18 1:15 PM 5 | */ 6 | 7 | class MissingNumber { 8 | 9 | int missingNumber(int[] nums) { 10 | 11 | int allXOR = 0; 12 | 13 | // XOR all numbers in range [0, n] 14 | for (int i = 0; i <= nums.length; i++) { 15 | allXOR = allXOR ^ i; 16 | } 17 | 18 | // XOR all numbers in the given array 19 | for (int num : nums) { 20 | allXOR = allXOR ^ num; 21 | } 22 | 23 | // The missing number 24 | return allXOR; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/MovingAverage.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /** 7 | * Created by nikoo28 on 9/22/18 6:15 PM 8 | */ 9 | 10 | class MovingAverage { 11 | 12 | private Queue slidingWindow; 13 | private double previousSum = 0.0; 14 | private int limit; 15 | 16 | public MovingAverage(int size) { 17 | 18 | slidingWindow = new LinkedList<>(); 19 | limit = size; 20 | } 21 | 22 | public double next(int val) { 23 | 24 | if (slidingWindow.size() == limit) { 25 | previousSum -= slidingWindow.poll(); 26 | } 27 | 28 | previousSum += val; 29 | slidingWindow.add(val); 30 | 31 | return previousSum / slidingWindow.size(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/NimGame.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/16/17 5 | */ 6 | class NimGame { 7 | 8 | public boolean canWinNim(int n){ 9 | return n % 4 != 0 ; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/leetcode/NotBoring.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select id, movie, description, rating 3 | from cinema 4 | where not (description = 'boring') 5 | and id mod 2 = 1 6 | order by rating desc; -------------------------------------------------------------------------------- /src/main/java/leetcode/NumberComplement.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/10/17 5 | */ 6 | class NumberComplement { 7 | 8 | public int findComplement(int num) { 9 | int i = 0; 10 | int j = 0; 11 | 12 | while (i < num) { 13 | i += Math.pow(2, j); 14 | j++; 15 | } 16 | 17 | return i - num; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/leetcode/NumberOfIslands.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/18/17 9:40 PM 5 | */ 6 | 7 | class NumberOfIslands { 8 | 9 | public int numIslands(char[][] grid) { 10 | 11 | int count = 0; 12 | 13 | for (int i = 0; i < grid.length; i++) { 14 | for (int j = 0; j < grid[i].length; j++) { 15 | if (grid[i][j] == '1') { 16 | explore(grid, i, j); 17 | count++; 18 | } 19 | } 20 | } 21 | 22 | return count; 23 | } 24 | 25 | private void explore(char[][] grid, int i, int j) { 26 | if (i < 0 || j < 0 || j >= grid[0].length || i >= grid.length || grid[i][j] == '0') return; 27 | 28 | grid[i][j] = '0'; 29 | explore(grid, i, j - 1); 30 | explore(grid, i, j + 1); 31 | explore(grid, i - 1, j); 32 | explore(grid, i + 1, j); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/PeakIndexInAMountainArray.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 9/22/18 5:43 PM 5 | */ 6 | 7 | class PeakIndexInAMountainArray { 8 | 9 | public int peakIndexInMountainArray(int[] A) { 10 | 11 | int peak = Integer.MIN_VALUE; 12 | int peakIdx = -1; 13 | int idx = 0; 14 | while (peak < A[idx]) { 15 | peak = A[idx]; 16 | idx++; 17 | } 18 | 19 | peakIdx = idx - 1; 20 | 21 | if (idx == A.length) 22 | return -1; 23 | 24 | while (idx < A.length) { 25 | if (A[idx] > peak) 26 | return -1; 27 | 28 | idx++; 29 | } 30 | 31 | return peakIdx; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/RangeAddition2.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 2:29 PM 5 | */ 6 | 7 | class RangeAddition2 { 8 | 9 | public int maxCount(int m, int n, int[][] ops) { 10 | if (ops == null || ops.length == 0) { 11 | return m * n; 12 | } 13 | 14 | int row = Integer.MAX_VALUE, col = Integer.MAX_VALUE; 15 | for(int[] op : ops) { 16 | row = Math.min(row, op[0]); 17 | col = Math.min(col, op[1]); 18 | } 19 | 20 | return row * col; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/leetcode/RansomeNote.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 3:09 PM 5 | */ 6 | 7 | class RansomeNote { 8 | 9 | public boolean canConstruct(String ransomNote, String magazine) { 10 | 11 | char[] magazineSet = new char[26]; 12 | char[] magazineChars = magazine.toCharArray(); 13 | char[] ransomeNoteChars = ransomNote.toCharArray(); 14 | 15 | for (char aChar : magazineChars) magazineSet[aChar - 'a']++; 16 | for (char aChar : ransomeNoteChars) if (magazineSet[aChar - 'a']-- == 0) return false; 17 | return true; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ReshapeTheMatrix.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * @author nikoo28 on 9/10/17 5 | */ 6 | class ReshapeTheMatrix { 7 | 8 | public int[][] matrixReshape(int[][] nums, int r, int c) { 9 | int m = nums.length, n = nums[0].length; 10 | if (m * n != r * c) return nums; 11 | 12 | int[][] result = new int[r][c]; 13 | int row = 0, col = 0; 14 | for (int[] num : nums) { 15 | for (int j = 0; j < n; j++) { 16 | result[row][col] = num[j]; 17 | col++; 18 | if (col == c) { 19 | col = 0; 20 | row++; 21 | } 22 | } 23 | } 24 | 25 | return result; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.ListNode; 4 | 5 | /** 6 | * Created by nikoo28 on 12/17/17 10:40 PM 7 | */ 8 | 9 | class ReverseLinkedList { 10 | 11 | public ListNode reverseList(ListNode head) { 12 | 13 | if (head == null || head.next == null) 14 | return head; 15 | 16 | ListNode prev = null; 17 | 18 | while (head.next != null) { 19 | 20 | ListNode temp = head.next; 21 | head.next = prev; 22 | prev = head; 23 | head = temp; 24 | } 25 | 26 | head.next = prev; 27 | return head; 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/ReverseString.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | class ReverseString { 4 | 5 | public String reverseString(String s) { 6 | 7 | StringBuilder stringBuilder = new StringBuilder(); 8 | for (int i = s.length() - 1; i >= 0; i--) { 9 | stringBuilder.append(s.charAt(i)); 10 | } 11 | 12 | return stringBuilder.toString(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/leetcode/SmallestLetterGreaterThanTarget.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 12:56 AM 5 | */ 6 | 7 | class SmallestLetterGreaterThanTarget { 8 | 9 | public char nextGreatestLetter(char[] letters, char target) { 10 | 11 | for (char letter : letters) { 12 | if (letter > target) 13 | return letter; 14 | } 15 | 16 | return letters[0]; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/leetcode/StringToInteger.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 7/19/19 2:39 AM 5 | */ 6 | 7 | class StringToInteger { 8 | 9 | public int myAtoi(String str) { 10 | 11 | str = str.trim(); 12 | if (str == null || str.length() == 0) 13 | return 0; 14 | 15 | char firstChar = str.charAt(0); 16 | int sign = 1, start = 0, len = str.length(); 17 | long sum = 0; 18 | 19 | if (firstChar == '+') { 20 | sign = 1; 21 | start++; 22 | } else if (firstChar == '-') { 23 | sign = -1; 24 | start++; 25 | } 26 | 27 | for (int i = start; i < len; i++) { 28 | if (!Character.isDigit(str.charAt(i))) 29 | return (int) sum * sign; 30 | sum = sum * 10 + str.charAt(i) - '0'; 31 | 32 | if (sign == 1 && sum > Integer.MAX_VALUE) 33 | return Integer.MAX_VALUE; 34 | if (sign == -1 && (-1) * sum < Integer.MIN_VALUE) 35 | return Integer.MIN_VALUE; 36 | } 37 | 38 | return (int) sum * sign; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/SumOfLeftLeaves.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | /** 6 | * Created by nikoo28 on 12/17/17 3:24 PM 7 | */ 8 | 9 | class SumOfLeftLeaves { 10 | 11 | private int sumOfLeftLeaves(TreeNode root) { 12 | 13 | if (root == null) 14 | return 0; 15 | 16 | int sum = 0; 17 | if (root.left != null) 18 | if (root.left.left == null && root.left.right == null) 19 | sum += root.left.val; 20 | else 21 | sum += sumOfLeftLeaves(root.left); 22 | 23 | sum += sumOfLeftLeaves(root.right); 24 | 25 | return sum; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/TrimABinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | /** 6 | * @author nikoo28 on 9/16/17 7 | */ 8 | 9 | class TrimABinarySearchTree { 10 | 11 | private TreeNode trimBST(TreeNode root, int L, int R) { 12 | 13 | if (root == null) 14 | return null; 15 | 16 | if (root.val < L) 17 | return trimBST(root.right, L, R); 18 | 19 | if (root.val > R) 20 | return trimBST(root.left, L, R); 21 | 22 | root.left = trimBST(root.left, L, R); 23 | root.right = trimBST(root.right, L, R); 24 | 25 | return root; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/TwoSumIV.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * @author nikoo28 on 9/17/17 10 | */ 11 | class TwoSumIV { 12 | 13 | public boolean findTarget(TreeNode root, int k) { 14 | 15 | List elements = new ArrayList<>(); 16 | inorder(root, elements); 17 | 18 | for (int i = 0, j = elements.size()-1; i k) 24 | j--; 25 | else 26 | i++; 27 | } 28 | 29 | return false; 30 | 31 | } 32 | 33 | private void inorder(TreeNode root, List elements) { 34 | if (root == null) 35 | return; 36 | inorder(root.left, elements); 37 | elements.add(root.val); 38 | inorder(root.right, elements); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/UnionFind.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | /** 4 | * Created by nikoo28 on 12/18/17 8:03 PM 5 | */ 6 | 7 | class UnionFind { 8 | private int[] father; 9 | int count = 0; 10 | 11 | UnionFind(char[][] grid) { 12 | int m = grid.length; 13 | int n = grid[0].length; 14 | father = new int[m * n]; 15 | for (int i = 0; i < m; i++) { 16 | for (int j = 0; j < n; j++) { 17 | if (grid[i][j] == '1') { 18 | int id = i * n + j; 19 | father[id] = id; 20 | count++; 21 | } 22 | } 23 | } 24 | } 25 | 26 | public void union(int node1, int node2) { 27 | int find1 = find(node1); 28 | int find2 = find(node2); 29 | if (find1 != find2) { 30 | father[find1] = find2; 31 | count--; 32 | } 33 | } 34 | 35 | private int find(int node) { 36 | if (father[node] == node) { 37 | return node; 38 | } 39 | father[node] = find(father[node]); 40 | return father[node]; 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/leetcode/UniqueMorseCodeWords.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Created by nikoo28 on 9/22/18 5:25 PM 7 | */ 8 | 9 | class UniqueMorseCodeWords { 10 | 11 | public int uniqueMorseCodeRepresentations(String[] words) { 12 | 13 | String[] morseCode = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; 14 | 15 | StringBuilder morseRepresentation = new StringBuilder(); 16 | HashSet uniqueRepresentations = new HashSet<>(); 17 | 18 | for (String word : words) { 19 | 20 | morseRepresentation.setLength(0); 21 | 22 | for (int i = 0; i < word.length(); i++) { 23 | morseRepresentation.append(morseCode[word.charAt(i) - 'a']); 24 | } 25 | 26 | uniqueRepresentations.add(morseRepresentation.toString()); 27 | } 28 | 29 | return uniqueRepresentations.size(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/WordBreak.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Created by nikoo28 on 7/18/19 9:50 PM 7 | */ 8 | 9 | class WordBreak { 10 | 11 | public boolean wordBreak(String s, List wordDict) { 12 | 13 | int[] visited = new int[s.length()]; 14 | Set dictSet = new HashSet<>(wordDict); 15 | Queue queue = new LinkedList<>(); 16 | queue.add(0); 17 | while (!queue.isEmpty()) { 18 | Integer begin = queue.remove(); 19 | if (visited[begin] == 0) { 20 | for (int i = begin + 1; i <= s.length(); i++) { 21 | 22 | String substring = s.substring(begin, i); 23 | if (dictSet.contains(substring)) { 24 | queue.add(i); 25 | if (i == s.length()) 26 | return true; 27 | } 28 | } 29 | visited[begin] = 1; 30 | } 31 | } 32 | 33 | return false; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/BackspaceStringCompare.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class BackspaceStringCompare { 4 | 5 | boolean backspaceCompare(String s, String t) { 6 | return getActual(s).equals(getActual(t)); 7 | } 8 | 9 | private String getActual(String input) { 10 | 11 | StringBuilder actualString = new StringBuilder(); 12 | int hashCount = 0; 13 | 14 | for (int i = input.length() - 1; i >= 0 ; i--) { 15 | 16 | // Keep a count of backspace characters 17 | if (input.charAt(i) == '#') { 18 | hashCount++; 19 | continue; 20 | } 21 | 22 | // If backspace count > 0 reduce it and skip the character 23 | if (hashCount > 0) { 24 | hashCount--; 25 | } else { 26 | // If no backspace, just insert at beginning 27 | actualString.insert(0, input.charAt(i)); 28 | } 29 | } 30 | 31 | return actualString.toString(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/BalancedBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | 5 | public class BalancedBinaryTree { 6 | 7 | boolean isBalanced(TreeNode root) { 8 | if (root == null) return true; 9 | return Math.abs(height(root.left) - height(root.right)) <= 1 10 | && isBalanced(root.left) 11 | && isBalanced(root.right); 12 | } 13 | 14 | int height(TreeNode root) { 15 | if (root == null) return 0; 16 | return 1 + Math.max(height(root.left), height(root.right)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/BestTimeToBuyAndSellAStock.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 12/19/17 1:26 AM 5 | */ 6 | 7 | class BestTimeToBuyAndSellAStock { 8 | 9 | int maxProfit(int[] prices) { 10 | 11 | // at the beginning the minimum price is the first price 12 | int buy_price = prices[0]; 13 | 14 | // at the beginning the minimum profit is zero 15 | int profit = 0; 16 | 17 | for (int i = 1; i < prices.length; i++) { 18 | 19 | // if the current price is less update the buy_price 20 | if (prices[i] < buy_price) { 21 | buy_price = prices[i]; 22 | } 23 | else { 24 | // else check if we can get a better profit 25 | int current_profit = prices[i] - buy_price; 26 | profit = Math.max(current_profit, profit); 27 | } 28 | } 29 | 30 | return profit; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/BestTimeToBuyAndSellAStockII.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 2:58 PM 5 | */ 6 | 7 | class BestTimeToBuyAndSellAStockII { 8 | 9 | public int maxProfit(int[] prices) { 10 | 11 | if (prices.length < 2) return 0; 12 | 13 | int buyingPrice = prices[0]; 14 | int profit = 0; 15 | 16 | for (int i = 1; i < prices.length; i++) { 17 | 18 | if (prices[i] < buyingPrice) { 19 | buyingPrice = prices[i]; 20 | continue; 21 | } 22 | 23 | profit += prices[i] - buyingPrice; 24 | buyingPrice = prices[i]; 25 | } 26 | 27 | return profit; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/CheckIfPangram.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class CheckIfPangram { 7 | 8 | boolean checkIfPangram(String sentence) { 9 | 10 | Set alphabetSet = new HashSet<>(); 11 | 12 | // Add all characters from 'a' to 'z' in hashset 13 | for (int i = 'a'; i <= 'z'; i++) { 14 | alphabetSet.add((char) i); 15 | } 16 | 17 | // Remove every character and check 18 | // if set becomes empty at any point of time 19 | for (int i = 0; i < sentence.length(); i++) { 20 | alphabetSet.remove(sentence.charAt(i)); 21 | if (alphabetSet.isEmpty()) 22 | return true; 23 | } 24 | 25 | return false; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 10/19/19 3:24 PM 5 | */ 6 | 7 | class ClimbingStairs { 8 | 9 | public int climbStairs(int n) { 10 | 11 | if (n == 1) return 1; 12 | 13 | int[] dp = new int[n + 1]; 14 | dp[1] = 1; 15 | dp[2] = 2; 16 | 17 | for (int i = 3; i <= n; i++) { 18 | dp[i] = dp[i - 1] + dp[i - 2]; 19 | } 20 | 21 | return dp[n]; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ContainsDuplicate.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by nikoo28 on 10/11/19 12:10 AM 8 | */ 9 | 10 | class ContainsDuplicate { 11 | 12 | public boolean containsDuplicate(int[] nums) { 13 | 14 | // Create hashset to store integers 15 | Set intSet = new HashSet<>(); 16 | 17 | // Iterate over each element 18 | for (int num : nums) { 19 | 20 | // Check the number in hashset 21 | if (intSet.contains(num)) 22 | return true; 23 | 24 | // Add the number to hashset 25 | intSet.add(num); 26 | } 27 | 28 | return false; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ContainsDuplicateII.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by nikoo28 on 10/11/19 12:31 AM 8 | */ 9 | 10 | class ContainsDuplicateII { 11 | 12 | boolean containsNearbyDuplicate(int[] nums, int k) { 13 | Set set = new HashSet<>(); 14 | 15 | for (int i = 0; i < nums.length; i++) { 16 | if (i > k) 17 | set.remove(nums[i - k - 1]); 18 | if (!set.add(nums[i])) 19 | return true; 20 | } 21 | return false; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/CountCompleteTreeNodes.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | 5 | public class CountCompleteTreeNodes { 6 | 7 | public int countNodes(TreeNode root) { 8 | 9 | int leftDepth = leftDepth(root); 10 | int rightDepth = rightDepth(root); 11 | 12 | if (leftDepth == rightDepth) 13 | return (int) Math.pow(2, leftDepth) - 1; 14 | else 15 | return 1 + countNodes(root.left) + countNodes(root.right); 16 | } 17 | 18 | private int rightDepth(TreeNode root) { 19 | int dep = 0; 20 | while (root != null) { 21 | root = root.right; 22 | dep++; 23 | } 24 | return dep; 25 | } 26 | 27 | private int leftDepth(TreeNode root) { 28 | int dep = 0; 29 | while (root != null) { 30 | root = root.left; 31 | dep++; 32 | } 33 | return dep; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/CountPrimes.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-07-21 12:27 5 | */ 6 | 7 | class CountPrimes { 8 | public int countPrimes(int n) { 9 | boolean[] notPrime = new boolean[n]; 10 | int count = 0; 11 | for (int i = 2; i < n; i++) { 12 | if (!notPrime[i]) { 13 | count++; 14 | for (int j = 2; i * j < n; j++) { 15 | notPrime[i * j] = true; 16 | } 17 | } 18 | } 19 | 20 | return count; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/DayOfTheYear.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.time.LocalDate; 4 | 5 | /** 6 | * Created by nikoo28 on 2019-08-10 19:33 7 | */ 8 | 9 | class DayOfTheYear { 10 | 11 | private int dayOfYear(String date) { 12 | 13 | return LocalDate.parse(date).getDayOfYear(); 14 | } 15 | 16 | public static void main(String[] args) { 17 | DayOfTheYear dayOfTheYear = new DayOfTheYear(); 18 | System.out.println(dayOfTheYear.dayOfYear("2004-03-01")); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class FibonacciNumber { 4 | 5 | int fib(int n) { 6 | // easy base cases/edge cases 7 | if (n <= 1) { 8 | return n; 9 | } 10 | 11 | // initialize our memoization map 12 | // size N +1 so that we can accommodate from 0 to N 13 | int[] map = new int[n + 1]; 14 | 15 | // put our base cases 16 | map[0] = 0; 17 | map[1] = 1; 18 | 19 | // iterate through remaining values (2...N) 20 | for (int i = 2; i <= n; i += 1) { 21 | map[i] = map[i - 1] + map[i - 2]; 22 | } 23 | return map[n]; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/FindAllNumbersDisappearedInAnArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class FindAllNumbersDisappearedInAnArray { 7 | 8 | public List findDisappearedNumbers(int[] nums) { 9 | 10 | List result = new ArrayList<>(); 11 | 12 | for (int i = 0; i < nums.length; i++) { 13 | int idx = Math.abs(nums[i]) - 1; 14 | if (nums[idx] < 0) 15 | continue; 16 | 17 | nums[idx] *= -1; 18 | } 19 | 20 | for (int i = 0; i < nums.length; i++) { 21 | if (nums[i] > 0) 22 | result.add(i + 1); 23 | } 24 | 25 | return result; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/FindCommonCharacters.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by nikoo28 on 10/16/19 1:17 AM 8 | */ 9 | 10 | class FindCommonCharacters { 11 | 12 | List commonChars(String[] A) { 13 | 14 | List result = new ArrayList<>(); 15 | 16 | for (int c = 'a'; c <= 'z'; c++) { 17 | int minCount = Integer.MAX_VALUE; 18 | for (String currentWord : A) { 19 | 20 | int wordCount = 0; 21 | for (char currentChar : currentWord.toCharArray()) { 22 | if (currentChar == c) { 23 | wordCount++; 24 | } 25 | } 26 | 27 | minCount = Math.min(minCount, wordCount); 28 | } 29 | 30 | for (int i = 0; i < minCount; i++) { 31 | result.add("" + (char) c); 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/FindPivotIndex.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class FindPivotIndex { 4 | 5 | int pivotIndex(int[] nums) { 6 | 7 | // Calculate the sum of the array 8 | int rightSum = 0; 9 | for (int num : nums) { 10 | rightSum += num; 11 | } 12 | 13 | int leftSum = 0; 14 | 15 | // Iterate through the array 16 | for (int i = 0; i < nums.length; i++) { 17 | 18 | // Update the right sum 19 | rightSum -= nums[i]; 20 | 21 | // Check if the left sum is equal to the right sum 22 | if (leftSum == rightSum) { 23 | return i; 24 | } 25 | 26 | // Update the left sum 27 | leftSum += nums[i]; 28 | } 29 | 30 | // Return -1 if no pivot index is found 31 | return -1; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/FirstUniqueCharacterInAString.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by nikoo28 on 6/30/20 10:28 PM 8 | */ 9 | 10 | public class FirstUniqueCharacterInAString { 11 | 12 | public int firstUniqueChar(String str) { 13 | 14 | int index = -1; 15 | str = str.toLowerCase(); 16 | 17 | Map charFreqMap = new HashMap<>(); 18 | 19 | // Update the map 20 | for (int i = 0; i < str.length(); i++) { 21 | char c = str.charAt(i); 22 | 23 | // Get the current frequency 24 | int freq = charFreqMap.getOrDefault(c, 0); 25 | 26 | // Update the map 27 | charFreqMap.put(c, (freq + 1)); 28 | } 29 | 30 | for (int i = 0; i < str.length(); i++) { 31 | if (charFreqMap.get(str.charAt(i)) == 1) { 32 | index = i; 33 | break; 34 | } 35 | } 36 | 37 | return index; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/HappyNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by nikoo28 on 10/19/19 3:11 PM 8 | */ 9 | 10 | class HappyNumber { 11 | 12 | boolean isHappy(int n) { 13 | 14 | Set usedIntegers = new HashSet<>(); 15 | while (true) { 16 | 17 | // Find the sum of squares 18 | int sum = 0; 19 | while (n != 0) { 20 | sum += Math.pow(n % 10, 2.0); 21 | n = n / 10; 22 | } 23 | 24 | // If sum is 1, return true 25 | if (sum == 1) return true; 26 | 27 | // Else, the new number is the current sum 28 | n = sum; 29 | 30 | // Check if we have already encountered 31 | // that number 32 | if (usedIntegers.contains(n)) 33 | return false; 34 | usedIntegers.add(n); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/IntersectionOfTwoArraysII.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | 6 | /** 7 | * Created by nikoo28 on 10/15/19 11:59 PM 8 | */ 9 | 10 | class IntersectionOfTwoArraysII { 11 | 12 | int[] intersect(int[] nums1, int[] nums2) { 13 | HashMap map = new HashMap<>(); 14 | ArrayList result = new ArrayList<>(); 15 | 16 | for (int value : nums1) { 17 | if (map.containsKey(value)) 18 | map.put(value, map.get(value) + 1); 19 | else 20 | map.put(value, 1); 21 | } 22 | 23 | for (int value : nums2) { 24 | if (map.containsKey(value) && map.get(value) > 0) { 25 | result.add(value); 26 | map.put(value, map.get(value) - 1); 27 | } 28 | } 29 | 30 | int[] r = new int[result.size()]; 31 | for (int i = 0; i < result.size(); i++) { 32 | r[i] = result.get(i); 33 | } 34 | 35 | return r; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/IsSubsequence.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class IsSubsequence { 4 | 5 | boolean isSubsequence(String str1, String str2) { 6 | 7 | // Initialize pointers for both strings 8 | int i = 0; 9 | int j = 0; 10 | // We can iterate until either of them becomes zero... 11 | 12 | while (i < str1.length() && j < str2.length()) { 13 | // Compare characters, increment both pointers if same 14 | if (str1.charAt(i) == str2.charAt(j)) { 15 | i++; 16 | j++; 17 | } else { 18 | j++; // Only increment second pointer 19 | } 20 | } 21 | 22 | // If it is a subsequence, 'i' will have travelled full 23 | // length of string 'str1', so just check and return 24 | return (i == str1.length()); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/JewelsAndStones.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | public class JewelsAndStones { 7 | 8 | int numJewelsInStones(String jewels, String stones) { 9 | 10 | // Create a set for all different jewels 11 | Set jewelSet = new HashSet<>(); 12 | for (int i = 0; i < jewels.length(); i++) 13 | jewelSet.add(jewels.charAt(i)); 14 | 15 | // Find total score/value 16 | int score = 0; 17 | for (int i = 0; i < stones.length(); i++) 18 | if (jewelSet.contains(stones.charAt(i))) 19 | score++; 20 | 21 | return score; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/KthMissingPositiveNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class KthMissingPositiveNumber { 4 | 5 | // Implementation using binary search with proper comments 6 | int findKthPositive(int[] arr, int k) { 7 | // Initialize the left and right pointers 8 | int left = 0; 9 | int right = arr.length; 10 | 11 | // Start a loop and keep moving till left is less than right 12 | while (left < right) { 13 | // Calculate the mid 14 | int mid = left + (right - left) / 2; 15 | 16 | // If the number of missing elements is less than k 17 | if (arr[mid] - mid - 1 < k) { 18 | // Move left to mid + 1 19 | left = mid + 1; 20 | } else { 21 | // Move right to mid 22 | right = mid; 23 | } 24 | } 25 | 26 | // Return the kth missing element 27 | return left + k; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/LastStoneWeight.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | 6 | public class LastStoneWeight { 7 | 8 | int lastStoneWeight(int[] stones) { 9 | 10 | // Create a priority queue 11 | PriorityQueue pq = 12 | new PriorityQueue<>(Collections.reverseOrder()); 13 | 14 | // Add all stones to the priority queue 15 | for (int stone : stones) 16 | pq.add(stone); 17 | 18 | // While there are more than 1 stone 19 | while (pq.size() > 1) { 20 | 21 | // Get the two heaviest stones 22 | int y = pq.poll(); 23 | int x = pq.poll(); 24 | 25 | // If the stones are not equal 26 | if (x != y) { 27 | pq.add(y - x); 28 | } 29 | } 30 | 31 | return pq.isEmpty() ? 0 : pq.poll(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/LeftAndRightSumDifferences.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class LeftAndRightSumDifferences { 4 | 5 | int[] leftRightDifference(int[] nums) { 6 | 7 | int rightSum = 0; 8 | int leftSum = 0; 9 | 10 | // Calculate the total right sum 11 | for (int num : nums) { 12 | rightSum += num; 13 | } 14 | 15 | // Iterate through the array 16 | for (int i = 0; i < nums.length; i++) { 17 | // Get the value at index i 18 | int val = nums[i]; 19 | 20 | // Update the right sum 21 | rightSum -= val; 22 | 23 | // Find the difference 24 | nums[i] = Math.abs(leftSum - rightSum); 25 | 26 | // Update the left sum 27 | leftSum += val; 28 | } 29 | 30 | return nums; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/LengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class LengthOfLastWord { 4 | 5 | int lengthOfLastWord(String s) { 6 | 7 | int count = 0; 8 | 9 | for (int i = s.length() - 1; i >= 0; i--) { 10 | 11 | // a letter is found so count 12 | if (s.charAt(i) != ' ') { 13 | count++; 14 | } 15 | else { 16 | // it's a white space instead 17 | // Did we already started to count a word ? 18 | // Yes so we found the last word 19 | if (count > 0) 20 | return count; 21 | } 22 | } 23 | 24 | return count; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.ListNode; 4 | 5 | /** 6 | * Created by nikoo28 on 2019-07-21 12:55 7 | */ 8 | 9 | class LinkedListCycle { 10 | 11 | public boolean hasCycle(ListNode head) { 12 | if (head == null || head.next == null) 13 | return false; 14 | ListNode slow = head, fast = head; 15 | while (fast != null && fast.next != null) { 16 | fast = fast.next.next; 17 | slow = slow.next; 18 | if (slow == fast) { 19 | while (head != slow) { 20 | head = head.next; 21 | slow = slow.next; 22 | } 23 | return true; 24 | } 25 | } 26 | return false; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.Arrays; 4 | 5 | public class LongestCommonPrefix { 6 | 7 | public String longestCommonPrefix(String[] strs) { 8 | 9 | StringBuilder result = new StringBuilder(); 10 | 11 | // Sort the array 12 | Arrays.sort(strs); 13 | 14 | // Get the first and last strings 15 | char[] first = strs[0].toCharArray(); 16 | char[] last = strs[strs.length - 1].toCharArray(); 17 | 18 | // Start comparing 19 | for (int i = 0; i < first.length; i++) { 20 | if (first[i] != last[i]) 21 | break; 22 | result.append(first[i]); 23 | } 24 | 25 | return result.toString(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/LowestCommonAncestorOfBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | /** 5 | * Created by nikoo28 on 12/19/17 12:58 AM 6 | */ 7 | 8 | class LowestCommonAncestorOfBinarySearchTree { 9 | 10 | private TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 11 | 12 | if (root == null) 13 | return root; 14 | 15 | if (root.val > p.val && root.val > q.val) 16 | return lowestCommonAncestor(root.left, p, q); 17 | 18 | if (root.val < p.val && root.val < q.val) 19 | return lowestCommonAncestor(root.right, p, q); 20 | 21 | return root; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MajorityElement.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by nikoo28 on 12/17/17 3:14 PM 7 | */ 8 | 9 | class MajorityElement { 10 | 11 | int majorityElement(int[] num) { 12 | 13 | int majority = num[0], votes = 1; 14 | 15 | for (int i = 1; i < num.length; i++) { 16 | 17 | if (votes == 0) { 18 | votes++; 19 | majority = num[i]; 20 | } else if (majority == num[i]) { 21 | votes++; 22 | } else 23 | votes--; 24 | 25 | } 26 | return majority; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MatrixDiagonalSum.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class MatrixDiagonalSum { 4 | 5 | int diagonalSum(int[][] mat) { 6 | 7 | int sum = 0; 8 | int n = mat.length; 9 | 10 | // Get the sum of both diagonals 11 | for (int i = 0; i < n; i++) { 12 | sum += mat[i][i]; 13 | sum += mat[i][n - i - 1]; 14 | } 15 | 16 | // If the matrix is odd 17 | // Subtract the duplicate element 18 | if (n % 2 != 0) { 19 | sum -= mat[n / 2][n / 2]; 20 | } 21 | 22 | return sum; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MaxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class MaxConsecutiveOnes { 4 | 5 | int findMaxConsecutiveOnes(int[] nums) { 6 | int max = 0; 7 | int count = 0; 8 | 9 | // Iterate through all the elements 10 | // and keep a track of the maximum 1s 11 | for (int num : nums) { 12 | if (num == 1) { 13 | count++; 14 | max = Math.max(max, count); 15 | } else { 16 | count = 0; 17 | } 18 | } 19 | 20 | return max; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MaximumAverageSubarrayI.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class MaximumAverageSubarrayI { 4 | 5 | double findMaxAverage(int[] nums, int k) { 6 | 7 | // Get sum for starting window 8 | int sum = 0; 9 | for (int i = 0; i < k; i++) 10 | sum += nums[i]; 11 | 12 | int maxSum = sum; 13 | 14 | // Start sliding window 15 | int startIndex = 0; 16 | int endIndex = k; 17 | while (endIndex < nums.length) { 18 | 19 | sum -= nums[startIndex]; // Remove previous element 20 | startIndex++; 21 | 22 | sum += nums[endIndex]; // Add next element 23 | endIndex++; 24 | 25 | maxSum = Math.max(maxSum, sum); // Update max sum 26 | } 27 | 28 | // Return the average 29 | return (double) maxSum / k; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MaximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | /** 9 | * @author nikoo28 on 9/16/17 10 | */ 11 | class MaximumDepthOfABinaryTree { 12 | 13 | int maxDepth(TreeNode root) { 14 | 15 | if (root == null) 16 | return 0; 17 | 18 | Queue nodes = new LinkedList<>(); 19 | 20 | nodes.add(root); 21 | int levels = 0; 22 | 23 | while (!nodes.isEmpty()) { 24 | 25 | levels++; 26 | int size = nodes.size(); 27 | for (int i = 0; i < size; i++) { 28 | TreeNode poppedNode = nodes.poll(); 29 | if (poppedNode.left != null) nodes.add(poppedNode.left); 30 | if (poppedNode.right != null) nodes.add(poppedNode.right); 31 | } 32 | 33 | } 34 | 35 | return levels; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MaximumOddBinaryNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class MaximumOddBinaryNumber { 4 | 5 | String maximumOddBinaryNumber(String s) { 6 | 7 | // Count total 0's and 1's in string 8 | int countZero = 0; 9 | int countOne = 0; 10 | for (char c : s.toCharArray()) { 11 | if (c == '0') 12 | countZero++; 13 | else 14 | countOne++; 15 | } 16 | 17 | // Build the answer 18 | StringBuilder ans = new StringBuilder(); 19 | 20 | // Add the first 1 21 | ans.append("1"); 22 | countOne--; 23 | 24 | // Add all the 0's 25 | ans.append("0".repeat(countZero)); 26 | 27 | // Add the remaining 1's 28 | ans.append("1".repeat(countOne)); 29 | 30 | // Reverse and return the answer 31 | return ans.reverse().toString(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-10-05 18:20 5 | */ 6 | 7 | class MaximumSubarray { 8 | 9 | public int maxSubArray(int[] nums) { 10 | 11 | int max_so_far = nums[0]; 12 | int curr_max = nums[0]; 13 | 14 | for (int i = 1; i < nums.length; i++) { 15 | curr_max = Math.max(nums[i], nums[i] + curr_max); 16 | max_so_far = Math.max(curr_max, max_so_far); 17 | } 18 | 19 | return max_so_far; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MergeTwoBinaryTrees.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | 5 | /** 6 | * @author nikoo28 on 9/10/17 7 | */ 8 | 9 | class MergeTwoBinaryTrees { 10 | private TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 11 | 12 | if (t1 == null) 13 | return t2; 14 | 15 | if (t2 == null) 16 | return t1; 17 | 18 | t1.val = t1.val + t2.val; 19 | t1.left = mergeTrees(t1.left, t2.left); 20 | t1.right = mergeTrees(t1.right, t2.right); 21 | 22 | return t1; 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MiddleOfTheLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.ListNode; 4 | 5 | public class MiddleOfTheLinkedList { 6 | 7 | ListNode middleNode(ListNode head) { 8 | 9 | ListNode slowPtr = head; 10 | ListNode fastPtr = head; 11 | 12 | // Travel until the fast pointer reaches 13 | // the last node or null 14 | while (fastPtr != null && fastPtr.next!= null) { 15 | 16 | // Slow pointer moves 1 node 17 | slowPtr = slowPtr.next; 18 | 19 | // Fast pointer moves 2 nodes 20 | fastPtr = fastPtr.next.next; 21 | } 22 | 23 | return slowPtr; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MinCostClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-07-21 15:22 5 | */ 6 | 7 | class MinCostClimbingStairs { 8 | 9 | int minCostClimbingStairs(int[] cost) { 10 | 11 | int n = cost.length; 12 | int[] minCost = new int[n + 1]; 13 | 14 | for (int i = 2; i <= n; i++) { 15 | minCost[i] = 16 | Math.min( 17 | (cost[i - 1] + minCost[i - 1]), 18 | (cost[i - 2] + minCost[i - 2]) 19 | ); 20 | } 21 | 22 | return minCost[n]; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MinimumDepthBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class MinimumDepthBinaryTree { 9 | 10 | int minDepth(TreeNode root) { 11 | if (root == null) 12 | return 0; 13 | 14 | int depth = 1; 15 | Queue q = new LinkedList(); 16 | q.offer(root); 17 | 18 | // Level order traversal 19 | while (!q.isEmpty()) { 20 | int size = q.size(); 21 | for (int i = 0; i < size; i++) { 22 | TreeNode node = q.poll(); 23 | 24 | // If a leaf node is found just return depth 25 | if (node.left == null && node.right == null) { 26 | return depth; 27 | } 28 | if (node.left != null) { 29 | q.offer(node.left); 30 | } 31 | if (node.right != null) { 32 | q.offer(node.right); 33 | } 34 | } 35 | depth++; 36 | } 37 | return depth; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MoveZeroes.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * @author nikoo28 on 9/17/17 5 | */ 6 | class MoveZeroes { 7 | 8 | public void moveZeroes(int[] nums) { 9 | 10 | // Start with the first position 11 | int insertPosition = 0; 12 | 13 | for (int i = 0; i < nums.length; i++) { 14 | // FIll all non-zero numbers 15 | if (nums[i] != 0) { 16 | nums[insertPosition] = nums[i]; 17 | insertPosition++; 18 | } 19 | } 20 | 21 | while (insertPosition < nums.length) { 22 | nums[insertPosition++] = 0; 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/MyStack.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class MyStack { 7 | 8 | private Queue queue; 9 | 10 | public MyStack() { 11 | queue = new LinkedList<>(); 12 | } 13 | 14 | public void push(int x) { 15 | queue.add(x); 16 | for (int i = 1; i < queue.size(); i++) 17 | queue.add(queue.remove()); 18 | 19 | } 20 | 21 | public int pop() { 22 | return queue.remove(); 23 | } 24 | 25 | public int top() { 26 | return queue.peek(); 27 | } 28 | 29 | public boolean empty() { 30 | return queue.isEmpty(); 31 | } 32 | 33 | public static void main(String[] args) { 34 | MyStack stack = new MyStack(); 35 | stack.push(1); 36 | stack.push(2); 37 | System.out.println(stack.top()); // returns 2 38 | stack.pop(); 39 | System.out.println(stack.pop()); // returns 1 40 | System.out.println(stack.empty()); // returns false 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/NumberOf1Bits.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 10/19/19 3:36 PM 5 | */ 6 | 7 | class NumberOf1Bits { 8 | 9 | int hammingWeight(int n) { 10 | int ones = 0; 11 | while (n != 0) { 12 | ones = ones + (n & 1); 13 | n = n >>> 1; 14 | } 15 | return ones; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/NumberOfGoodPairs.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class NumberOfGoodPairs { 4 | 5 | public int numIdenticalPairs(int[] nums) { 6 | 7 | // Calculate the frequency of each number 8 | int[] count = new int[102]; 9 | 10 | for (int num : nums) { 11 | count[num]++; 12 | } 13 | 14 | int totalCount = 0; 15 | 16 | // Calculate total number of pairs possible 17 | for (int i : count) { 18 | totalCount += ((i) * (i-1))/2; 19 | } 20 | 21 | return totalCount; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/NumbersSmallerThanTheCurrentNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class NumbersSmallerThanTheCurrentNumber { 4 | 5 | public int[] smallerNumbersThanCurrent(int[] nums) { 6 | 7 | // Create buckets for counting sort 8 | int[] buckets = new int[102]; 9 | 10 | // Get frequency of each element 11 | for (int num : nums) { 12 | buckets[num]++; 13 | } 14 | 15 | // Count smaller numbers than each element 16 | for (int i = 1; i < buckets.length; i++) { 17 | buckets[i] += buckets[i - 1]; 18 | } 19 | 20 | // Populate the result 21 | int[] result = new int[nums.length]; 22 | for (int i = 0; i < result.length; i++) { 23 | if (nums[i] == 0) 24 | result[i] = 0; 25 | else 26 | result[i] = buckets[nums[i] - 1]; 27 | } 28 | 29 | return result; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/PascalTriangleII.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by nikoo28 on 2019-07-21 15:27 8 | */ 9 | 10 | class PascalTriangleII { 11 | 12 | public List getRow(int rowIndex) { 13 | Integer[] rowList = new Integer[rowIndex + 1]; 14 | rowList[0] = 1; 15 | for (int i = 1; i < rowList.length; i++) { 16 | rowList[i] = (int) ((long) rowList[i - 1] * (rowIndex - (i - 1)) / (i)); 17 | } 18 | return Arrays.asList(rowList); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/RangeSumOfBST.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | 5 | public class RangeSumOfBST { 6 | 7 | public int rangeSumBST(TreeNode root, int low, int high) { 8 | if (root == null) 9 | return 0; 10 | 11 | int sum = 0; 12 | 13 | // Explore the left sub-tree 14 | if (root.val > low) 15 | sum += rangeSumBST(root.left, low, high); 16 | 17 | // If value is in range add it to sum 18 | if (root.val >= low && root.val <= high) 19 | sum += root.val; 20 | 21 | // Explore the right sub-tree only if required 22 | if (root.val < high) 23 | sum += rangeSumBST(root.right, low, high); 24 | 25 | return sum; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/RansomNote.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class RansomNote { 4 | 5 | boolean canConstruct(String ransomNote, String magazine) { 6 | int[] charCount = new int[26]; 7 | 8 | // Count the frequency of each character in the magazine 9 | for (char c : magazine.toCharArray()) { 10 | charCount[c - 'a']++; 11 | } 12 | 13 | // Check if we can construct the ransom note 14 | for (char c : ransomNote.toCharArray()) { 15 | if (charCount[c - 'a'] == 0) { 16 | return false; // Character not available in magazine 17 | } 18 | charCount[c - 'a']--; 19 | } 20 | 21 | // Ransom note can be constructed 22 | return true; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/RemoveLinkedListElements.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.ListNode; 4 | 5 | public class RemoveLinkedListElements { 6 | 7 | public ListNode removeElements(ListNode head, int val) { 8 | 9 | // Create a dummy head node 10 | ListNode dummy = new ListNode(-1); 11 | dummy.next = head; 12 | 13 | ListNode curr = dummy; 14 | while (curr.next != null) { 15 | 16 | // Check if the value matches 17 | if (curr.next.val == val) 18 | curr.next = curr.next.next; 19 | else 20 | curr = curr.next; 21 | } 22 | 23 | // Return the head 24 | return dummy.next; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ReorderDataInLogFiles.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by nikoo28 on 10/8/19 1:24 AM 7 | */ 8 | 9 | class ReorderDataInLogFiles { 10 | 11 | public String[] reorderLogFiles(String[] logs) { 12 | Arrays.sort(logs, (log1, log2) -> { 13 | String[] split1 = log1.split(" ", 2); 14 | String[] split2 = log2.split(" ", 2); 15 | boolean isDigit1 = Character.isDigit(split1[1].charAt(0)); 16 | boolean isDigit2 = Character.isDigit(split2[1].charAt(0)); 17 | if (!isDigit1 && !isDigit2) { 18 | int cmp = split1[1].compareTo(split2[1]); 19 | if (cmp != 0) return cmp; 20 | return split1[0].compareTo(split2[0]); 21 | } 22 | return isDigit1 ? (isDigit2 ? 0 : 1) : -1; 23 | }); 24 | return logs; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ReverseOnlyLetters.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class ReverseOnlyLetters { 4 | 5 | String reverseOnlyLetters(String s) { 6 | 7 | // Convert the string to a character array 8 | char[] arr = s.toCharArray(); 9 | 10 | // Get the left and right pointers 11 | int left = 0; 12 | int right = arr.length - 1; 13 | 14 | // Start a loop and compare characters 15 | while (left < right) { 16 | 17 | // If left is not a letter, move right 18 | if (!Character.isLetter(arr[left])) left++; 19 | 20 | // If right is not a letter, move left 21 | else if (!Character.isLetter(arr[right])) right--; 22 | 23 | // If both are letters, swap them 24 | else { 25 | char temp = arr[left]; 26 | arr[left++] = arr[right]; 27 | arr[right--] = temp; 28 | } 29 | } 30 | 31 | // Convert the character array to a string 32 | return new String(arr); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ReversePrefixOfWord.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.Stack; 4 | 5 | public class ReversePrefixOfWord { 6 | 7 | String reversePrefix(String word, char ch) { 8 | 9 | int firstOccurrence = word.indexOf(ch); 10 | if (firstOccurrence == -1) 11 | return word; 12 | 13 | Stack charStack = new Stack<>(); 14 | 15 | // Add all elements to stack 16 | for (int i = 0; i <= firstOccurrence; i++) 17 | charStack.push(word.charAt(i)); 18 | 19 | StringBuilder result = new StringBuilder(); 20 | 21 | // POP elements of stack 22 | while (!charStack.isEmpty()) 23 | result.append(charStack.pop()); 24 | 25 | // Add all remaining chars 26 | for (int i = (firstOccurrence + 1); i < word.length(); i++) 27 | result.append(word.charAt(i)); 28 | 29 | return result.toString(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ReverseWordsInAString3.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.StringJoiner; 4 | 5 | /** 6 | * @author nikoo28 on 9/10/17 7 | */ 8 | class ReverseWordsInAString3 { 9 | 10 | String reverseWords(String s) { 11 | 12 | String[] splits = s.split(" "); 13 | StringJoiner outputString = new StringJoiner(" "); 14 | 15 | for (String split : splits) { 16 | outputString.add(new StringBuilder(split).reverse().toString()); 17 | } 18 | 19 | return outputString.toString(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ReverseWordsInAStringIII.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class ReverseWordsInAStringIII { 4 | 5 | String reverseWords(String s) { 6 | 7 | char[] arr = s.toCharArray(); 8 | 9 | int left = 0, right = 0; 10 | 11 | while (right < arr.length) { 12 | // If we find a space, reverse the word 13 | if (arr[right] == ' ') { 14 | reverse(arr, left, right - 1); 15 | left = right + 1; 16 | } 17 | 18 | right++; 19 | } 20 | 21 | // Reverse the last word 22 | reverse(arr, left, right - 1); 23 | 24 | // Return the string 25 | return new String(arr); 26 | } 27 | 28 | private void reverse(char[] arr, int left, int right) { 29 | while (left < right) { 30 | char temp = arr[left]; 31 | arr[left++] = arr[right]; 32 | arr[right--] = temp; 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/RotateArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-07-21 14:59 5 | */ 6 | 7 | class RotateArray { 8 | 9 | public void rotate(int[] nums, int k) { 10 | 11 | if (nums.length == 0) 12 | return; 13 | 14 | k %= nums.length; 15 | reverse(nums, 0, nums.length - 1); 16 | reverse(nums, 0, k - 1); 17 | reverse(nums, k, nums.length - 1); 18 | } 19 | 20 | private void reverse(int[] nums, int start, int end) { 21 | while (start < end) { 22 | int temp = nums[start]; 23 | nums[start] = nums[end]; 24 | nums[end] = temp; 25 | start++; 26 | end--; 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/SameTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class SameTree { 9 | 10 | boolean isSameTree(TreeNode root1, TreeNode root2) { 11 | 12 | Queue queue = new LinkedList<>(); 13 | queue.add(root1); 14 | queue.add(root2); 15 | 16 | // Loop till the queue is not empty 17 | while (!queue.isEmpty()) { 18 | TreeNode first = queue.poll(); 19 | TreeNode second = queue.poll(); 20 | 21 | // Check for equality 22 | if (first == null && second == null) { 23 | continue; 24 | } else if ( 25 | first == null || second == null || first.val != second.val) { 26 | return false; 27 | } 28 | 29 | // Add other nodes 30 | queue.add(first.left); 31 | queue.add(second.left); 32 | queue.add(first.right); 33 | queue.add(second.right); 34 | } 35 | return true; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class SearchInsertPosition { 4 | 5 | public int searchInsert(int[] nums, int target) { 6 | 7 | int low = 0; 8 | int high = nums.length - 1; 9 | 10 | while (low <= high) { 11 | int mid = low + (high - low) / 2; 12 | 13 | if (nums[mid] == target) { 14 | return mid; 15 | } else if (nums[mid] > target) { 16 | high = mid - 1; 17 | } else { 18 | low = mid + 1; 19 | } 20 | } 21 | 22 | return low; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ShuffleString.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class ShuffleString { 4 | 5 | String restoreString(String s, int[] indices) { 6 | 7 | // Character array to form final string 8 | char[] str = new char[s.length()]; 9 | 10 | // Do what the question says 11 | for (int i = 0; i < s.length(); i++) { 12 | str[indices[i]] = s.charAt(i); 13 | } 14 | 15 | // Return the restored string 16 | return String.valueOf(str); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/SingleNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * @author nikoo28 on 9/16/17 5 | */ 6 | class SingleNumber { 7 | 8 | public int singleNumber(int[] nums) { 9 | int sing = nums[0]; 10 | for (int i = 1; i < nums.length; i++) { 11 | sing = sing ^ nums[i]; 12 | } 13 | return sing; 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/SquaresOfSortedArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class SquaresOfSortedArray { 4 | 5 | int[] sortedSquares(int[] nums) { 6 | 7 | int[] result = new int[nums.length]; 8 | 9 | // Square all elements 10 | for (int i = 0; i < nums.length; i++) { 11 | nums[i] = nums[i] * nums[i]; 12 | } 13 | 14 | int head = 0; 15 | int tail = nums.length - 1; 16 | 17 | // Set them at right place in the result array 18 | for (int pos = nums.length - 1; pos >= 0; pos--) { 19 | 20 | if (nums[head] > nums[tail]) { 21 | result[pos] = nums[head]; 22 | // Increment head pointer 23 | head++; 24 | } else { 25 | result[pos] = nums[tail]; 26 | // Increment tail pointer 27 | tail--; 28 | } 29 | } 30 | 31 | return result; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/StringCompression.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-09-14 17:34 5 | */ 6 | 7 | class StringCompression { 8 | 9 | public int compress(char[] chars) { 10 | int anchor = 0, write = 0; 11 | for (int read = 0; read < chars.length; read++) { 12 | if (read + 1 == chars.length || chars[read + 1] != chars[read]) { 13 | chars[write++] = chars[anchor]; 14 | if (read > anchor) { 15 | for (char c : ("" + (read - anchor + 1)).toCharArray()) { 16 | chars[write++] = c; 17 | } 18 | } 19 | anchor = read + 1; 20 | } 21 | } 22 | return write; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/SumOfUniqueElements.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class SumOfUniqueElements { 4 | 5 | int sumOfUnique(int[] nums) { 6 | 7 | // Create a frequency array to store the frequency 8 | int[] freq = new int[101]; 9 | int sum = 0; 10 | 11 | for (int num : nums) 12 | freq[num]++; 13 | 14 | for (int i = 0; i < freq.length; i++) { 15 | if (freq[i] == 1) { 16 | sum += i; 17 | } 18 | } 19 | 20 | return sum; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/TwoSumII.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 12/17/17 8:54 PM 5 | */ 6 | 7 | class TwoSumII { 8 | 9 | public int[] twoSum(int[] numbers, int target) { 10 | 11 | int start = 0; 12 | int end = numbers.length - 1; 13 | 14 | while (start < end) { 15 | int sum = numbers[start] + numbers[end]; 16 | if (sum > target) 17 | end--; 18 | if (sum < target) 19 | start++; 20 | if (sum == target) 21 | break; 22 | } 23 | 24 | return new int[]{start + 1, end + 1}; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/UglyNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 10/19/19 3:21 PM 5 | */ 6 | 7 | public class UglyNumber { 8 | 9 | public boolean isUgly(int num) { 10 | if (num == 1) return true; 11 | if (num == 0) return false; 12 | while (num % 2 == 0) num = num >> 1; 13 | while (num % 3 == 0) num = num / 3; 14 | while (num % 5 == 0) num = num / 5; 15 | return num == 1; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Created by nikoo28 on 9/23/18 12:40 PM 5 | */ 6 | 7 | class ValidAnagram { 8 | 9 | public boolean isAnagram(String str1, String str2) { 10 | 11 | // Convert both to lowercase to ignore case match 12 | str1 = str1.toLowerCase(); 13 | str2 = str2.toLowerCase(); 14 | 15 | // Strip of all the white spaces 16 | str1 = str1.replace(" ", ""); 17 | str2 = str2.replace(" ", ""); 18 | 19 | // Initialize the bucket array 20 | int[] counts = new int[26]; 21 | 22 | // Fill the buckets 23 | for (int i = 0; i < str1.length(); i++) { 24 | counts[str1.charAt(i) - 'a']++; 25 | } 26 | 27 | // Empty the buckets 28 | for (int i = 0; i < str2.length(); i++) { 29 | counts[str2.charAt(i) - 'a']--; 30 | } 31 | 32 | // Check if all buckets are empty 33 | for (int count : counts) { 34 | if (count != 0) 35 | return false; 36 | } 37 | 38 | return true; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class ValidPalindrome { 4 | 5 | boolean validPalindrome(String s) { 6 | // Get the left and right pointers 7 | int left = 0; 8 | int right = s.length() - 1; 9 | 10 | // Start a loop and compare characters 11 | while (left < right) 12 | // If same, move both pointers 13 | if (s.charAt(left) == s.charAt(right)) { 14 | left++; 15 | right--; 16 | } 17 | // If not, simply return false 18 | else 19 | return false; 20 | 21 | // If we come out of the loop, then all 22 | // characters have matched, return true 23 | return true; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ValidPalindromeII.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | public class ValidPalindromeII { 4 | 5 | boolean validPalindrome(String s) { 6 | int left = 0; 7 | int right = s.length() - 1; 8 | 9 | while (left < right) { 10 | // Keep moving till characters match 11 | if (s.charAt(left) == s.charAt(right)) { 12 | left++; 13 | right--; 14 | } else { 15 | // Try deleting 1 character from either direction 16 | return isPalindrome(s, left + 1, right) 17 | || isPalindrome(s, left, right - 1); 18 | } 19 | } 20 | 21 | return true; 22 | } 23 | 24 | private boolean isPalindrome(String s, int left, int right) { 25 | while (left < right) { 26 | if (s.charAt(left) == s.charAt(right)) { 27 | left++; 28 | right--; 29 | } else return false; 30 | } 31 | return true; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/ValidParantheses.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * Created by nikoo28 on 7/11/19 2:00 AM 7 | */ 8 | 9 | class ValidParantheses { 10 | 11 | boolean isValid(String s) { 12 | 13 | Stack stack = new Stack<>(); 14 | 15 | for (char c : s.toCharArray()) { 16 | 17 | if (c == '(') 18 | stack.push(')'); 19 | else if (c == '{') 20 | stack.push('}'); 21 | else if (c == '[') 22 | stack.push(']'); 23 | 24 | else if (stack.isEmpty() || stack.pop() != c) 25 | return false; 26 | } 27 | return stack.isEmpty(); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/hard/SlidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | package leetcode.hard; 2 | 3 | /** 4 | * Created by nikoo28 on 7/20/19 12:26 AM 5 | */ 6 | 7 | class SlidingWindowMaximum { 8 | 9 | public int[] maxSlidingWindow(int[] nums, int k) { 10 | 11 | int n = nums.length; 12 | if (n * k == 0) return new int[0]; 13 | 14 | int[] output = new int[n - k + 1]; 15 | for (int i = 0; i < n - k + 1; i++) { 16 | int max = Integer.MIN_VALUE; 17 | for (int j = i; j < i + k; j++) 18 | max = Math.max(max, nums[j]); 19 | output[i] = max; 20 | } 21 | return output; 22 | 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.ListNode; 4 | 5 | import java.util.List; 6 | 7 | public class AddTwoNumbers { 8 | 9 | ListNode addTwoNumbers(ListNode l1, ListNode l2) { 10 | 11 | ListNode result = new ListNode(0); 12 | ListNode ptr = result; 13 | 14 | int carry = 0; // Set default carry 15 | 16 | while (l1 != null || l2 != null) { 17 | 18 | int sum = 0 + carry; // Initialize sum 19 | 20 | if (l1 != null) { // Use number from first list 21 | sum += l1.val; 22 | l1 = l1.next; 23 | } 24 | 25 | if (l2 != null) { // Use number from 2nd list 26 | sum += l2.val; 27 | l2 = l2.next; 28 | } 29 | 30 | carry = sum / 10; // Get sum and carry 31 | sum = sum % 10; 32 | ptr.next = new ListNode(sum); 33 | ptr = ptr.next; 34 | } 35 | 36 | if (carry == 1) ptr.next = new ListNode(1); 37 | 38 | return result.next; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/BoatsToSavePeople.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BoatsToSavePeople { 6 | 7 | int numRescueBoats(int[] people, int limit) { 8 | 9 | // Sort the people by weight 10 | Arrays.sort(people); 11 | 12 | int boats = 0; 13 | 14 | // Use 2 pointers to find the heaviest and lightest person 15 | int left = 0, right = people.length - 1; 16 | 17 | while (left <= right) { 18 | 19 | // If heaviest and lightest person can fit in same boat 20 | if (people[left] + people[right] <= limit) { 21 | left++; 22 | } 23 | 24 | // In any case, the heaviest person will be on the boat 25 | right--; 26 | 27 | // Increment the number of boats 28 | boats++; 29 | } 30 | 31 | return boats; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/CapacityToShipPackagesWithinDDays.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class CapacityToShipPackagesWithinDDays { 4 | 5 | int shipWithinDays(int[] weights, int D) { 6 | 7 | int minCap = 0; 8 | int maxCap = 0; 9 | for (int weight : weights) { 10 | 11 | minCap = Math.max(minCap, weight); 12 | maxCap += weight; 13 | } 14 | 15 | // Apply binary search 16 | while (minCap < maxCap) { 17 | int mid = minCap + (maxCap - minCap) / 2; 18 | 19 | // Try to ship with "mid" capacity 20 | int days = 1; 21 | int sum = 0; 22 | for (int weight : weights) { 23 | if (sum + weight > mid) { 24 | days++; 25 | sum = 0; 26 | } 27 | sum += weight; 28 | } 29 | 30 | // If more days are required, increase capacity 31 | if (days > D) 32 | minCap = mid + 1; 33 | else 34 | maxCap = mid; 35 | } 36 | 37 | return minCap; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/CoinChange.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class CoinChange { 4 | 5 | int coinChange(int[] coins, int amount) { 6 | 7 | // Check edge case 8 | if (amount < 1) return 0; 9 | 10 | // Create DP array 11 | int[] minCoinsDP = new int[amount + 1]; 12 | 13 | for (int i = 1; i <= amount; i++) { 14 | 15 | minCoinsDP[i] = Integer.MAX_VALUE; 16 | 17 | // Try each coin 18 | for (int coin : coins) { 19 | if (coin <= i && minCoinsDP[i - coin] != Integer.MAX_VALUE) 20 | minCoinsDP[i] = Math.min(minCoinsDP[i], 1 + minCoinsDP[i - coin]); 21 | } 22 | } 23 | 24 | return minCoinsDP[amount] == Integer.MAX_VALUE ? -1 : minCoinsDP[amount]; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/CompareVersionNumbers.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-08-24 00:57 5 | */ 6 | 7 | class CompareVersionNumbers { 8 | 9 | public int compareVersion(String version1, String version2) { 10 | 11 | String[] v1 = version1.split("\\."); 12 | String[] v2 = version2.split("\\."); 13 | 14 | int longest = Math.max(v1.length, v2.length); 15 | 16 | for (int i = 0; i < longest; i++) { 17 | int ver1 = i < v1.length ? Integer.parseInt(v1[i]) : 0; 18 | int ver2 = i < v2.length ? Integer.parseInt(v2[i]) : 0; 19 | 20 | if (ver1 > ver2) return 1; 21 | if (ver1 < ver2) return -1; 22 | } 23 | return 0; 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Created by nikoo28 on 12/18/17 9:25 PM 5 | */ 6 | 7 | class ContainerWithMostWater { 8 | 9 | public int maxArea(int[] height) { 10 | 11 | int left = 0; 12 | int right = height.length - 1; 13 | int maxArea = 0; 14 | 15 | while (left < right) { 16 | 17 | int area = 18 | Math.min(height[left], height[right]) 19 | * (right - left); 20 | 21 | maxArea = Math.max(area, maxArea); 22 | 23 | if (height[left] < height[right]) 24 | left++; 25 | else 26 | right--; 27 | } 28 | 29 | return maxArea; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/ContiguousArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class ContiguousArray { 7 | 8 | int findMaxLength(int[] nums) { 9 | 10 | if (nums == null || nums.length == 0) { // Base Case 11 | return 0; 12 | } 13 | 14 | // Converting all 0 to -1 15 | for (int i = 0; i < nums.length; i++) 16 | if (nums[i] == 0) nums[i] = -1; 17 | 18 | int sum = 0; // current 19 | int maxLength = 0; // final-ans 20 | 21 | Map map = new HashMap<>(); 22 | map.put(0, -1); // put sentinel value 23 | 24 | for (int i = 0; i < nums.length; i++) { 25 | sum += nums[i]; 26 | 27 | if (map.containsKey(sum)) { 28 | // if present, update length 29 | int last = map.get(sum); 30 | maxLength = Math.max(maxLength, i - last); 31 | } else 32 | map.put(sum, i); 33 | 34 | } 35 | 36 | return maxLength; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/CountServersThatCommunicate.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class CountServersThatCommunicate { 4 | 5 | int countServers(int[][] grid) { 6 | 7 | int rows = grid.length; 8 | int cols = rows == 0 ? 0 : grid[0].length; 9 | 10 | int[] rowCount = new int[rows]; 11 | int[] colCount = new int[cols]; 12 | 13 | int servers = 0; 14 | 15 | for (int row = 0; row < rows; row++) 16 | for (int col = 0; col < cols; col++) 17 | if (grid[row][col] == 1) { 18 | ++rowCount[row]; 19 | ++colCount[col]; 20 | } 21 | 22 | for (int row = 0; row < rows; row++) 23 | for (int col = 0; col < cols; col++) 24 | if (grid[row][col] == 1 && (rowCount[row] > 1 || colCount[col] > 1)) { 25 | ++servers; 26 | } 27 | 28 | return servers; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/DailyTemperatures.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Stack; 4 | 5 | public class DailyTemperatures { 6 | 7 | public int[] dailyTemperatures(int[] temperatures) { 8 | 9 | Stack helperStack = new Stack<>(); 10 | 11 | int n = temperatures.length; 12 | int[] result = new int[n]; 13 | 14 | for(int idx = n - 1; idx >= 0; idx--) { 15 | 16 | // Popping all indices with a lower or equal 17 | // temperature than the current index 18 | while(!helperStack.isEmpty() 19 | && temperatures[idx] >= temperatures[helperStack.peek()]) { 20 | helperStack.pop(); 21 | } 22 | 23 | // If the stack still has elements, 24 | // then the next warmer temperature exists! 25 | if(!helperStack.isEmpty()) { 26 | result[idx] = helperStack.peek() - idx; 27 | } 28 | 29 | // Inserting current index in the stack 30 | helperStack.push(idx); 31 | } 32 | 33 | return result; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/DecodeWays.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class DecodeWays { 4 | 5 | int numDecodings(String s) { 6 | int n = s.length(); 7 | int[] dp = new int[n + 1]; 8 | dp[0] = 1; 9 | dp[1] = s.charAt(0) == '0' ? 0 : 1; 10 | 11 | for (int i = 2; i <= n; i++) { 12 | int oneDigit = Integer.valueOf(s.substring(i - 1, i)); 13 | int twoDigits = Integer.valueOf(s.substring(i - 2, i)); 14 | 15 | if (oneDigit >= 1) 16 | dp[i] += dp[i - 1]; 17 | 18 | if (twoDigits >= 10 && twoDigits <= 26) 19 | dp[i] += dp[i - 2]; 20 | } 21 | 22 | return dp[n]; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/FindMinimumInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class FindMinimumInRotatedSortedArray { 4 | 5 | int findMin(int[] nums) { 6 | 7 | int left = 0; 8 | int right = nums.length - 1; 9 | 10 | while (left < right) { 11 | 12 | int mid = left + (right - left) / 2; 13 | 14 | // Check if the middle element is greater 15 | // than the right element 16 | if (nums[mid] > nums[right]) { 17 | left = mid + 1; 18 | } else { 19 | right = mid; 20 | } 21 | } 22 | 23 | return nums[left]; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/GasStation.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class GasStation { 4 | 5 | int canCompleteCircuit(int[] gas, int[] cost) { 6 | int totalGas = 0, totalCost = 0; 7 | 8 | // Calculate total gas and total cost 9 | for (int i = 0; i < gas.length; i++) { 10 | totalGas += gas[i]; 11 | totalCost += cost[i]; 12 | } 13 | 14 | // If total gas is less than total cost, return -1 15 | if (totalGas < totalCost) { 16 | return -1; 17 | } 18 | 19 | int currentGas = 0, startIndex = 0; 20 | // Iterate through the gas stations 21 | for (int i = 0; i < gas.length; i++) { 22 | currentGas += gas[i] - cost[i]; 23 | 24 | // If current gas is negative, reset start index and current gas 25 | if (currentGas < 0) { 26 | startIndex = i + 1; 27 | currentGas = 0; 28 | } 29 | } 30 | 31 | // Return the starting index if a valid circuit exists 32 | return startIndex; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/GenerateParantheses.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by nikoo28 on 11/2/19 11:28 PM 8 | */ 9 | 10 | class GenerateParantheses { 11 | 12 | List generateParenthesis(int n) { 13 | 14 | List list = new ArrayList<>(); 15 | backtrack(list, "", 0, 0, n); 16 | return list; 17 | } 18 | 19 | private void backtrack(List list, String str, int open, int close, int max) { 20 | 21 | if (str.length() == max * 2) { 22 | list.add(str); 23 | return; 24 | } 25 | 26 | if (open < max) 27 | backtrack(list, str + "(", open + 1, close, max); 28 | if (close < open) 29 | backtrack(list, str + ")", open, close + 1, max); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/HouseRobber.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class HouseRobber { 4 | 5 | int rob(int[] nums) { 6 | 7 | // If only 1 element, just return it 8 | if (nums.length < 2) 9 | return nums[0]; 10 | 11 | // Create array to store the maximum loot at each index 12 | int[] dp = new int[nums.length]; 13 | 14 | // Memoize maximum loots at first 2 indexes 15 | dp[0] = nums[0]; 16 | dp[1] = Math.max(nums[0], nums[1]); 17 | 18 | // Use them to fill complete array 19 | for (int i = 2; i < nums.length; i++) { 20 | 21 | // Core logic 22 | dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); 23 | } 24 | 25 | return dp[nums.length - 1]; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/HouseRobberIII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.TreeNode; 4 | 5 | public class HouseRobberIII { 6 | 7 | int rob(TreeNode root) { 8 | 9 | int[] options = travel(root); 10 | return Math.max(options[0], options[1]); 11 | } 12 | 13 | private int[] travel(TreeNode root) { 14 | // Base case. just return {0,0} as you cannot rob anything 15 | if (root == null) 16 | return new int[2]; 17 | 18 | int[] left_node_choices = travel(root.left); 19 | int[] right_node_choices = travel(root.right); 20 | int[] options = new int[2]; 21 | 22 | // Store value if looted in [0] 23 | options[0] = root.val + left_node_choices[1] + right_node_choices[1]; 24 | 25 | // Store value if skipped in [1] 26 | options[1] = Math.max(left_node_choices[0], left_node_choices[1]) + 27 | Math.max(right_node_choices[0], right_node_choices[1]); 28 | 29 | return options; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/InsertInterval.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class InsertInterval { 4 | 5 | int[][] insert(int[][] intervals, int[] newInterval) { 6 | int[][] result = new int[intervals.length + 1][2]; 7 | int i = 0, j = 0; 8 | 9 | // Add all intervals that end before the new interval starts 10 | while (i < intervals.length && intervals[i][1] < newInterval[0]) { 11 | result[j++] = intervals[i++]; 12 | } 13 | 14 | // Merge overlapping intervals 15 | while (i < intervals.length && intervals[i][0] <= newInterval[1]) { 16 | newInterval[0] = Math.min(newInterval[0], intervals[i][0]); 17 | newInterval[1] = Math.max(newInterval[1], intervals[i++][1]); 18 | } 19 | 20 | result[j++] = newInterval; 21 | 22 | // Add remaining intervals 23 | while (i < intervals.length) { 24 | result[j++] = intervals[i++]; 25 | } 26 | 27 | return java.util.Arrays.copyOf(result, j); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/JumpGame.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class JumpGame { 4 | 5 | boolean canJump(int[] nums) { 6 | 7 | // Initially the final position is the last index 8 | int finalPosition = nums.length - 1; 9 | 10 | // Start with the second last index 11 | for (int idx = nums.length - 2; idx >= 0; idx--) { 12 | 13 | // If you can reach the final position from this index 14 | // update the final position flag 15 | if (idx + nums[idx] >= finalPosition) { 16 | finalPosition = idx; 17 | } 18 | } 19 | 20 | // If we reach the first index, then we can 21 | // make the jump possible 22 | return finalPosition == 0; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/JumpGameII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class JumpGameII { 4 | 5 | int jump(int[] nums) { 6 | 7 | int totalJumps = 0; 8 | 9 | // destination is last index 10 | int destination = nums.length - 1; 11 | 12 | int coverage = 0, lastJumpIdx = 0; 13 | 14 | // Base case 15 | if (nums.length == 1) return 0; 16 | 17 | // Greedy strategy: extend coverage as long as possible 18 | for (int i = 0; i < nums.length; i++) { 19 | 20 | coverage = Math.max(coverage, i + nums[i]); 21 | 22 | if (i == lastJumpIdx) { 23 | lastJumpIdx = coverage; 24 | totalJumps++; 25 | 26 | // check if we reached destination already 27 | if (coverage >= destination) { 28 | return totalJumps; 29 | } 30 | } 31 | } 32 | 33 | return totalJumps; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/JumpGameIII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class JumpGameIII { 7 | 8 | boolean canReach(int[] arr, int start) { 9 | 10 | Queue q = new LinkedList<>(); 11 | q.add(start); 12 | 13 | while (!q.isEmpty()) { 14 | int curr = q.poll(); 15 | 16 | // reached the target index 17 | if (arr[curr] == 0) 18 | return true; 19 | 20 | // negative means we already tried it 21 | if (arr[curr] < 0) 22 | continue; 23 | 24 | // Try both directions 25 | if (curr + arr[curr] < arr.length) q.add(curr + arr[curr]); 26 | 27 | if (curr - arr[curr] >= 0) q.add(curr - arr[curr]); 28 | 29 | // mark this element as visited 30 | arr[curr] = -arr[curr]; 31 | } 32 | 33 | return false; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/KokoEatingBananas.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class KokoEatingBananas { 4 | 5 | int minEatingSpeed(int[] piles, int h) { 6 | int minSpeed = 1; 7 | 8 | // Find max pile size 9 | int maxSpeed = 0; 10 | for (int pile : piles) 11 | maxSpeed = Math.max(maxSpeed, pile); 12 | 13 | // Binary search 14 | while (minSpeed < maxSpeed) { 15 | int mid = minSpeed + (maxSpeed - minSpeed) / 2; 16 | 17 | if (canEatInTime(piles, h, mid)) 18 | maxSpeed = mid; 19 | else 20 | minSpeed = mid + 1; 21 | } 22 | 23 | return minSpeed; 24 | } 25 | 26 | private boolean canEatInTime(int[] piles, int h, int speed) { 27 | int hours = 0; 28 | for(int pile : piles) 29 | hours += (int) Math.ceil((double) pile / speed); 30 | 31 | return hours <= h; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/LinkedListCycleII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.ListNode; 4 | 5 | /** 6 | * Created by nikoo28 on 12/19/17 12:43 AM 7 | */ 8 | 9 | class LinkedListCycleII { 10 | 11 | public ListNode detectCycle(ListNode head) { 12 | 13 | // Start both from head 14 | ListNode slow = head, fast = head; 15 | 16 | // Advance both at different speeds 17 | // until they meet once 18 | while (fast != null && fast.next != null) { 19 | fast = fast.next.next; 20 | slow = slow.next; 21 | 22 | // As soon as they meet, start from the 23 | // head again and move at the same speed 24 | if (slow == fast) { 25 | while (head != slow) { 26 | head = head.next; 27 | slow = slow.next; 28 | } 29 | return slow; 30 | } 31 | } 32 | return null; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class LongestCommonSubsequence { 4 | 5 | int longestCommonSubsequence(String text1, String text2) { 6 | // Construct dp matrix 7 | int[][] dp = new int[text1.length() + 1][text2.length() + 1]; 8 | 9 | // Iterate over each cell and update values 10 | for (int i = 1; i <= text1.length(); i++) 11 | 12 | for (int j = 1; j <= text2.length(); j++) 13 | 14 | if (text1.charAt(i - 1) == text2.charAt(j - 1)) 15 | dp[i][j] = 1 + dp[i - 1][j - 1]; 16 | else 17 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 18 | 19 | // Return the value in last cell 20 | return dp[text1.length()][text2.length()]; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/LongestIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class LongestIncreasingSubsequence { 4 | 5 | int lengthOfLIS(int[] nums) { 6 | 7 | int[] T = new int[nums.length]; 8 | 9 | // Start main pointer 10 | for (int i = 1; i < nums.length; i++) 11 | 12 | // Start second pointer 13 | for (int j = 0; j < i; j++) 14 | if (nums[i] > nums[j]) 15 | if (T[j] + 1 > T[i]) 16 | T[i] = T[j] + 1; 17 | 18 | // find the max value 19 | int maxIndex = 0; 20 | for (int i = 0; i < T.length; i++) 21 | if (T[i] > T[maxIndex]) 22 | maxIndex = i; 23 | 24 | return T[maxIndex] + 1; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/LongestSubstringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Created by nikoo28 on 12/18/17 9:29 PM 8 | */ 9 | 10 | class LongestSubstringWithoutRepeatingCharacters { 11 | 12 | int lengthOfLongestSubstring(String s) { 13 | 14 | Set charSet = new HashSet<>(); 15 | 16 | int maxLength = 0; 17 | int left = 0; 18 | 19 | for (int right = 0; right < s.length(); right++) { 20 | 21 | while (charSet.contains(s.charAt(right))) { 22 | charSet.remove(s.charAt(left)); 23 | left++; 24 | } 25 | 26 | charSet.add(s.charAt(right)); 27 | maxLength = Math.max(maxLength, right - left + 1); 28 | } 29 | 30 | return maxLength; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/LowestCommonAncestorOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.TreeNode; 4 | 5 | /** 6 | * Created by nikoo28 on 12/19/17 12:55 AM 7 | */ 8 | 9 | class LowestCommonAncestorOfBinaryTree { 10 | 11 | TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 | if (root == null || root == p || root == q) 13 | return root; 14 | 15 | TreeNode left = lowestCommonAncestor(root.left, p, q); 16 | TreeNode right = lowestCommonAncestor(root.right, p, q); 17 | 18 | if (left != null && right != null) 19 | return root; 20 | 21 | if (left != null) 22 | return left; 23 | else 24 | return right; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MaxConsecutiveOnesIII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class MaxConsecutiveOnesIII { 4 | 5 | int longestOnes(int[] nums, int k) { 6 | 7 | int zeroCount = 0; 8 | int start = 0; 9 | int max_ones = 0; 10 | 11 | for (int end = 0; end < nums.length; end++) { 12 | if (nums[end] == 0) 13 | zeroCount++; 14 | 15 | while (zeroCount > k) { 16 | if (nums[start] == 0) 17 | zeroCount--; 18 | 19 | start++; 20 | } 21 | 22 | max_ones = Math.max(max_ones, end - start + 1); 23 | } 24 | return max_ones; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MaximalSquare.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class MaximalSquare { 4 | 5 | int maximalSquare(char[][] matrix) { 6 | 7 | int rows = matrix.length; 8 | int cols = matrix[0].length; 9 | int[][] dp = new int[rows][cols]; 10 | int maxSide = 0; 11 | 12 | // Fill the dp table 13 | for (int i = 0; i < rows; i++) { 14 | for (int j = 0; j < cols; j++) { 15 | if (matrix[i][j] == '1') { 16 | 17 | // Special handling for the first row and first column 18 | if (i == 0 || j == 0) 19 | dp[i][j] = 1; 20 | else 21 | // For others, dp[i][j] is the minimum of the three neighbors 22 | dp[i][j] = 1 + 23 | Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]); 24 | 25 | maxSide = Math.max(maxSide, dp[i][j]); 26 | } 27 | } 28 | } 29 | 30 | // Return the area of the largest square 31 | return maxSide * maxSide; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MaximumBinaryTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.TreeNode; 4 | 5 | public class MaximumBinaryTree { 6 | 7 | TreeNode constructMaximumBinaryTree(int[] nums) { 8 | if (nums == null) 9 | return null; 10 | return build(nums, 0, nums.length - 1); 11 | } 12 | 13 | private TreeNode build(int[] nums, int start, int end) { 14 | if (start > end) return null; 15 | 16 | // Identify max index 17 | int idxMax = start; 18 | for (int i = start + 1; i <= end; i++) 19 | if (nums[i] > nums[idxMax]) 20 | idxMax = i; 21 | 22 | // Create a root 23 | TreeNode root = new TreeNode(nums[idxMax]); 24 | 25 | // Assign left and right children 26 | root.left = build(nums, start, idxMax - 1); 27 | root.right = build(nums, idxMax + 1, end); 28 | 29 | return root; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MaximumLengthOfRepeatedSubarray.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class MaximumLengthOfRepeatedSubarray { 4 | 5 | int findLength(int[] nums1, int[] nums2) { 6 | 7 | int[][] dp = new int[nums1.length + 1][nums2.length + 1]; 8 | 9 | int max = 0; 10 | 11 | // Iterate over each position in the matrix 12 | for (int i = 1; i <= nums1.length; i++) 13 | for (int j = 1; j <= nums2.length; j++) 14 | 15 | // If numbers are equal 16 | if (nums1[i - 1] == nums2[j - 1]) { 17 | // Get the number from diagonally opposite 18 | // and add 1 19 | dp[i][j] = dp[i - 1][j - 1] + 1; 20 | 21 | max = Math.max(dp[i][j], max); 22 | } 23 | 24 | return max; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MaximumProductAfterKIncrements.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class MaximumProductAfterKIncrements { 6 | 7 | int maximumProduct(int[] nums, int k) { 8 | 9 | PriorityQueue numPQ = new PriorityQueue<>(); 10 | int mod = 1000000007; 11 | 12 | // Add all elements to priority queue 13 | for (int num : nums) 14 | numPQ.offer(num); 15 | 16 | for (int i = 0; i < k; i++) { 17 | // Get the minimum element and increment by 1 18 | int minElement = numPQ.remove(); 19 | minElement++; 20 | 21 | // Add it back to the priority queue 22 | numPQ.offer(minElement); 23 | } 24 | 25 | // Find the product 26 | long result = 1; 27 | while (!numPQ.isEmpty()) { 28 | result *= numPQ.poll(); 29 | result %= mod; 30 | } 31 | 32 | return (int) result; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MaximumProductSubarray.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class MaximumProductSubarray { 4 | 5 | int maxProduct(int[] nums) { 6 | 7 | int n = nums.length; 8 | long leftProduct = 1; 9 | long rightProduct = 1; 10 | long ans = nums[0]; 11 | 12 | for (int i = 0; i < n; i++) { 13 | 14 | //if any of leftProduct or rightProduct become 0 then update it to 1 15 | leftProduct = (leftProduct == 0 || leftProduct < Integer.MIN_VALUE) ? 1 : leftProduct; 16 | rightProduct = (rightProduct == 0 || rightProduct < Integer.MIN_VALUE) ? 1 : rightProduct; 17 | 18 | //prefix product 19 | leftProduct *= nums[i]; 20 | 21 | //suffix product 22 | rightProduct *= nums[n - 1 - i]; 23 | 24 | ans = Math.max(ans, Math.max(leftProduct, rightProduct)); 25 | } 26 | 27 | return (int) ans; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MinStack.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Stack; 4 | 5 | public class MinStack { 6 | 7 | Stack stack; 8 | Stack minStack; 9 | 10 | public MinStack() { 11 | stack = new Stack<>(); 12 | minStack = new Stack<>(); 13 | } 14 | 15 | public void push(int val) { 16 | stack.push(val); 17 | 18 | // If minStack is empty or new value is less than equal to 19 | // the top of the minStack, push it onto the minStack 20 | if (minStack.isEmpty() || val <= minStack.peek()) 21 | minStack.push(val); 22 | } 23 | 24 | public void pop() { 25 | int poppedValue = stack.pop(); 26 | 27 | // If popped value == top of the minStack, 28 | // pop it from the minStack as well 29 | if (poppedValue == minStack.peek()) 30 | minStack.pop(); 31 | } 32 | 33 | public int top() { 34 | return stack.peek(); 35 | } 36 | 37 | public int getMin() { 38 | return minStack.peek(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MinimumIncrementToMakeArrayUnique.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Arrays; 4 | 5 | public class MinimumIncrementToMakeArrayUnique { 6 | 7 | int minIncrementForUnique(int[] nums) { 8 | 9 | Arrays.sort(nums); 10 | 11 | int moves = 0; 12 | 13 | // Iterate through the array 14 | for (int i = 1; i < nums.length; i++) { 15 | 16 | // If the current element is 17 | // less than or equal to the previous element 18 | if (nums[i] <= nums[i - 1]) { 19 | 20 | // Increment the moves by the difference 21 | moves += nums[i - 1] - nums[i] + 1; 22 | nums[i] = nums[i - 1] + 1; 23 | } 24 | } 25 | 26 | return moves; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/MinimumSizeSubarraySum.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class MinimumSizeSubarraySum { 4 | 5 | int minSubArrayLen(int target, int[] nums) { 6 | 7 | int minLenWindow = Integer.MAX_VALUE; 8 | int currentSum = 0; 9 | 10 | // Start 2 pointers sliding window 11 | int low = 0; 12 | int high = 0; 13 | while(high < nums.length) { 14 | 15 | // Find the current sum and increase window size 16 | currentSum += nums[high]; 17 | high++; 18 | 19 | // Try to reduce the window size 20 | while (currentSum >= target) { 21 | 22 | int currentWindowSize = high - low; 23 | 24 | // Update minimum length of window 25 | minLenWindow = Math.min(minLenWindow, currentWindowSize); 26 | 27 | currentSum -= nums[low]; 28 | low++; 29 | } 30 | } 31 | 32 | return minLenWindow == Integer.MAX_VALUE ? 0 : minLenWindow; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/OddEvenLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.ListNode; 4 | 5 | public class OddEvenLinkedList { 6 | 7 | ListNode oddEvenList(ListNode head) { 8 | 9 | if (head == null) 10 | return head; 11 | 12 | ListNode odd = head; 13 | ListNode even = head.next; 14 | 15 | // Maintain the even head 16 | ListNode evenHead = even; 17 | 18 | while (even != null && even.next != null) { 19 | 20 | // Change pointers for odd list 21 | odd.next = odd.next.next; 22 | odd = odd.next; 23 | 24 | // Change pointers for even list 25 | even.next = even.next.next; 26 | even = even.next; 27 | } 28 | 29 | // Assign even list at the end of odd list 30 | odd.next = evenHead; 31 | 32 | return head; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/PalindromicSubstrings.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class PalindromicSubstrings { 4 | 5 | int countSubstrings(String s) { 6 | 7 | int count = 0; 8 | 9 | for (int i = 0; i < s.length(); i++) { 10 | 11 | // Count palindromes with odd length 12 | count += countPalindromes(s, i, i); 13 | 14 | // Count palindromes with even length 15 | count += countPalindromes(s, i, i + 1); 16 | } 17 | 18 | return count; 19 | 20 | } 21 | 22 | private int countPalindromes(String s, int left, int right) { 23 | 24 | int count = 0; 25 | 26 | // Check for palindromes 27 | while (left >= 0 && right < s.length() 28 | && s.charAt(left) == s.charAt(right)) { 29 | count++; 30 | left--; 31 | right++; 32 | } 33 | 34 | return count; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/ProductOfArrayExceptSelf.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Created by nikoo28 on 7/12/19 1:23 AM 5 | */ 6 | 7 | class ProductOfArrayExceptSelf { 8 | 9 | public int[] productExceptSelf(int[] nums) { 10 | 11 | // Array to store all left multiplication 12 | int[] left = new int[nums.length]; 13 | 14 | // Array to store all right multiplication 15 | int[] right = new int[nums.length]; 16 | 17 | left[0] = 1; 18 | for (int i = 1; i < nums.length; i++) { 19 | left[i] = left[i - 1] * nums[i - 1]; 20 | } 21 | 22 | right[nums.length - 1] = 1; 23 | for (int i = nums.length - 2; i > -1; i--) { 24 | right[i] = right[i + 1] * nums[i + 1]; 25 | } 26 | 27 | int[] ans = new int[nums.length]; 28 | for (int i = 0; i < nums.length; i++) { 29 | ans[i] = left[i] * right[i]; 30 | } 31 | 32 | return ans; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/RemoveNthNodeFromEndOfList.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.ListNode; 4 | 5 | public class RemoveNthNodeFromEndOfList { 6 | 7 | ListNode removeNthFromEnd(ListNode head, int n) { 8 | 9 | ListNode dummy = new ListNode(-1); 10 | dummy.next = head; 11 | 12 | ListNode firstPtr = dummy; 13 | ListNode secondPtr = dummy; 14 | 15 | // Move secondPtr n spaces ahead 16 | for (int i = 0; i < n; i++) { 17 | secondPtr = secondPtr.next; 18 | } 19 | 20 | // Move both now, until the next of secondPtr is null 21 | while(secondPtr.next != null) { 22 | firstPtr = firstPtr.next; 23 | secondPtr = secondPtr.next; 24 | } 25 | 26 | // We now have to remove the node next of firstPtr 27 | firstPtr.next = firstPtr.next.next; 28 | 29 | return dummy.next; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/ReverseWordsInAString.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-08-23 22:44 5 | */ 6 | 7 | class ReverseWordsInAString { 8 | 9 | String reverseWords(String s) { 10 | 11 | String[] words = s.split("\\s+"); 12 | StringBuilder reversed = new StringBuilder(); 13 | 14 | for (int i = words.length - 1; i >=0 ; i--) { 15 | reversed.append(words[i].trim()); 16 | reversed.append(" "); 17 | } 18 | 19 | return reversed.toString().trim(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/SearchA2DMatrixII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Created by nikoo28 on 2019-07-21 14:44 5 | */ 6 | 7 | class SearchA2DMatrixII { 8 | 9 | private boolean searchMatrix(int[][] matrix, int target) { 10 | 11 | int row = matrix.length - 1; 12 | int col = 0; 13 | 14 | while (row >= 0 && col <= matrix[row].length) { 15 | 16 | if (target == matrix[row][col]) return true; 17 | if (target > matrix[row][col]) col++; 18 | else row--; 19 | } 20 | 21 | return false; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[][] matrix = {{-1, 3}}; 26 | SearchA2DMatrixII searchA2DMatrixII = new SearchA2DMatrixII(); 27 | 28 | System.out.println(searchA2DMatrixII.searchMatrix(matrix, 3)); 29 | } 30 | 31 | } 32 | 33 | //1 4 7 11 15 34 | //2 5 8 12 19 35 | //3 6 9 16 22 36 | //10 13 14 17 24 37 | //18 21 23 26 30 -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/SortColors.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Created by nikoo28 on 12/19/17 1:12 AM 5 | */ 6 | 7 | class SortColors { 8 | 9 | void sortColors(int[] nums) { 10 | 11 | int start = 0; 12 | int mid = 0; 13 | int end = nums.length - 1; 14 | 15 | while (mid <= end) { 16 | 17 | switch (nums[mid]) { 18 | case 0: 19 | // Swap with start index 20 | swap(nums, start, mid); 21 | mid++; 22 | start++; 23 | break; 24 | 25 | case 1: 26 | mid++; 27 | break; 28 | 29 | case 2: 30 | // Swap with end index 31 | swap(nums, mid, end); 32 | end--; 33 | break; 34 | } 35 | } 36 | 37 | } 38 | 39 | private void swap(int[] arr, int pos1, int pos2) { 40 | int temp = arr[pos1]; 41 | arr[pos1] = arr[pos2]; 42 | arr[pos2] = temp; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/SubArraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by nikoo28 on 2019-09-08 20:33 8 | */ 9 | 10 | class SubArraySumEqualsK { 11 | 12 | public int subarraySum(int[] nums, int k) { 13 | 14 | Map sumCountMap = new HashMap<>(); 15 | sumCountMap.put(0, 1); 16 | 17 | int result = 0; 18 | int prefixSum = 0; 19 | 20 | for (int num : nums) { 21 | prefixSum += num; 22 | if (sumCountMap.containsKey(prefixSum - k)) { 23 | result += sumCountMap.get(prefixSum - k); 24 | } 25 | sumCountMap.put(prefixSum, sumCountMap.getOrDefault(prefixSum, 0) + 1); 26 | } 27 | 28 | return result; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/SubtreeOfAnotherTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.TreeNode; 4 | 5 | import java.util.Stack; 6 | 7 | public class SubtreeOfAnotherTree { 8 | 9 | String preOrderTraversal(TreeNode node) { 10 | if (node == null) { 11 | return "null"; 12 | } 13 | 14 | StringBuilder sb = new StringBuilder("^"); 15 | sb.append(node.val); 16 | sb.append(preOrderTraversal(node.left)); 17 | sb.append(preOrderTraversal(node.right)); 18 | 19 | return sb.toString(); 20 | } 21 | 22 | boolean isSubtree(TreeNode root, TreeNode subRoot) { 23 | 24 | String fullTree = preOrderTraversal(root); 25 | String subTree = preOrderTraversal(subRoot); 26 | 27 | return (fullTree.contains(subTree)); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/SumOfSquareNumbers.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class SumOfSquareNumbers { 4 | 5 | boolean judgeSquareSum(int c) { 6 | 7 | // Base case 8 | if (c < 0) return false; 9 | 10 | // Two pointers 11 | long left = 0; 12 | long right = (int) Math.sqrt(c); 13 | 14 | while (left <= right) { 15 | long sum = left * left + right * right; 16 | 17 | if (sum == c) 18 | return true; 19 | else if (sum < c) 20 | left++; 21 | else 22 | right--; 23 | } 24 | 25 | return false; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.ListNode; 4 | 5 | public class SwapNodesInPairs { 6 | 7 | ListNode swapPairs(ListNode head) { 8 | 9 | // Create a dummy node to ease things 10 | ListNode dummy = new ListNode(0); 11 | dummy.next = head; 12 | 13 | ListNode point = dummy; 14 | 15 | // Ensure nodes we are swapping are not null 16 | while (point.next != null && point.next.next != null) { 17 | 18 | // Identify nodes to swap 19 | ListNode swap1 = point.next; 20 | ListNode swap2 = point.next.next; 21 | 22 | // Actually swap 23 | swap1.next = swap2.next; 24 | swap2.next = swap1; 25 | 26 | 27 | // Prepare for next 28 | point.next = swap2; 29 | point = swap1; 30 | } 31 | 32 | // Return the start node 33 | return dummy.next; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/Triangle.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.List; 4 | 5 | public class Triangle { 6 | 7 | int minimumTotal(List> triangle) { 8 | 9 | int height = triangle.size(); 10 | int[][] dp = new int[height + 1][height + 1]; 11 | 12 | for (int level = height - 1; level >= 0; level--) { 13 | 14 | for (int i = 0; i <= level; i++) { 15 | 16 | // Add the minimum amongst 2 adjacent elements 17 | // from bottom level 18 | dp[level][i] = triangle.get(level).get(i) 19 | + Math.min( 20 | dp[level + 1][i], dp[level + 1][i + 1]); 21 | } 22 | 23 | } 24 | 25 | return dp[0][0]; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/UniquePaths.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | public class UniquePaths { 4 | 5 | int uniquePaths(int m, int n) { 6 | int[][] grid = new int[m][n]; 7 | 8 | // Iterate over the grid 9 | for (int i = 0; i < m; i++) 10 | 11 | for (int j = 0; j < n; j++) { 12 | 13 | // If we are at the first row or first column, 14 | // there is only one way to reach that cell 15 | if (i == 0 || j == 0) 16 | grid[i][j] = 1; 17 | else 18 | // Memoize the number of ways to reach that cell 19 | grid[i][j] = grid[i][j - 1] + grid[i - 1][j]; 20 | } 21 | 22 | // Return the number of ways to reach the last cell 23 | return grid[m - 1][n - 1]; 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/util/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | /** 4 | * Created by nikoo28 on 1/17/21 10:10 PM 5 | */ 6 | 7 | public class BinarySearch { 8 | 9 | static boolean binarySearch(int[] arr, int numberToSearch) { 10 | 11 | int left = 0; 12 | int right = arr.length - 1; 13 | 14 | while (left <= right) { 15 | 16 | // Find the mid index 17 | int mid = (left + right) / 2; 18 | 19 | // Check at mid index 20 | if (arr[mid] == numberToSearch) 21 | return true; 22 | 23 | // Update the terminal indices 24 | if (arr[mid] < numberToSearch) { 25 | left = mid + 1; 26 | } else 27 | right = mid - 1; 28 | } 29 | 30 | return false; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/util/GenerateIntegers.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | public class GenerateIntegers { 7 | 8 | public static void main(String[] args) { 9 | try { 10 | FileWriter myWriter = new FileWriter("integers.txt"); 11 | 12 | for (int i = 0; i < 10000000; i++) { 13 | myWriter.write(i + "\n"); 14 | } 15 | 16 | myWriter.close(); 17 | System.out.println("Successfully wrote to the file."); 18 | } catch (IOException e) { 19 | System.out.println("An error occurred."); 20 | e.printStackTrace(); 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/util/GraphEdge.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | public class GraphEdge { 4 | 5 | private final int source; 6 | private final int destination; 7 | private final int weight; 8 | 9 | public GraphEdge(int source, int destination, int weight) { 10 | this.source = source; 11 | this.destination = destination; 12 | this.weight = weight; 13 | } 14 | 15 | public int getSource() { return source; } 16 | 17 | public int getDestination() { return destination; } 18 | 19 | public int getWeight() { return weight; } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/util/Node.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | /** 4 | * Created by nikoo28 on 31/3/24 14:57:32 5 | */ 6 | 7 | public class Node { 8 | public int val; 9 | 10 | public Node next; 11 | public Node random; 12 | 13 | public Node(int x) { 14 | val = x; 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/java/codility/ambitious/IdenticalPairOfIndicesTest.java: -------------------------------------------------------------------------------- 1 | package codility.ambitious; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/16/19 3:15 AM 9 | */ 10 | 11 | class IdenticalPairOfIndicesTest { 12 | 13 | IdenticalPairOfIndices identicalPairOfIndices = new IdenticalPairOfIndices(); 14 | 15 | @Test 16 | void solution() { 17 | int[] a = {3, 5, 6, 3, 3, 5}; 18 | 19 | assertEquals(4, identicalPairOfIndices.solution(a)); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/codility/painless/BinaryGapTest.java: -------------------------------------------------------------------------------- 1 | package codility.painless; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/16/19 3:12 AM 9 | */ 10 | 11 | class BinaryGapTest { 12 | 13 | BinaryGap binaryGap = new BinaryGap(); 14 | 15 | @Test 16 | void testSolution() { 17 | assertEquals(0, binaryGap.solution(15)); 18 | assertEquals(1, binaryGap.solution(20)); 19 | assertEquals(4, binaryGap.solution(529)); 20 | assertEquals(2, binaryGap.solution(9)); 21 | assertEquals(0, binaryGap.solution(1)); 22 | assertEquals(0, binaryGap.solution(32)); 23 | assertEquals(5, binaryGap.solution(1041)); 24 | assertEquals(0, binaryGap.solution(2147483647)); 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /src/test/java/hackerrank/algorithms/search/PairsTest.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.search; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/1/20 10:24 PM 9 | */ 10 | 11 | class PairsTest { 12 | 13 | Pairs pairs = new Pairs(); 14 | 15 | @Test 16 | void testPairs1() { 17 | int k = 2; 18 | int[] arr = {1, 5, 3, 4, 2}; 19 | 20 | assertEquals(3, pairs.pairs(k, arr)); 21 | } 22 | 23 | 24 | @Test 25 | void testPairs2() { 26 | int k = 1; 27 | int[] arr = {363374326, 364147530, 61825163, 1073065718, 1281246024, 28 | 1399469912, 428047635, 491595254, 879792181, 1069262793}; 29 | 30 | assertEquals(0, pairs.pairs(k, arr)); 31 | } 32 | 33 | @Test 34 | void testPairs3() { 35 | int k = 2; 36 | int[] arr = {1, 3, 5, 8, 6, 4, 2}; 37 | 38 | assertEquals(5, pairs.pairs(k, arr)); 39 | } 40 | } -------------------------------------------------------------------------------- /src/test/java/hackerrank/algorithms/strings/BetterCompressionTest.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class BetterCompressionTest { 8 | 9 | private final BetterCompression betterCompression; 10 | 11 | BetterCompressionTest() { 12 | betterCompression = new BetterCompression(); 13 | } 14 | 15 | @Test 16 | void testBetterCompression1() { 17 | String s = "a3c9b2c1"; 18 | 19 | assertEquals("a3b2c10", betterCompression.betterCompression(s)); 20 | } 21 | 22 | @Test 23 | void testBetterCompression2() { 24 | String s = "a34"; 25 | 26 | assertEquals("a34", betterCompression.betterCompression(s)); 27 | } 28 | 29 | @Test 30 | void testBetterCompression3() { 31 | String s = "a34b121c1a22"; 32 | 33 | assertEquals("a56b121c1", betterCompression.betterCompression(s)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/hackerrank/algorithms/strings/CamelCaseTest.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class CamelCaseTest { 8 | 9 | private final CamelCase camelCase; 10 | 11 | public CamelCaseTest() { 12 | camelCase = new CamelCase(); 13 | } 14 | 15 | @Test 16 | void testCamelcase1() { 17 | String s = "oneTwoThree"; 18 | assertEquals(3, camelCase.camelcase(s)); 19 | } 20 | 21 | @Test 22 | void testCamelcase2() { 23 | String s = "saveChangesInTheEditor"; 24 | assertEquals(5, camelCase.camelcase(s)); 25 | } 26 | 27 | @Test 28 | void testCamelcase3() { 29 | String s = "a"; 30 | assertEquals(1, camelCase.camelcase(s)); 31 | } 32 | 33 | @Test 34 | void testCamelcase4() { 35 | String s = "aBCD"; 36 | assertEquals(4, camelCase.camelcase(s)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/hackerrank/algorithms/strings/TwoCharactersTest.java: -------------------------------------------------------------------------------- 1 | package hackerrank.algorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 8/25/20 9:52 PM 9 | */ 10 | 11 | class TwoCharactersTest { 12 | 13 | private TwoCharacters twoCharacters = new TwoCharacters(); 14 | 15 | @Test 16 | void testTwoCharacters1() { 17 | String str = "beabeefeab"; 18 | assertEquals(5, twoCharacters.alternate(str)); 19 | } 20 | 21 | @Test 22 | void testTwoCharacters2() { 23 | String str = "jshdjshdjshdjs"; 24 | assertEquals(8, twoCharacters.alternate(str)); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/MissingNumberTest.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class MissingNumberTest { 8 | 9 | private final MissingNumber missingNumber; 10 | 11 | MissingNumberTest() { 12 | missingNumber = new MissingNumber(); 13 | } 14 | 15 | @Test 16 | void testMissingNumber1() { 17 | int[] nums = {0, 1}; 18 | 19 | assertEquals(2, missingNumber.missingNumber(nums)); 20 | } 21 | 22 | @Test 23 | void testMissingNumber2() { 24 | int[] nums = {9, 6, 4, 2, 3, 5, 7, 0, 1}; 25 | 26 | assertEquals(8, missingNumber.missingNumber(nums)); 27 | } 28 | 29 | @Test 30 | void testMissingNumber3() { 31 | int[] nums = {0}; 32 | 33 | assertEquals(1, missingNumber.missingNumber(nums)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/BestTimeToBuyAndSellAStockIITest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class BestTimeToBuyAndSellAStockIITest { 8 | 9 | BestTimeToBuyAndSellAStockII bestTimeToBuyAndSellAStockII = new BestTimeToBuyAndSellAStockII(); 10 | 11 | @Test 12 | void maxProfit1() { 13 | int[] prices = {7, 1, 5, 3, 6, 4}; 14 | assertEquals(7, bestTimeToBuyAndSellAStockII.maxProfit(prices)); 15 | } 16 | 17 | @Test 18 | void maxProfit2() { 19 | int[] prices = {1, 2, 3, 4, 5}; 20 | assertEquals(4, bestTimeToBuyAndSellAStockII.maxProfit(prices)); 21 | } 22 | 23 | @Test 24 | void maxProfit3() { 25 | int[] prices = {7, 6, 4, 3, 1}; 26 | assertEquals(0, bestTimeToBuyAndSellAStockII.maxProfit(prices)); 27 | } 28 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/CheckIfPangramTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class CheckIfPangramTest { 8 | 9 | private final CheckIfPangram checkIfPangram; 10 | 11 | CheckIfPangramTest() { 12 | checkIfPangram = new CheckIfPangram(); 13 | } 14 | 15 | @Test 16 | void testCheckIfPangram1() { 17 | String sentence = "thequickbrownfoxjumpsoverthelazydog"; 18 | assertTrue(checkIfPangram.checkIfPangram(sentence)); 19 | } 20 | 21 | @Test 22 | void testCheckIfPangram2() { 23 | String sentence = "studyalgorithms"; 24 | assertFalse(checkIfPangram.checkIfPangram(sentence)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ClimbingStairsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/19/19 3:28 PM 9 | */ 10 | 11 | class ClimbingStairsTest { 12 | 13 | private ClimbingStairs climbingStairs = new ClimbingStairs(); 14 | 15 | @Test 16 | void testClimbStairs() { 17 | assertEquals(2, climbingStairs.climbStairs(2)); 18 | assertEquals(3, climbingStairs.climbStairs(3)); 19 | assertEquals(5, climbingStairs.climbStairs(4)); 20 | assertEquals(8, climbingStairs.climbStairs(5)); 21 | assertEquals(13, climbingStairs.climbStairs(6)); 22 | } 23 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ContainsDuplicateIITest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/11/19 12:32 AM 9 | */ 10 | 11 | class ContainsDuplicateIITest { 12 | 13 | private ContainsDuplicateII containsDuplicateII = new ContainsDuplicateII(); 14 | 15 | @Test 16 | void testContainsNearbyDuplicate1() { 17 | int[] nums = {1, 2, 3, 1}; 18 | assertTrue(containsDuplicateII.containsNearbyDuplicate(nums, 3)); 19 | } 20 | 21 | @Test 22 | void testContainsNearbyDuplicate2() { 23 | int[] nums = {1, 0, 1, 1}; 24 | assertTrue(containsDuplicateII.containsNearbyDuplicate(nums, 1)); 25 | } 26 | 27 | @Test 28 | void testContainsNearbyDuplicate3() { 29 | int[] nums = {1, 2, 3, 1, 2, 3}; 30 | assertFalse(containsDuplicateII.containsNearbyDuplicate(nums, 2)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ContainsDuplicateTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/11/19 12:12 AM 9 | */ 10 | 11 | class ContainsDuplicateTest { 12 | 13 | private final ContainsDuplicate containsDuplicate; 14 | 15 | ContainsDuplicateTest() { 16 | containsDuplicate = new ContainsDuplicate(); 17 | } 18 | 19 | @Test 20 | void testContainsDuplicate1() { 21 | int[] nums = {1, 2, 3, 1}; 22 | assertTrue(containsDuplicate.containsDuplicate(nums)); 23 | } 24 | 25 | @Test 26 | void testContainsDuplicate2() { 27 | int[] nums = {1, 2, 3, 4}; 28 | assertFalse(containsDuplicate.containsDuplicate(nums)); 29 | } 30 | 31 | @Test 32 | void testContainsDuplicate3() { 33 | int[] nums = {1, 1, 1, 3, 3, 4, 3, 2, 4, 2}; 34 | assertTrue(containsDuplicate.containsDuplicate(nums)); 35 | } 36 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/FibonacciNumberTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class FibonacciNumberTest { 8 | 9 | private final FibonacciNumber fibonacciNumber; 10 | 11 | FibonacciNumberTest() { 12 | fibonacciNumber = new FibonacciNumber(); 13 | } 14 | 15 | @Test 16 | void testFib1() { 17 | int n = 2; 18 | assertEquals(1, fibonacciNumber.fib(n)); 19 | } 20 | 21 | @Test 22 | void testFib2() { 23 | int n = 5; 24 | assertEquals(5, fibonacciNumber.fib(n)); 25 | } 26 | 27 | @Test 28 | void testFib3() { 29 | int n = 10; 30 | assertEquals(55, fibonacciNumber.fib(n)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/HappyNumberTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/19/19 3:14 PM 9 | */ 10 | 11 | class HappyNumberTest { 12 | 13 | private HappyNumber happyNumber = new HappyNumber(); 14 | 15 | @Test 16 | void testIsHappy() { 17 | assertTrue(happyNumber.isHappy(7)); 18 | assertTrue(happyNumber.isHappy(19)); 19 | assertTrue(happyNumber.isHappy(31)); 20 | assertTrue(happyNumber.isHappy(8455)); 21 | assertTrue(happyNumber.isHappy(46154)); 22 | assertTrue(happyNumber.isHappy(99942)); 23 | 24 | assertFalse(happyNumber.isHappy(42)); 25 | assertFalse(happyNumber.isHappy(243)); 26 | assertFalse(happyNumber.isHappy(343)); 27 | assertFalse(happyNumber.isHappy(1134)); 28 | assertFalse(happyNumber.isHappy(99999)); 29 | assertFalse(happyNumber.isHappy(756345)); 30 | } 31 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/JewelsAndStonesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class JewelsAndStonesTest { 8 | 9 | private final JewelsAndStones jewelsAndStones; 10 | 11 | JewelsAndStonesTest() { 12 | jewelsAndStones = new JewelsAndStones(); 13 | } 14 | 15 | @Test 16 | void testNumJewelsInStones1() { 17 | String jewels = "aA"; 18 | String stones = "aAAbbbb"; 19 | 20 | assertEquals(3, jewelsAndStones.numJewelsInStones(jewels, stones)); 21 | } 22 | 23 | @Test 24 | void testNumJewelsInStones2() { 25 | String jewels = "z"; 26 | String stones = "ZZ"; 27 | 28 | assertEquals(0, jewelsAndStones.numJewelsInStones(jewels, stones)); 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/LastStoneWeightTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class LastStoneWeightTest { 8 | 9 | private final LastStoneWeight lastStoneWeight; 10 | 11 | LastStoneWeightTest() { 12 | lastStoneWeight = new LastStoneWeight(); 13 | } 14 | 15 | @Test 16 | void testLastStoneWeight1() { 17 | int[] stones = {2, 7, 4, 1, 8, 1}; 18 | assertEquals(1, lastStoneWeight.lastStoneWeight(stones)); 19 | } 20 | 21 | @Test 22 | void testLastStoneWeight2() { 23 | int[] stones = {1, 3}; 24 | assertEquals(2, lastStoneWeight.lastStoneWeight(stones)); 25 | } 26 | 27 | @Test 28 | void testLastStoneWeight3() { 29 | int[] stones = {2, 2}; 30 | assertEquals(0, lastStoneWeight.lastStoneWeight(stones)); 31 | } 32 | 33 | @Test 34 | void testLastStoneWeight4() { 35 | int[] stones = {1, 1, 1, 1, 1}; 36 | assertEquals(1, lastStoneWeight.lastStoneWeight(stones)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/LengthOfLastWordTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class LengthOfLastWordTest { 8 | 9 | private final LengthOfLastWord lengthOfLastWord; 10 | 11 | LengthOfLastWordTest() { 12 | lengthOfLastWord = new LengthOfLastWord(); 13 | } 14 | 15 | @Test 16 | void testLengthOfLastWord1() { 17 | String s = "Hello World"; 18 | assertEquals(5, lengthOfLastWord.lengthOfLastWord(s)); 19 | } 20 | 21 | @Test 22 | void testLengthOfLastWord2() { 23 | String s = " fly me to the moon "; 24 | assertEquals(4, lengthOfLastWord.lengthOfLastWord(s)); 25 | } 26 | 27 | @Test 28 | void testLengthOfLastWord3() { 29 | String s = "luffy is still joyboy"; 30 | assertEquals(6, lengthOfLastWord.lengthOfLastWord(s)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/MajorityElementTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class MajorityElementTest { 8 | 9 | private final MajorityElement majorityElement; 10 | 11 | MajorityElementTest() { 12 | majorityElement = new MajorityElement(); 13 | } 14 | 15 | @Test 16 | void testMajorityElement1() { 17 | int[] num = {3, 3, 2}; 18 | assertEquals(3, majorityElement.majorityElement(num)); 19 | } 20 | 21 | @Test 22 | void testMajorityElement2() { 23 | int[] num = {2, 2, 1, 3, 1, 2, 2}; 24 | assertEquals(2, majorityElement.majorityElement(num)); 25 | } 26 | 27 | @Test 28 | void testMajorityElement3() { 29 | int[] num = {6, 5, 5}; 30 | assertEquals(5, majorityElement.majorityElement(num)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/MaximumSubarrayTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 2019-10-05 18:24 9 | */ 10 | 11 | class MaximumSubarrayTest { 12 | 13 | private MaximumSubarray maximumSubarray = new MaximumSubarray(); 14 | 15 | @Test 16 | void testMaxSubArray1() { 17 | int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3}; 18 | assertEquals(7, maximumSubarray.maxSubArray(arr)); 19 | } 20 | 21 | @Test 22 | void testMaxSubArray2() { 23 | int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; 24 | assertEquals(6, maximumSubarray.maxSubArray(arr)); 25 | } 26 | 27 | @Test 28 | // All negative numbers 29 | void testMaxSubArray3() { 30 | int[] arr = {-2, -51, -3, -4, -1, -22, -11, -5, -7}; 31 | assertEquals(-1, maximumSubarray.maxSubArray(arr)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/MoveZeroesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class MoveZeroesTest { 8 | 9 | private final MoveZeroes moveZeroes; 10 | 11 | MoveZeroesTest() { 12 | moveZeroes = new MoveZeroes(); 13 | } 14 | 15 | @Test 16 | void testMoveZeroes1() { 17 | int[] arr = {0, 1, 0, 3, 12}; 18 | int[] expectedResult = {1, 3, 12, 0, 0}; 19 | 20 | moveZeroes.moveZeroes(arr); 21 | assertArrayEquals(expectedResult, arr); 22 | } 23 | 24 | @Test 25 | void testMoveZeroes2() { 26 | int[] arr = {0, 0, 0}; 27 | int[] expected = {0, 0, 0}; 28 | 29 | moveZeroes.moveZeroes(arr); 30 | assertArrayEquals(expected, arr); 31 | } 32 | 33 | @Test 34 | void testMoveZeroes3() { 35 | int[] arr = {1, 2, 3}; 36 | int[] expected = {1, 2, 3}; 37 | 38 | moveZeroes.moveZeroes(arr); 39 | assertArrayEquals(expected, arr); 40 | } 41 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/NextGreaterElementITest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class NextGreaterElementITest { 8 | 9 | private final NextGreaterElementI nextGreaterElementI; 10 | 11 | NextGreaterElementITest() { 12 | nextGreaterElementI = new NextGreaterElementI(); 13 | } 14 | 15 | @Test 16 | void testNextGreaterElement1() { 17 | int[] nums1 = {4, 1, 2}; 18 | int[] nums2 = {1, 3, 4, 2}; 19 | 20 | int[] expected = {-1, 3, -1}; 21 | int[] actual = nextGreaterElementI.nextGreaterElement(nums1, nums2); 22 | 23 | assertArrayEquals(expected, actual); 24 | } 25 | 26 | @Test 27 | void testNextGreaterElement2() { 28 | int[] nums1 = {2, 4}; 29 | int[] nums2 = {1, 2, 3, 4}; 30 | 31 | int[] expected = {3, -1}; 32 | int[] actual = nextGreaterElementI.nextGreaterElement(nums1, nums2); 33 | 34 | assertArrayEquals(expected, actual); 35 | } 36 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/NumberOf1BitsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/19/19 3:36 PM 9 | */ 10 | 11 | class NumberOf1BitsTest { 12 | 13 | private NumberOf1Bits numberOf1Bits = new NumberOf1Bits(); 14 | 15 | @Test 16 | void testHammingWeight() { 17 | assertEquals(3, numberOf1Bits.hammingWeight(521)); 18 | assertEquals(1, numberOf1Bits.hammingWeight(2097152)); 19 | assertEquals(31, numberOf1Bits.hammingWeight(Integer.MAX_VALUE)); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/NumberOfGoodPairsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class NumberOfGoodPairsTest { 8 | 9 | private final NumberOfGoodPairs numberOfGoodPairs; 10 | 11 | NumberOfGoodPairsTest() { 12 | numberOfGoodPairs = new NumberOfGoodPairs(); 13 | } 14 | 15 | @Test 16 | void testNumIdenticalPairs1() { 17 | int[] nums = {1, 2, 3, 1, 1, 3}; 18 | 19 | assertEquals(4, numberOfGoodPairs.numIdenticalPairs(nums)); 20 | } 21 | 22 | @Test 23 | void testNumIdenticalPairs2() { 24 | int[] nums = {1, 1, 1, 1}; 25 | 26 | assertEquals(6, numberOfGoodPairs.numIdenticalPairs(nums)); 27 | } 28 | 29 | @Test 30 | void testNumIdenticalPairs3() { 31 | int[] nums = {1, 2, 3}; 32 | 33 | assertEquals(0, numberOfGoodPairs.numIdenticalPairs(nums)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/RansomNoteTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class RansomNoteTest { 8 | 9 | private final RansomNote ransomNote; 10 | 11 | RansomNoteTest() { 12 | ransomNote = new RansomNote(); 13 | } 14 | 15 | @Test 16 | void testCanConstruct1() { 17 | String ransomNoteStr = "a"; 18 | String magazineStr = "b"; 19 | assertFalse(ransomNote.canConstruct(ransomNoteStr, magazineStr)); 20 | } 21 | 22 | @Test 23 | void testCanConstruct2() { 24 | String ransomNoteStr = "aa"; 25 | String magazineStr = "ab"; 26 | assertFalse(ransomNote.canConstruct(ransomNoteStr, magazineStr)); 27 | } 28 | 29 | @Test 30 | void testCanConstruct3() { 31 | String ransomNoteStr = "aa"; 32 | String magazineStr = "aab"; 33 | assertTrue(ransomNote.canConstruct(ransomNoteStr, magazineStr)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ReorderDataInLogFilesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | /** 7 | * Created by nikoo28 on 10/8/19 1:25 AM 8 | */ 9 | 10 | class ReorderDataInLogFilesTest { 11 | 12 | private ReorderDataInLogFiles reorderDataInLogFiles = new ReorderDataInLogFiles(); 13 | 14 | @Test 15 | void reorderLogFilesTest() { 16 | String[] input = {"dig1 8 1 5 1", "let1 art can", "dig2 3 6", "let2 own kit dig", "let3 art zero"}; 17 | 18 | String[] expectedOutput = {"let1 art can", "let3 art zero", "let2 own kit dig", "dig1 8 1 5 1", "dig2 3 6"}; 19 | 20 | String[] actualValue = reorderDataInLogFiles.reorderLogFiles(input); 21 | 22 | Assertions.assertArrayEquals(expectedOutput, actualValue); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ReversePrefixOfWordTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ReversePrefixOfWordTest { 8 | 9 | private final ReversePrefixOfWord reversePrefixOfWord; 10 | 11 | ReversePrefixOfWordTest() { 12 | reversePrefixOfWord = new ReversePrefixOfWord(); 13 | } 14 | 15 | @Test 16 | void testReversePrefix1() { 17 | String word = "abcdefd"; 18 | char ch = 'd'; 19 | 20 | assertEquals("dcbaefd", reversePrefixOfWord.reversePrefix(word, ch)); 21 | } 22 | 23 | @Test 24 | void testReversePrefix2() { 25 | String word = "xyxzxe"; 26 | char ch = 'x'; 27 | 28 | assertEquals("xyxzxe", reversePrefixOfWord.reversePrefix(word, ch)); 29 | } 30 | 31 | @Test 32 | void testReversePrefix3() { 33 | String word = "abcdefd"; 34 | char ch = 'x'; 35 | 36 | assertEquals("abcdefd", reversePrefixOfWord.reversePrefix(word, ch)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ReverseWordsInAString3Test.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 11/2/19 5:48 PM 9 | */ 10 | 11 | class ReverseWordsInAString3Test { 12 | 13 | private ReverseWordsInAString3 reverseWordsInAString3 = new ReverseWordsInAString3(); 14 | 15 | @Test 16 | void testReverseWords() { 17 | 18 | String s = "Let's take LeetCode contest"; 19 | String expected = "s'teL ekat edoCteeL tsetnoc"; 20 | 21 | assertEquals(expected, reverseWordsInAString3.reverseWords(s)); 22 | } 23 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/SearchInsertPositionTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class SearchInsertPositionTest { 8 | 9 | private final SearchInsertPosition searchInsertPosition; 10 | 11 | SearchInsertPositionTest() { 12 | searchInsertPosition = new SearchInsertPosition(); 13 | } 14 | 15 | @Test 16 | void testSearchInsert1() { 17 | int[] nums = {1,3,5,6}; 18 | int target = 5; 19 | 20 | assertEquals(2, searchInsertPosition.searchInsert(nums, target)); 21 | } 22 | 23 | @Test 24 | void testSearchInsert2() { 25 | int[] nums = {1,3,5,6}; 26 | int target = 2; 27 | 28 | assertEquals(1, searchInsertPosition.searchInsert(nums, target)); 29 | } 30 | 31 | @Test 32 | void testSearchInsert3() { 33 | int[] nums = {1,3,5,6}; 34 | int target = 7; 35 | 36 | assertEquals(4, searchInsertPosition.searchInsert(nums, target)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ShuffleStringTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ShuffleStringTest { 8 | 9 | private final ShuffleString shuffleString; 10 | 11 | ShuffleStringTest() { 12 | shuffleString = new ShuffleString(); 13 | } 14 | 15 | @Test 16 | void testRestoreString1() { 17 | String s = "codeleet"; 18 | int[] indices = {4, 5, 6, 7, 0, 2, 1, 3}; 19 | 20 | assertEquals("leetcode", shuffleString.restoreString(s, indices)); 21 | } 22 | 23 | @Test 24 | void testRestoreString2() { 25 | String s = "abc"; 26 | int[] indices = {0, 1, 2}; 27 | 28 | assertEquals("abc", shuffleString.restoreString(s, indices)); 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/SingleNumberTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class SingleNumberTest { 8 | 9 | SingleNumber singleNumber = new SingleNumber(); 10 | 11 | @Test 12 | void singleNumber1() { 13 | int[] arr = {2, 2, 1}; 14 | assertEquals(1, singleNumber.singleNumber(arr)); 15 | } 16 | 17 | @Test 18 | void singleNumber2() { 19 | int[] arr = {4, 1, 2, 1, 2}; 20 | assertEquals(4, singleNumber.singleNumber(arr)); 21 | } 22 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/SumOfUniqueElementsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class SumOfUniqueElementsTest { 8 | 9 | private final SumOfUniqueElements sumOfUniqueElements; 10 | 11 | SumOfUniqueElementsTest() { 12 | sumOfUniqueElements = new SumOfUniqueElements(); 13 | } 14 | 15 | @Test 16 | void testSumOfUnique1() { 17 | int[] nums = {1, 2, 3, 2}; 18 | assertEquals(4, sumOfUniqueElements.sumOfUnique(nums)); 19 | } 20 | 21 | @Test 22 | void testSumOfUnique2() { 23 | int[] nums = {1, 1, 1, 1, 1}; 24 | assertEquals(0, sumOfUniqueElements.sumOfUnique(nums)); 25 | } 26 | 27 | @Test 28 | void testSumOfUnique3() { 29 | int[] nums = {1, 2, 3, 4, 5}; 30 | assertEquals(15, sumOfUniqueElements.sumOfUnique(nums)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/UglyNumberTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/19/19 3:21 PM 9 | */ 10 | 11 | class UglyNumberTest { 12 | 13 | private UglyNumber uglyNumber = new UglyNumber(); 14 | 15 | @Test 16 | void testIsUgly() { 17 | assertTrue(uglyNumber.isUgly(8)); 18 | assertTrue(uglyNumber.isUgly(6)); 19 | assertFalse(uglyNumber.isUgly(14)); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ValidAnagramTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 7/3/20 8:44 PM 9 | */ 10 | 11 | class ValidAnagramTest { 12 | 13 | ValidAnagram validAnagram = new ValidAnagram(); 14 | 15 | @Test 16 | void testIsAnagram1() { 17 | assertEquals(false, validAnagram.isAnagram("rat", "car")); 18 | } 19 | 20 | @Test 21 | void testIsAnagram2() { 22 | assertEquals(true, validAnagram.isAnagram("anagram", "nagaram")); 23 | } 24 | 25 | @Test 26 | void testIsAnagram3() { 27 | assertEquals(false, validAnagram.isAnagram("mississippi", "mips")); 28 | } 29 | 30 | @Test 31 | void testIsAnagram4() { 32 | assertEquals(true, validAnagram.isAnagram("silent", "listen")); 33 | } 34 | 35 | @Test 36 | void testIsAnagram5() { 37 | assertEquals(true, validAnagram.isAnagram("a decimal point", "im a dot in place")); 38 | } 39 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ValidPalindromeIITest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ValidPalindromeIITest { 8 | 9 | private final ValidPalindromeII validPalindromeII; 10 | 11 | ValidPalindromeIITest() { 12 | validPalindromeII = new ValidPalindromeII(); 13 | } 14 | 15 | @Test 16 | void testValidPalindrome1() { 17 | String s = "abca"; 18 | assertTrue(validPalindromeII.validPalindrome(s)); 19 | } 20 | 21 | @Test 22 | void testValidPalindrome2() { 23 | String s = "abc"; 24 | assertFalse(validPalindromeII.validPalindrome(s)); 25 | } 26 | 27 | @Test 28 | void testValidPalindrome3() { 29 | String s = "abbva"; 30 | assertTrue(validPalindromeII.validPalindrome(s)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ValidPalindromeTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ValidPalindromeTest { 8 | 9 | private final ValidPalindrome validPalindrome; 10 | 11 | ValidPalindromeTest() { 12 | validPalindrome = new ValidPalindrome(); 13 | } 14 | 15 | @Test 16 | void testValidPalindrome1() { 17 | String s = "racecar"; 18 | assertTrue(validPalindrome.validPalindrome(s)); 19 | } 20 | 21 | @Test 22 | void testValidPalindrome2() { 23 | String s = "raceacar"; 24 | assertFalse(validPalindrome.validPalindrome(s)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/easy/ValidParanthesesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ValidParanthesesTest { 8 | 9 | private final ValidParantheses validParantheses; 10 | 11 | ValidParanthesesTest() { 12 | validParantheses = new ValidParantheses(); 13 | } 14 | 15 | @Test 16 | void testIsValid1() { 17 | String s = "()[]{}"; 18 | assertTrue(validParantheses.isValid(s)); 19 | } 20 | 21 | @Test 22 | void testIsValid2() { 23 | String s = "(]"; 24 | assertFalse(validParantheses.isValid(s)); 25 | } 26 | 27 | @Test 28 | void testIsValid3() { 29 | String s = "}"; 30 | assertFalse(validParantheses.isValid(s)); 31 | } 32 | 33 | @Test 34 | void testIsValid4() { 35 | String s = "("; 36 | assertFalse(validParantheses.isValid(s)); 37 | } 38 | 39 | @Test 40 | void testIsValid5() { 41 | String s = "[{()[]}()]"; 42 | assertTrue(validParantheses.isValid(s)); 43 | } 44 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/hard/LongestValidParenthesesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.hard; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 11/5/19 12:32 AM 9 | */ 10 | 11 | class LongestValidParenthesesTest { 12 | 13 | private LongestValidParentheses longestValidParentheses = new LongestValidParentheses(); 14 | 15 | @Test 16 | void testLongestValidParentheses1() { 17 | String s = "(()"; 18 | assertEquals(2, longestValidParentheses.longestValidParentheses(s)); 19 | } 20 | 21 | @Test 22 | void testLongestValidParentheses2() { 23 | String s = ")()())"; 24 | assertEquals(4, longestValidParentheses.longestValidParentheses(s)); 25 | } 26 | 27 | @Test 28 | void testLongestValidParentheses3() { 29 | String s = ")()())((()())"; 30 | assertEquals(6, longestValidParentheses.longestValidParentheses(s)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/hard/TrappingRainWaterIITest.java: -------------------------------------------------------------------------------- 1 | package leetcode.hard; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 11/2/19 5:06 PM 9 | */ 10 | 11 | class TrappingRainWaterIITest { 12 | 13 | private TrappingRainWaterII trappingRainWaterII = new TrappingRainWaterII(); 14 | 15 | @Test 16 | void testTrapRainWater1() { 17 | int[][] heightMap = { 18 | {1, 4, 3, 1, 3, 2}, 19 | {3, 2, 1, 3, 2, 4}, 20 | {2, 3, 3, 2, 3, 1} 21 | }; 22 | 23 | assertEquals(4, trappingRainWaterII.trapRainWater(heightMap)); 24 | } 25 | 26 | @Test 27 | void testTrapRainWater2() { 28 | int[][] heightMap = {}; 29 | 30 | assertEquals(0, trappingRainWaterII.trapRainWater(heightMap)); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/AddTwoNumbersIITest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import util.ListNode; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import static org.junit.jupiter.api.Assertions.*; 7 | 8 | /** 9 | * Created by nikoo28 on 10/11/19 12:44 AM 10 | */ 11 | 12 | class AddTwoNumbersIITest { 13 | 14 | private AddTwoNumbersII addTwoNumbersII = new AddTwoNumbersII(); 15 | 16 | @Test 17 | void testAddTwoNumbers() { 18 | ListNode l1 = new ListNode(7); 19 | l1.next = new ListNode(2); 20 | l1.next.next = new ListNode(4); 21 | l1.next.next.next = new ListNode(3); 22 | 23 | ListNode l2 = new ListNode(5); 24 | l2.next = new ListNode(6); 25 | l2.next.next = new ListNode(4); 26 | 27 | ListNode result = addTwoNumbersII.addTwoNumbers(l1, l2); 28 | 29 | assertEquals(7, result.val); 30 | assertEquals(8, result.next.val); 31 | assertEquals(0, result.next.next.val); 32 | assertEquals(7, result.next.next.next.val); 33 | assertNull(result.next.next.next.next); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/CoinChangeTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class CoinChangeTest { 8 | 9 | private final CoinChange coinChange; 10 | 11 | CoinChangeTest() { 12 | coinChange = new CoinChange(); 13 | } 14 | 15 | @Test 16 | void testCoinChange1() { 17 | int[] coins = {1, 2, 5}; 18 | int amount = 11; 19 | 20 | assertEquals(3, coinChange.coinChange(coins, amount)); 21 | } 22 | 23 | @Test 24 | void testCoinChange2() { 25 | int[] coins = {2}; 26 | int amount = 3; 27 | 28 | assertEquals(-1, coinChange.coinChange(coins, amount)); 29 | } 30 | 31 | @Test 32 | void testCoinChange3() { 33 | int[] coins = {1}; 34 | int amount = 0; 35 | 36 | assertEquals(0, coinChange.coinChange(coins, amount)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/ContiguousArrayTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ContiguousArrayTest { 8 | 9 | private final ContiguousArray contiguousArray; 10 | 11 | ContiguousArrayTest() { 12 | contiguousArray = new ContiguousArray(); 13 | } 14 | 15 | @Test 16 | void testFindMaxLength1() { 17 | int[] nums = {0, 1, 0, 1, 0, 1}; 18 | assertEquals(6, contiguousArray.findMaxLength(nums)); 19 | } 20 | 21 | @Test 22 | void testFindMaxLength2() { 23 | int[] nums = {0}; 24 | assertEquals(0, contiguousArray.findMaxLength(nums)); 25 | } 26 | 27 | @Test 28 | void testFindMaxLength3() { 29 | int[] nums = {0, 1}; 30 | assertEquals(2, contiguousArray.findMaxLength(nums)); 31 | } 32 | 33 | @Test 34 | void testFindMaxLength4() { 35 | int[] nums = {0, 1, 1, 0, 1}; 36 | assertEquals(4, contiguousArray.findMaxLength(nums)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/DecodeWaysTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class DecodeWaysTest { 8 | 9 | private final DecodeWays decodeWays; 10 | 11 | DecodeWaysTest() { 12 | decodeWays = new DecodeWays(); 13 | } 14 | 15 | @Test 16 | void testNumDecodings1() { 17 | assertEquals(2, decodeWays.numDecodings("12")); 18 | } 19 | 20 | @Test 21 | void testNumDecodings2() { 22 | assertEquals(3, decodeWays.numDecodings("226")); 23 | } 24 | 25 | @Test 26 | void testNumDecodings3() { 27 | assertEquals(0, decodeWays.numDecodings("0")); 28 | } 29 | 30 | @Test 31 | void testNumDecodings4() { 32 | assertEquals(0, decodeWays.numDecodings("06")); 33 | } 34 | 35 | @Test 36 | void testNumDecodings5() { 37 | assertEquals(4, decodeWays.numDecodings("122016")); 38 | } 39 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/EditDistanceTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class EditDistanceTest { 8 | 9 | private final EditDistance editDistance; 10 | 11 | EditDistanceTest() { 12 | editDistance = new EditDistance(); 13 | } 14 | 15 | @Test 16 | void testMinDistance1() { 17 | String word1 = "horse"; 18 | String word2 = "ros"; 19 | assertEquals(3, editDistance.minDistance(word1, word2)); 20 | } 21 | 22 | @Test 23 | void testMinDistance2() { 24 | String word1 = "intention"; 25 | String word2 = "execution"; 26 | assertEquals(5, editDistance.minDistance(word1, word2)); 27 | } 28 | 29 | @Test 30 | void testMinDistance3() { 31 | String word1 = "abcdef"; 32 | String word2 = "azcde"; 33 | assertEquals(2, editDistance.minDistance(word1, word2)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/FruitIntoBasketsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class FruitIntoBasketsTest { 8 | 9 | private final FruitIntoBaskets fruitIntoBaskets; 10 | 11 | FruitIntoBasketsTest() { 12 | fruitIntoBaskets = new FruitIntoBaskets(); 13 | } 14 | 15 | @Test 16 | void testTotalFruit1() { 17 | int[] fruits = {0, 1, 1}; 18 | assertEquals(3, fruitIntoBaskets.totalFruit(fruits)); 19 | } 20 | 21 | @Test 22 | void testTotalFruit2() { 23 | int[] fruits = {0, 1, 2, 3}; 24 | assertEquals(2, fruitIntoBaskets.totalFruit(fruits)); 25 | } 26 | 27 | @Test 28 | void testTotalFruit3() { 29 | int[] fruits = {1, 2, 1, 1, 3, 4, 2, 2, 2, 2, 4}; 30 | assertEquals(6, fruitIntoBaskets.totalFruit(fruits)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/GenerateParanthesesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.List; 6 | 7 | import static org.junit.jupiter.api.Assertions.*; 8 | 9 | /** 10 | * Created by nikoo28 on 11/3/19 1:25 AM 11 | */ 12 | 13 | class GenerateParanthesesTest { 14 | 15 | private GenerateParantheses generateParantheses = new GenerateParantheses(); 16 | 17 | @Test 18 | void generateParenthesis() { 19 | 20 | String[] expected = { 21 | "((()))", 22 | "(()())", 23 | "(())()", 24 | "()(())", 25 | "()()()" 26 | }; 27 | 28 | List actual = generateParantheses.generateParenthesis(3); 29 | 30 | for (String s : expected) { 31 | assertTrue(actual.contains(s)); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/JumpGameIIITest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class JumpGameIIITest { 8 | 9 | private final JumpGameIII jumpGameIII; 10 | 11 | JumpGameIIITest() { 12 | jumpGameIII = new JumpGameIII(); 13 | } 14 | 15 | @Test 16 | void testCanReach1() { 17 | int[] arr = {4, 2, 3, 0, 3, 1, 2}; 18 | int start_index = 5; 19 | 20 | assertTrue(jumpGameIII.canReach(arr, start_index)); 21 | } 22 | 23 | @Test 24 | void testCanReach2() { 25 | int[] arr = {4, 2, 3, 0, 3, 1, 2}; 26 | int start_index = 0; 27 | 28 | assertTrue(jumpGameIII.canReach(arr, start_index)); 29 | } 30 | 31 | @Test 32 | void testCanReach3() { 33 | int[] arr = {3, 0, 2, 1, 2}; 34 | int start_index = 2; 35 | 36 | assertFalse(jumpGameIII.canReach(arr, start_index)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/JumpGameTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class JumpGameTest { 8 | 9 | private final JumpGame jumpGame; 10 | 11 | JumpGameTest() { 12 | jumpGame = new JumpGame(); 13 | } 14 | 15 | @Test 16 | void testCanJump1() { 17 | int[] nums = {2, 3, 1, 1, 4}; 18 | 19 | assertTrue(jumpGame.canJump(nums)); 20 | } 21 | 22 | @Test 23 | void testCanJump2() { 24 | int[] nums = {3, 2, 1, 0, 4}; 25 | 26 | assertFalse(jumpGame.canJump(nums)); 27 | } 28 | 29 | @Test 30 | void testCanJump3() { 31 | int[] nums = {2}; 32 | 33 | assertTrue(jumpGame.canJump(nums)); 34 | } 35 | 36 | @Test 37 | void testCanJump4() { 38 | int[] nums = {0}; 39 | 40 | assertTrue(jumpGame.canJump(nums)); 41 | } 42 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/LRUCacheTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 11/2/19 2:33 PM 9 | */ 10 | 11 | class LRUCacheTest { 12 | 13 | @Test 14 | void testLRUCache1() { 15 | 16 | LRUCache cache = new LRUCache(2 /* capacity */); 17 | 18 | cache.put(1, 1); 19 | cache.put(2, 2); 20 | assertEquals(1, cache.get(1)); // returns 1 21 | cache.put(3, 3); // evicts key 2 22 | assertEquals(-1, cache.get(2)); // returns -1 (not found) 23 | cache.put(4, 4); // evicts key 1 24 | assertEquals(-1, cache.get(1)); // returns -1 (not found) 25 | assertEquals(3, cache.get(3)); // returns 3 26 | assertEquals(4, cache.get(4)); // returns 4 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/LongestPalindromicSubstringTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 11/2/19 10:16 PM 9 | */ 10 | 11 | class LongestPalindromicSubstringTest { 12 | 13 | private LongestPalindromicSubstring longestPalindromicSubstring = new LongestPalindromicSubstring(); 14 | 15 | @Test 16 | void longestPalindrome1() { 17 | String s = "babad"; 18 | 19 | String actual = longestPalindromicSubstring.longestPalindrome(s); 20 | 21 | assertTrue(actual.equals("bab") || actual.equals("aba")); 22 | } 23 | 24 | @Test 25 | void longestPalindrome2() { 26 | String s = "cbbd"; 27 | 28 | String actual = longestPalindromicSubstring.longestPalindrome(s); 29 | 30 | assertEquals("bb", actual); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/MaximumLengthOfRepeatedSubarrayTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class MaximumLengthOfRepeatedSubarrayTest { 8 | 9 | private final MaximumLengthOfRepeatedSubarray maximumLengthOfRepeatedSubarray; 10 | 11 | MaximumLengthOfRepeatedSubarrayTest() { 12 | maximumLengthOfRepeatedSubarray = new MaximumLengthOfRepeatedSubarray(); 13 | } 14 | 15 | @Test 16 | void testFindLength1() { 17 | int[] nums1 = {1, 2, 3, 2, 1}; 18 | int[] nums2 = {3, 2, 1, 4, 7}; 19 | 20 | assertEquals(3, maximumLengthOfRepeatedSubarray.findLength(nums1, nums2)); 21 | } 22 | 23 | @Test 24 | void testFindLength2() { 25 | int[] nums1 = {0, 0, 0, 0, 0}; 26 | int[] nums2 = {0, 0, 0, 0}; 27 | 28 | assertEquals(4, maximumLengthOfRepeatedSubarray.findLength(nums1, nums2)); 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/MaximumVowelsInASubstringTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class MaximumVowelsInASubstringTest { 8 | 9 | private final MaximumVowelsInASubstring maximumVowelsInASubstring; 10 | 11 | MaximumVowelsInASubstringTest() { 12 | maximumVowelsInASubstring = new MaximumVowelsInASubstring(); 13 | } 14 | 15 | @Test 16 | void testMaxVowels1() { 17 | String s = "abciiidef"; 18 | int k = 3; 19 | 20 | assertEquals(3, maximumVowelsInASubstring.maxVowels(s, k)); 21 | } 22 | 23 | @Test 24 | void testMaxVowels2() { 25 | String s = "aeiou"; 26 | int k = 2; 27 | 28 | assertEquals(2, maximumVowelsInASubstring.maxVowels(s, k)); 29 | } 30 | 31 | @Test 32 | void testMaxVowels3() { 33 | String s = "leetcode"; 34 | int k = 3; 35 | 36 | assertEquals(2, maximumVowelsInASubstring.maxVowels(s, k)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/MinStackTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class MinStackTest { 8 | 9 | @Test 10 | void testMinStack1() { 11 | MinStack minStack = new MinStack(); 12 | minStack.push(-2); 13 | minStack.push(0); 14 | minStack.push(-3); 15 | assertEquals(-3, minStack.getMin()); 16 | minStack.pop(); 17 | assertEquals(0, minStack.top()); 18 | assertEquals(-2, minStack.getMin()); 19 | } 20 | 21 | @Test 22 | void testMinStack2() { 23 | MinStack minStack = new MinStack(); 24 | minStack.push(-1); 25 | minStack.push(-2); 26 | minStack.push(-3); 27 | minStack.push(0); 28 | minStack.push(2); 29 | assertEquals(-3, minStack.getMin()); 30 | assertEquals(2, minStack.top()); 31 | minStack.pop(); 32 | assertEquals(0, minStack.top()); 33 | assertEquals(-3, minStack.getMin()); 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/MinimumDominoRotationsForEqualRowTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class MinimumDominoRotationsForEqualRowTest { 8 | 9 | private MinimumDominoRotationsForEqualRow minimumDominoRotationsForEqualRow = new MinimumDominoRotationsForEqualRow(); 10 | 11 | @Test 12 | void testMinDominoRotations1() { 13 | int[] A = {2, 1, 2, 4, 2, 2}; 14 | int[] B = {5, 2, 6, 2, 3, 2}; 15 | 16 | assertEquals(2, minimumDominoRotationsForEqualRow.minDominoRotations(A, B)); 17 | } 18 | 19 | @Test 20 | void testMinDominoRotations2() { 21 | int[] A = {3, 5, 1, 2, 3}; 22 | int[] B = {3, 6, 3, 3, 4}; 23 | 24 | assertEquals(-1, minimumDominoRotationsForEqualRow.minDominoRotations(A, B)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/NonOverlappingIntervalsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class NonOverlappingIntervalsTest { 8 | 9 | private final NonOverlappingIntervals nonOverlappingIntervals; 10 | 11 | NonOverlappingIntervalsTest() { 12 | nonOverlappingIntervals = new NonOverlappingIntervals(); 13 | } 14 | 15 | @Test 16 | void testEraseOverlapIntervals1() { 17 | assertEquals(1, nonOverlappingIntervals.eraseOverlapIntervals(new int[][]{{1, 2}, {2, 3}, {3, 4}, {1, 3}})); 18 | } 19 | 20 | @Test 21 | void testEraseOverlapIntervals2() { 22 | assertEquals(2, nonOverlappingIntervals.eraseOverlapIntervals(new int[][]{{1, 2}, {1, 2}, {1, 2}})); 23 | } 24 | 25 | @Test 26 | void testEraseOverlapIntervals3() { 27 | assertEquals(0, nonOverlappingIntervals.eraseOverlapIntervals(new int[][]{{1, 2}, {2, 3}})); 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/RottingOrangesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class RottingOrangesTest { 8 | 9 | private final RottingOranges rottingOranges; 10 | 11 | RottingOrangesTest() { 12 | rottingOranges = new RottingOranges(); 13 | } 14 | 15 | @Test 16 | void testOrangesRotting1() { 17 | int[][] grid = { 18 | {2, 1, 1}, 19 | {1, 1, 0}, 20 | {0, 1, 1} 21 | }; 22 | 23 | assertEquals(4, rottingOranges.orangesRotting(grid)); 24 | } 25 | 26 | @Test 27 | void testOrangesRotting2() { 28 | int[][] grid = { 29 | {2, 1, 1}, 30 | {0, 1, 1}, 31 | {1, 0, 1} 32 | }; 33 | 34 | assertEquals(-1, rottingOranges.orangesRotting(grid)); 35 | } 36 | 37 | @Test 38 | void testOrangesRotting3() { 39 | int[][] grid = { 40 | {0, 2} 41 | }; 42 | 43 | assertEquals(0, rottingOranges.orangesRotting(grid)); 44 | } 45 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/SearchA2DMatrixTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class SearchA2DMatrixTest { 8 | 9 | private final SearchA2DMatrix searchA2DMatrix; 10 | 11 | SearchA2DMatrixTest() { 12 | searchA2DMatrix = new SearchA2DMatrix(); 13 | } 14 | 15 | @Test 16 | void testSearchMatrix1() { 17 | int[][] matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}; 18 | assertTrue(searchA2DMatrix.searchMatrix(matrix, 3)); 19 | assertFalse(searchA2DMatrix.searchMatrix(matrix, 13)); 20 | } 21 | 22 | @Test 23 | void testSearchMatrix2() { 24 | int[][] matrix = {{1}, {10}, {60}}; 25 | assertFalse(searchA2DMatrix.searchMatrix(matrix, 0)); 26 | assertTrue(searchA2DMatrix.searchMatrix(matrix, 10)); 27 | assertFalse(searchA2DMatrix.searchMatrix(matrix, 65)); 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/SetMatrixZeroesTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Arrays; 6 | 7 | import static org.junit.jupiter.api.Assertions.*; 8 | 9 | class SetMatrixZeroesTest { 10 | 11 | private final SetMatrixZeroes setMatrixZeroes; 12 | 13 | SetMatrixZeroesTest() { 14 | setMatrixZeroes = new SetMatrixZeroes(); 15 | } 16 | 17 | @Test 18 | void testSetZeroes1() { 19 | int[][] matrix = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; 20 | int[][] expected = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}; 21 | 22 | setMatrixZeroes.setZeroes(matrix); 23 | assertTrue(Arrays.deepEquals(expected, matrix)); 24 | } 25 | 26 | @Test 27 | void testSetZeroes2() { 28 | int[][] matrix = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}}; 29 | int[][] expected = {{0, 0, 0, 0}, {0, 4, 5, 0}, {0, 3, 1, 0}}; 30 | 31 | setMatrixZeroes.setZeroes(matrix); 32 | assertTrue(Arrays.deepEquals(expected, matrix)); 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/SortColorsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class SortColorsTest { 8 | 9 | private final SortColors sortColors; 10 | 11 | SortColorsTest() { 12 | sortColors = new SortColors(); 13 | } 14 | 15 | @Test 16 | void testSortColors1() { 17 | int[] arr = {2, 0, 2, 1, 1, 0}; 18 | int[] expected = {0, 0, 1, 1, 2, 2}; 19 | 20 | sortColors.sortColors(arr); 21 | assertArrayEquals(expected, arr); 22 | } 23 | 24 | @Test 25 | void testSortColors2() { 26 | int[] arr = {2, 0, 2}; 27 | int[] expected = {0, 2, 2}; 28 | 29 | sortColors.sortColors(arr); 30 | assertArrayEquals(expected, arr); 31 | } 32 | 33 | @Test 34 | void testSortColors3() { 35 | int[] arr = {0}; 36 | int[] expected = {0}; 37 | 38 | sortColors.sortColors(arr); 39 | assertArrayEquals(expected, arr); 40 | } 41 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/TimeMapTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class TimeMapTest { 8 | 9 | private final TimeMap timeMap; 10 | 11 | TimeMapTest() { 12 | timeMap = new TimeMap(); 13 | } 14 | 15 | @Test 16 | void testSetAndGet1() { 17 | timeMap.set("foo", "bar", 1); 18 | assertEquals("bar", timeMap.get("foo", 1)); 19 | assertEquals("bar", timeMap.get("foo", 3)); 20 | } 21 | 22 | @Test 23 | void testSetAndGet2() { 24 | timeMap.set("foo", "bar", 1); 25 | timeMap.set("foo", "baz", 2); 26 | assertEquals("bar", timeMap.get("foo", 1)); 27 | assertEquals("baz", timeMap.get("foo", 2)); 28 | assertEquals("baz", timeMap.get("foo", 3)); 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/UniquePathsTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class UniquePathsTest { 8 | 9 | private final UniquePaths uniquePaths; 10 | 11 | UniquePathsTest() { 12 | uniquePaths = new UniquePaths(); 13 | } 14 | 15 | @Test 16 | void testUniquePaths1() { 17 | assertEquals(3, uniquePaths.uniquePaths(3, 2)); 18 | } 19 | 20 | @Test 21 | void testUniquePaths2() { 22 | assertEquals(28, uniquePaths.uniquePaths(7, 3)); 23 | } 24 | 25 | @Test 26 | void testUniquePaths3() { 27 | assertEquals(6, uniquePaths.uniquePaths(3, 3)); 28 | } 29 | 30 | @Test 31 | void testUniquePaths4() { 32 | assertEquals(28, uniquePaths.uniquePaths(3, 7)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/leetcode/medium/UpdateMatrixTest.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class UpdateMatrixTest { 8 | 9 | private final UpdateMatrix updateMatrix; 10 | 11 | UpdateMatrixTest() { 12 | updateMatrix = new UpdateMatrix(); 13 | } 14 | 15 | @Test 16 | void testUpdateMatrix1() { 17 | int[][] mat = { 18 | {0, 0, 0}, 19 | {0, 1, 0}, 20 | {1, 1, 1} 21 | }; 22 | int[][] expected = { 23 | {0, 0, 0}, 24 | {0, 1, 0}, 25 | {1, 2, 1} 26 | }; 27 | assertArrayEquals(expected, updateMatrix.updateMatrix(mat)); 28 | } 29 | 30 | @Test 31 | void testUpdateMatrix2() { 32 | int[][] mat = { 33 | {0, 0, 0}, 34 | {0, 1, 0}, 35 | {1, 1, 1} 36 | }; 37 | int[][] expected = { 38 | {0, 0, 0}, 39 | {0, 1, 0}, 40 | {1, 2, 1} 41 | }; 42 | assertArrayEquals(expected, updateMatrix.updateMatrix(mat)); 43 | } 44 | } -------------------------------------------------------------------------------- /src/test/java/util/CountingSortTest.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 12/26/20 8:54 PM 9 | */ 10 | 11 | class CountingSortTest { 12 | 13 | @Test 14 | void testCountingSort1() { 15 | int[] arr = {7, 3, 9, 5, 4, 8, 0, 1}; 16 | int[] sortedArray = {0, 1, 3, 4, 5, 7, 8, 9}; 17 | 18 | CountingSort.countingSort(arr); 19 | assertArrayEquals(sortedArray, arr); 20 | } 21 | 22 | @Test 23 | void testCountingSort2() { 24 | int[] arr = {7, 3, 9, 5, 4, 8, 0, 1, -1, -2, -6, -7, -3, -5, -99, -101, 98, 34, 12, 56, 13, 63}; 25 | int[] sortedArray = {-101, -99, -7, -6, -5, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 12, 13, 34, 56, 63, 98}; 26 | 27 | CountingSort.countingSort(arr); 28 | assertArrayEquals(sortedArray, arr); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/test/java/util/MergeSortTest.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/4/20 7:47 PM 9 | */ 10 | 11 | class MergeSortTest { 12 | 13 | @Test 14 | void testMergeSort1() { 15 | int[] arr = {7, 3, 9, 5, 4, 8, 0, 1}; 16 | int[] sortedArray = {0, 1, 3, 4, 5, 7, 8, 9}; 17 | 18 | MergeSort.mergeSort(arr, 8); 19 | assertArrayEquals(sortedArray, arr); 20 | } 21 | 22 | @Test 23 | void testMergeSort2() { 24 | int[] arr = {7, 3, 9, 5, 4, 8, 0, 1, -1, -2, -6, -7, -3, -5, -99, -100, 9999, 34, 12, 5653, 1213, 6563}; 25 | int[] sortedArray = {-100, -99, -7, -6, -5, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 12, 34, 1213, 5653, 6563, 9999}; 26 | 27 | MergeSort.mergeSort(arr, 22); 28 | assertArrayEquals(sortedArray, arr); 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/java/util/QuickSortTest.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | /** 8 | * Created by nikoo28 on 10/11/20 5:02 PM 9 | */ 10 | 11 | class QuickSortTest { 12 | 13 | @Test 14 | void testQuickSort1() { 15 | int[] arr = {7, 3, 9, 5, 4, 8, 0, 1}; 16 | int[] sortedArray = {0, 1, 3, 4, 5, 7, 8, 9}; 17 | 18 | QuickSort.quickSort(arr, 0, arr.length - 1); 19 | assertArrayEquals(sortedArray, arr); 20 | } 21 | 22 | @Test 23 | void testQuickSort2() { 24 | int[] arr = {7, 3, 9, 5, 4, 8, 0, 1, -1, -2, -6, -7, -3, -5, -99, -100, 9999, 34, 12, 5653, 1213, 6563}; 25 | int[] sortedArray = {-100, -99, -7, -6, -5, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 12, 34, 1213, 5653, 6563, 9999}; 26 | 27 | QuickSort.quickSort(arr, 0, arr.length - 1); 28 | assertArrayEquals(sortedArray, arr); 29 | } 30 | } --------------------------------------------------------------------------------