├── .checkstyle ├── .gitignore ├── .travis.yml ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main └── java ├── array ├── CheckValidPassword.java ├── ConvertStringSToT.java ├── CountTripletsWithSmallerSum.java ├── FileUtil.java ├── FindTelephoneBill.java ├── MaxMinSort.java ├── MaxPositiveProduct.java ├── MergeKSortedArrays.java ├── ReversePositiveNumbers.java ├── StreamAverage.java ├── UriTesting.java └── ZeroOutMatrix.java ├── backtracking ├── CryptarithmeticPuzzle.java ├── HamiltonianCycle.java ├── KnightsTour.java ├── MColoringProblem.java ├── NQueenProblem.java ├── RatInMaze.java ├── SubsetSum.java ├── Sudoku.java └── TugOfWar.java ├── bit ├── AddWithoutArithmeticOp.java ├── BitManipulation.java ├── BitVector.java ├── FractionalRepresentation.java ├── MaxNumberWithoutComparison.java └── NextMinMax.java ├── book └── mcdowell │ ├── AllCombinationOfLength.java │ ├── AllCombinations.java │ ├── DeConcantenateWordUsingDictionary.java │ ├── GameOfMasterMind.java │ ├── IntegerWordConversion.java │ ├── MaximumSumCircularArray.java │ ├── MedianOfIntStream.java │ ├── MinDisBtwTwoNum.java │ ├── MinSwapsForPairArrangment.java │ ├── ThreeArrayCommonElement.java │ └── ZigZagMatrix.java ├── dp ├── BinomialCoefficient.java ├── BoxStackingProblem.java ├── CoinChange.java ├── CuttingRod.java ├── EditDistance.java ├── EggDroppingPuzzle.java ├── EvaluateExpressionToTrue.java ├── FloydWarshall.java ├── Knapsack.java ├── LongestBitonicSequence.java ├── LongestCommonSubsequence.java ├── LongestIncreasingSubsequence.java ├── LongestPalindromicSubsequence.java ├── MaximumSumIncreasingSubsequence.java ├── MinCostPath.java ├── OptimalBinarySearchTree.java ├── PrintMaximumAWithFourKeys.java ├── TrappingRainWater.java ├── WildCardPatternMatching.java └── WordWrapProblem.java ├── ds ├── BinarySearchTree.java ├── BinaryTree.java ├── BloomFilter.java ├── DogCatQueue.java ├── DoubleHash.java ├── Edge.java ├── GetRankBST.java ├── Graph.java ├── GraphAdjList.java ├── GraphComplex.java ├── Hash.java ├── HashMap.java ├── MaxHeap.java ├── MinHeap.java ├── NaryTree.java ├── Node.java ├── SearchPatternTrie.java ├── State.java ├── Union.java └── java │ ├── QueueApp.java │ └── StackApp.java ├── graph ├── BreadthFirstSearch.java ├── DepthFirstSearch.java ├── DetectCycleInDirectedGraph.java ├── DetectCycleInUndirectedGraph.java ├── DetectCycleInUndirectedGraphUsingUnion.java ├── DijkstraShortestPath.java ├── IsUndirectedGraphATree.java ├── IsUndirectedGraphConnected.java ├── KCenterProblem.java ├── KruskalMinimumSpanningTree.java ├── LongestPathInDirectedAcyclicGraph.java ├── PrimsMinimumSpanningTree.java └── TopologicalSorting.java ├── greedy ├── ActivitySelection.java ├── JobSequencingProblem.java └── MinimumNumberOfCoins.java ├── hackerrank ├── AppendAndDelete.java ├── BetweenTwoSets.java ├── DistinctSubPalindrome.java ├── HalloweenParty.java ├── IsPossible.java └── LoveLetterMystery.java ├── interview ├── amazon │ ├── AlphabetSeries.java │ ├── FindHeavyCoin.java │ ├── InviteGuests.java │ ├── ModifiedRegex.java │ ├── OddTimesNumber.java │ ├── PathToFormTargetNumber.java │ ├── TargetSumSubarray.java │ └── WordExists.java ├── facebook │ └── MaximumOverlappingIntervals.java ├── goldman_sachs │ └── SumPairs.java ├── google │ ├── AddOneToNumber.java │ ├── Array3Pointers.java │ ├── ArraySerializerDeserializer.java │ ├── BigNumAddUsingArray.java │ ├── BiggestNumber.java │ ├── BurstBaloons.java │ ├── ContainerWithMostWater.java │ ├── CountPatternsInAndroidLockScreen.java │ ├── DiffCharArrMaxLenProduct.java │ ├── ExpressiveWords.java │ ├── FibonacciNumberLessThanN.java │ ├── FindNumRepeatsMoreThanInSortedArr.java │ ├── FruitIntoBaskets.java │ ├── GCD.java │ ├── GridUniquePaths.java │ ├── HighestValueByConcantenation.java │ ├── IntersectionOfSortedArrays.java │ ├── IsValidJson.java │ ├── JumpGame.java │ ├── KthRowOfPascalsTriangle.java │ ├── LicenseKeyFormatting.java │ ├── LongestSubstringWithAtMostTwoDistinctCharacters.java │ ├── LongestSubstringWithoutRepeatingCharacters.java │ ├── MaxDistance.java │ ├── MedianOfArray.java │ ├── MergeOverlappingIntervals.java │ ├── MinimumWindowSubstring.java │ ├── MissingRanges.java │ ├── NthSmallestMulFromSet.java │ ├── PlusOne.java │ ├── RemoveDuplicatesFromSortedArray.java │ ├── ShortestContainingSubtring.java │ ├── ShortestSubstringContainingPatternChar.java │ ├── ThreeSumZero.java │ ├── TrappingRainWater.java │ ├── UniqueEmailAddress.java │ ├── ValidParentheses.java │ └── WaveArray.java ├── microsoft │ ├── CircularBuffer.java │ ├── IntegerAverage.java │ ├── KnightsTour.java │ ├── LinkedAreasCount.java │ ├── MaxTimeToRotAllOranges.java │ └── ReverseDoublyLinkList.java ├── twitter │ ├── InfoMasking.java │ └── Kraken.java └── visa │ ├── BigFilePatternMatching.java │ └── data.txt ├── leetcode ├── ListNode.java ├── competition │ ├── LicenseKeyFormatting.java │ ├── MagicalString.java │ ├── NumberComplement.java │ └── SlidingWindowMedian.java ├── easy │ ├── E108_ConvertSortedArrayToBinarySearchTree.java │ ├── E144_BinaryTreePreorderTraversal.java │ ├── E14_LongestCommonPrefix.java │ ├── E1_TwoSum.java │ ├── E20_ValidParenthesis.java │ ├── E21_MergeSortedLinkedList.java │ ├── E268_MissingNumber.java │ ├── E26_RemoveDuplicatesFromSortedArray.java │ ├── E27_RemoveElement.java │ ├── E28_ImplementStr.java │ ├── E338_CountingBits.java │ ├── E35_SearchInsertPosition.java │ ├── E367_ValidPerfectSquare.java │ ├── E392_IsSubsequence.java │ ├── E64_BinaryTreeInorderTraversal.java │ ├── E69_Sqrt.java │ ├── E70_ClimbingStairs.java │ └── E9_PalindromeNumber.java ├── hard │ ├── H10_RegularExpressionMatching.java │ ├── H126_WordLadderII.java │ ├── H149_MaxPointsOnALine.java │ ├── H218_SkylineProblem.java │ ├── H312_BurstBalloon.java │ ├── H327_CountOfRangeSum.java │ ├── H329_LongestIncreasingPathInAMatrix.java │ ├── H330_PatchingArray.java │ ├── H352_SummaryRanges.java │ ├── H41_FirstMissingPositive.java │ ├── H42_TrappingRainWater.java │ ├── H4_SortedArrayMedian.java │ ├── H51_NQueens.java │ ├── H52_NQueensII.java │ ├── H60_PermutationSequence.java │ └── H84_LargestRectangleInHistogram.java └── medium │ ├── M114_FlattenBinaryTreeToLinkedList.java │ ├── M116_PopulatingNextRightPointersInEachNode.java │ ├── M117_PopulatingNextRightPointersInEachNodeII.java │ ├── M11_ContainerWithMostWater.java │ ├── M122_BestTimeToBuyAndSellStockII.java │ ├── M128_LongestConsecutiveSequence.java │ ├── M129_SumRootToLeafNumbers.java │ ├── M130_SurroundedRegions.java │ ├── M137_SingleNumberII.java │ ├── M146_LRUCache.java │ ├── M152_MaximumProductSubarray.java │ ├── M153_FindMinimumInRotatedSortedArray.java │ ├── M15_ThreeSum.java │ ├── M162_FindPeakElement.java │ ├── M167_TwoSumIIInputArraySorted.java │ ├── M16_ThreeSumClosest.java │ ├── M17_LetterCombinationOfPhoneNumber.java │ ├── M18_FourSum.java │ ├── M19_RemoveNthNodeFromEndOfLinkedList.java │ ├── M200_NumberOfIslands.java │ ├── M201_BitwiseAndOfNumbersRange.java │ ├── M2096_StepByStepBinaryTreeTraversal.java │ ├── M215_KthLargestElementInAnArray.java │ ├── M216_CombinationSumIII.java │ ├── M22_GenerateParentheses.java │ ├── M230_KthSmallestElementInABST.java │ ├── M238_ProductOfArrayExceptSelf.java │ ├── M240_SearchA2DMatrixII.java │ ├── M241_DifferentWaysToAddParentheses.java │ ├── M24_SwapNodesInPairs.java │ ├── M260_SingleNumberIII.java │ ├── M264_UglyNumberII.java │ ├── M274_HIndex.java │ ├── M275_HIndexII.java │ ├── M279_PerfectSquares.java │ ├── M287_FindTheDuplicateNumber.java │ ├── M289_GameOfLife.java │ ├── M29_DivideTwoIntegers.java │ ├── M2_AddTwoNumbers.java │ ├── M300_LongestIncreasingSubsequence.java │ ├── M309_BestTimeToBuyAndSellStockWithCooldown.java │ ├── M313_SuperUglyNumber.java │ ├── M318_MaximumProductOfWordLengths.java │ ├── M319_BulbSwitcher.java │ ├── M31_NextPermutation.java │ ├── M322_CoinChange.java │ ├── M328_OddEvenLinkedList.java │ ├── M331_VerifyPreorderSerializationOfABinaryTree.java │ ├── M334_IncreasingTripletSubsequence.java │ ├── M337_HouseRobberIII.java │ ├── M33_SearchInRotatedSortedArray.java │ ├── M343_IntegerBreak.java │ ├── M347_TopKFrequentElements.java │ ├── M34_SearchForARange.java │ ├── M357_CountNumbersWithUniqueDigits.java │ ├── M368_LargestDivisibleSubset.java │ ├── M375_GuessNumberHigherOrLowerII.java │ ├── M376_WiggleSubsequence.java │ ├── M377_CombinationSumIV.java │ ├── M378_KthSmallestElementInASortedMatrix.java │ ├── M382_LinkedListRandomNode.java │ ├── M384_ShuffleAnArray.java │ ├── M388_LongestAbsoluteFilePath.java │ ├── M390_EliminationGame.java │ ├── M393_UTF8Validation.java │ ├── M394_DecodeString.java │ ├── M395_LongestSubstringWithAtLeastKRepeatingCharacters.java │ ├── M399_EvaluateDivision.java │ ├── M39_CombinationSum.java │ ├── M3_LongestSubstringWithoutRepeatingCharacters.java │ ├── M406_QueueReconstructionByHeight.java │ ├── M40_CombinationSumII.java │ ├── M413_ArithmeticSlices.java │ ├── M416_PartitionEqualSubsetSum.java │ ├── M419_BattleshipsInABoard.java │ ├── M421_MaximumXOROfTwoNumbersInAnArray.java │ ├── M423_ReconstructOriginalDigitsFromEnglish.java │ ├── M424_LongestRepeatingCharacterReplacement.java │ ├── M435_NonOverlappingIntervals.java │ ├── M436_FindRightInterval.java │ ├── M450_DeleteNodeInABST.java │ ├── M452_MinimumNumberOfArrowsToBurstBalloons.java │ ├── M454_FourSumII.java │ ├── M45_JumpGameII.java │ ├── M46_Permutations.java │ ├── M474_OnesAndZeroes.java │ ├── M47_PermutationsII.java │ ├── M48_RotateImage.java │ ├── M49_GroupAnagrams.java │ ├── M50_Pow.java │ ├── M53_MaximumSubarray.java │ ├── M54_SpiralMatrix.java │ ├── M55_JumpGame.java │ ├── M59_SpiralMatrixII.java │ ├── M5_LongestPalindromicSubstring.java │ ├── M61_RotateList.java │ ├── M62_UniquePaths.java │ ├── M63_UniquePathsII.java │ ├── M64_MinPathSum.java │ ├── M6_ZigZagConversion.java │ ├── M71_SimplifyPath.java │ ├── M72_EditDistance.java │ ├── M73_SetMatrixZeroes.java │ ├── M74_SearchA2DMatrix.java │ ├── M75_SortColors.java │ ├── M77_Combinations.java │ ├── M78_Subsets.java │ ├── M7_ReverseInteger.java │ ├── M80_RemoveDuplicatesFromSortedArrayII.java │ ├── M81_SearchInRotatedSortedArrayII.java │ ├── M89_GrayCode.java │ ├── M8_StringToInteger.java │ ├── M90_SubsetsII.java │ └── M96_UniqueBinarySearchTrees.java ├── math ├── BabylonianForSquareRoot.java ├── BinomialCoefficient.java ├── BirthdayParadox.java ├── CalculateClockAngle.java ├── CalculateEToPowerX.java ├── CatalanNumbers.java ├── ContSubseqAddiTo9Count.java ├── ContiguousArrayLargestSum.java ├── ConvertToBase8.java ├── CountDecodingsOfDigitSeq.java ├── CountNoOfTwos.java ├── CountNonConsOneBinaryString.java ├── DFABasedDivision.java ├── DiceRollHistogram.java ├── DivisibleBy7.java ├── DrawCircle.java ├── FactorialMaximumTrailingZero.java ├── FancyNumber.java ├── FindDayOfWeek.java ├── FindDerrangements.java ├── FindExcelColumn.java ├── FindNextSmallestPalindrome.java ├── FindSmallestNumThatMultipliesToN.java ├── FirstKDigitsOfReciprocalOfN.java ├── FrequencyDistRandGenerator.java ├── GaussianDistribution.java ├── GenerateAllNumbers.java ├── GeneratePrimeNumbers.java ├── GetBussinessDate.java ├── GroupOfMultipleOf3.java ├── HornersPolynomialEvaluation.java ├── ImplementOperations.java ├── IsFibonacciNumber.java ├── LargestMultipleOf2_5_3.java ├── LargestMultipleOf3.java ├── LexicographicalRankOfString.java ├── LongestIncreasingSubsequence.java ├── LuckyNumbers.java ├── MagicSquare.java ├── MakeFairCoinFromUnfairCoin.java ├── MaximizeStockProfit.java ├── MultipleOf3.java ├── MultiplyBy7.java ├── MultiplyPolynomials.java ├── NextBigNumber.java ├── NonNegativeIntegerPair.java ├── PalindromeNumber.java ├── PascalsTriangle.java ├── PolynomialEvaluation.java ├── PolynomialsAddition.java ├── PowerOperation.java ├── PrintAllNumberCombination.java ├── PrintAllPrimeFactors.java ├── PrintCombinationOfRElements.java ├── PrintNumbersInLexographicalOrder.java ├── ProductRepresentationCombination.java ├── Rand7FromRand5.java ├── RandGeneratorThreeNumGivenProb.java ├── RankSelection.java ├── ReachNthStair.java ├── Replace0With5.java ├── ReservoirSamplingOptimized.java ├── RussianPeasantMultiplication.java ├── ShuffleCardDeck.java ├── SieveOfEratosthenes.java ├── SmallestTwin.java ├── StreamAverage.java ├── SumOfBitDiffInAllPairs.java ├── TowerOfHanoi.java ├── TrailingZeroesInFactorial.java └── TwoVesselInfiniteWater.java ├── pramp ├── Interview10.java ├── Interview11.java ├── Interview3.java ├── Interview4.java ├── Interview5.java ├── Interview6.java ├── Interview7.java ├── Interview8.java └── Interview9.java ├── puzzles └── CircularSwordKilling.java ├── recursion ├── ActivitySelection.java ├── BiNodeBSTToDLL.java ├── Boggle.java ├── BurstBalloon.java ├── ChessPrintValidComb.java ├── CountDecoding.java ├── EggDroppingPuzzle.java ├── ExpressionTree.java ├── FindCurrencyRepresentation.java ├── FlipZeroesForMaxConsOnes.java ├── KnapSnackProblem.java ├── LongestPalindromicSubsequence.java ├── LowestCommonAncestor.java ├── MaximumPathSumBinaryTree.java ├── MinimumEditDistance.java ├── NonIncreasingSequence.java ├── NumberToAlphabetDecoding.java ├── ParenthesisCombForExpression.java ├── PossibleParenthesisCombination.java ├── PrintAllPossiblePathsInMatrix.java ├── PrintAllSubset.java ├── PrintTreeBoundaries.java ├── RobotGridWaysToDestination.java ├── SelectionRank.java ├── SelectionRankLinearTime.java ├── StringCombinations.java ├── StringUnconcatenation.java ├── TransformString.java ├── UniqueSubsets.java └── WildPatternMatching.java ├── sorting ├── AlmostSortedArrSearch.java ├── BinaryInsertionSort.java ├── BinarySearch.java ├── BucketSort.java ├── FindKClosestElement.java ├── GivenSumTwoElements.java ├── IndicesToSortCompleteArray.java ├── InterpolationSearch.java ├── LargestSequenceTwoAttributes.java ├── LeastDifferencePair.java ├── MedianOfTwoSortedArr.java ├── NearlyKSortedArrSorting.java ├── QuickSort.java ├── RadixSort.java ├── SortedBinaryArray.java ├── StrictlyIncreasingMatrix.java └── WaveSorting.java └── string ├── GoatConversion.java ├── LexicographicalRankOfStringPermutation.java ├── LongestCommonSubstring.java ├── LongestPalindromicSubstring.java ├── LongestRepeatedSubstring.java ├── PrintAllPalindromicSubstrings.java ├── Search2DArray.java ├── SearchAnagramSubstring.java ├── SearchPatternBoyerMoore.java ├── SearchPatternKMP.java ├── SearchPatternNaive.java ├── SearchPatternNaiveOptimized.java ├── SearchPatternRabinKarp.java ├── SearchPatternSuffixArray.java ├── SearchPatternUsingTrie.java ├── StringPermutationsWithDuplicateCharacters.java ├── StringPermutationsWithoutDuplicateCharacters.java ├── SubStringPalindrome.java └── ZigZagArray.java /.checkstyle: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | .classpath 3 | .project 4 | .idea/ 5 | .settings* 6 | /.gradle/ 7 | /build/ -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | sudo: required 5 | before_script: 6 | - chmod +x gradlew 7 | before_install: 8 | - chmod +x gradlew 9 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'eclipse' 3 | 4 | repositories { 5 | jcenter() 6 | mavenCentral() 7 | } 8 | 9 | sourceSets { 10 | main { 11 | java { 12 | srcDirs = ['src/main/java'] 13 | } 14 | } 15 | } 16 | 17 | compileJava { 18 | options.encoding = "UTF-8" 19 | } 20 | 21 | dependencies { 22 | implementation 'org.slf4j:slf4j-api:1.7.21' 23 | implementation 'junit:junit:4.12' 24 | testImplementation 'junit:junit:4.12' 25 | } 26 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shivam-maharshi/algorithms/dde09df344010cfcf4c2dc126844a9dfce63ba78/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was auto generated by the Gradle buildInit task 3 | * by 'shivam.maharshi' at '12/21/16 1:58 PM' with Gradle 2.14.1 4 | * 5 | * The settings file is used to specify which projects to include in your build. 6 | * In a single project build this file can be empty or even removed. 7 | * 8 | * Detailed information about configuring a multi-project build in Gradle can be found 9 | * in the user guide at https://docs.gradle.org/2.14.1/userguide/multi_project_builds.html 10 | */ 11 | 12 | /* 13 | // To declare projects as part of a multi-project build use the 'include' method 14 | include 'shared' 15 | include 'api' 16 | include 'services:webservice' 17 | */ 18 | 19 | rootProject.name = 'Algorithms' 20 | -------------------------------------------------------------------------------- /src/main/java/array/CheckValidPassword.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Question in Cloud Era. Check whether a given password is valid or not. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | class CheckValidPassword { 9 | public int solution(String S) { 10 | int res = -1; 11 | for (int i = 0; i < S.length(); i++) { 12 | for (int j = i + 1; j <= S.length(); j++) { 13 | if (isValid(S.substring(i, j))) { 14 | res = Math.max(res, j - i); 15 | } 16 | } 17 | } 18 | return res; 19 | } 20 | 21 | private boolean isValid(String s) { 22 | int[] a = new int[256]; 23 | for (int i = 0; i < s.length(); i++) { 24 | a[s.charAt(i)]++; 25 | } 26 | boolean hasUpperCase = false; 27 | for (int i = 65; i <= 90; i++) { 28 | if (a[i] > 0) { 29 | hasUpperCase = true; 30 | break; 31 | } 32 | } 33 | boolean hasNumber = false; 34 | for (int i = 48; i <= 57; i++) { 35 | if (a[i] > 0) { 36 | hasNumber = true; 37 | break; 38 | } 39 | } 40 | return (hasUpperCase && (!hasNumber)); 41 | } 42 | 43 | public static void main(String[] args) { 44 | System.out.println(new CheckValidPassword().solution("a0bb")); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/array/CountTripletsWithSmallerSum.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Count the number of triplets with sum smaller than a given number. Values are 7 | * distinct. 8 | * 9 | * Link: http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class CountTripletsWithSmallerSum { 14 | 15 | public static int countTriplets(int[] a, int sum) { 16 | int res = 0; 17 | Arrays.sort(a); 18 | for (int i = 0; i < a.length; i++) { 19 | if (a[i] >= sum) { 20 | break; 21 | } 22 | int es = sum - a[i]; 23 | int j = i + 1; 24 | int k = a.length - 1; 25 | while (j < k) { 26 | if (a[j] + a[k] < es) { 27 | res += k - j; 28 | // System.out.println("Res+" + res + "K , J : " + k + " , " + j); 29 | j++; 30 | } else if (a[j] + a[k] >= es) { 31 | k--; 32 | } 33 | } 34 | } 35 | System.out.println(res); 36 | return res; 37 | } 38 | 39 | public static void main(String[] args) { 40 | int[] a = new int[] { 5, 1, 3, 4, 7 }; 41 | CountTripletsWithSmallerSum.countTriplets(a, 12); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/array/MaxMinSort.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Sort an array in the maximum and minimum form. Hence an array like 5 | * 1,2,3,4,5,6,7 should become 7,1,6,2,5,3,4. Doing this with auxiliary space is 6 | * trivial. Hence do it in space. 7 | * 8 | * Link: http://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class MaxMinSort { 13 | 14 | public static void sort(int[] a) { 15 | int len = a.length; 16 | int j = 0; 17 | for (int i=0; i < len; i++) { 18 | int temp = a[i]; 19 | while (temp > 0) { 20 | if (i < len / 2) 21 | j = 2 * i + 1; 22 | else 23 | j = (len - 1 - i) * 2; 24 | if(i==j) { 25 | a[i]=-temp; 26 | break; 27 | } 28 | swap(temp, a[j]); 29 | a[j] = -1*a[j]; 30 | i=j; 31 | } 32 | } 33 | for (int n : a) 34 | System.out.print(n + " "); 35 | } 36 | 37 | public static void swap(int temp, int a) { 38 | int swap = a; 39 | temp = a; 40 | a = swap; 41 | } 42 | 43 | public static void main(String[] args) { 44 | int[] a = { 1, 2, 3, 4, 5, 6, 7 }; 45 | sort(a); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/array/ReversePositiveNumbers.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Given an array reverse the consecutive positive numbers between -ve numbers. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class ReversePositiveNumbers { 9 | 10 | public static int[] reverse(int[] arr) { 11 | if (arr == null || arr.length == 0) { 12 | return arr; 13 | } 14 | int i = 0, j = 1; 15 | while (j < arr.length) { 16 | if (arr[j] <= 0) { 17 | if (i != j - 1) { 18 | if (arr[i] <= 0) { 19 | i++; 20 | } 21 | reverse(arr, i, j - 1); 22 | } 23 | /* 24 | * Print it or whatever because the array has already been 25 | * reversed. 26 | */ 27 | i = ++j; 28 | } 29 | j++; 30 | } 31 | return arr; 32 | } 33 | 34 | private static void reverse(int[] arr, int i, int j) { 35 | while (j > i) { 36 | int temp = arr[i]; 37 | arr[i] = arr[j]; 38 | arr[j] = temp; 39 | i++; 40 | j--; 41 | } 42 | } 43 | 44 | public static void main(String[] args) { 45 | int[] arr = new int[] { 4, 3, 8, 9, -2, 6, 10, 13, 4, 5, -9, 0, -2 }; 46 | ReversePositiveNumbers.reverse(arr); 47 | for (int i = 0; i < arr.length; i++) { 48 | System.out.print(arr[i] + " "); 49 | } 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/array/StreamAverage.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | /** 4 | * Consider a stream of doubles. At any moment find the moving average of the 5 | * last k numbers. If received less than k numbers than return average of only 6 | * those numbers. 7 | * 8 | * Link: http://www.geeksforgeeks.org/average-of-a-stream-of-numbers/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class StreamAverage { 13 | 14 | public static void runningAverage(double[] stream, int k) { 15 | double avg = 0F; 16 | double[] store = new double[k]; 17 | int i = 0, sl = stream.length; 18 | boolean touchedK = false; 19 | for (int j = 0; j < sl; j++) { 20 | if (j == k) { 21 | touchedK = true; 22 | } 23 | if (i == k) { 24 | i = 0; 25 | } 26 | if (touchedK) { 27 | avg = (avg * k - store[i] + stream[j]) / k; 28 | } else { 29 | avg = (avg * (j) + stream[j]) / (j + 1); 30 | } 31 | System.out.println(avg); 32 | store[i] = stream[j]; 33 | i++; 34 | } 35 | } 36 | 37 | public static void main(String[] args) { 38 | double[] stream = new double[] { 1, 3, 5, 7, 0, 2, 5, 6 }; 39 | StreamAverage.runningAverage(stream, 3); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/array/UriTesting.java: -------------------------------------------------------------------------------- 1 | package array; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.net.URLEncoder; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * @author shivam.maharshi 10 | */ 11 | public class UriTesting { 12 | 13 | public static void main(String[] args) { 14 | long start = System.currentTimeMillis(); 15 | String file = "C:/Users/Sam/Downloads/elwiki-20151201-all-titles-in-ns0.txt"; 16 | List urls = FileUtil.read(file); 17 | List out = new ArrayList<>(), fail = new ArrayList<>(); 18 | for (String url : urls) 19 | try { 20 | out.add(URLEncoder.encode(url, "UTF-8")); 21 | } catch (UnsupportedEncodingException e) { 22 | fail.add(url); 23 | } 24 | FileUtil.write(out, file + "encoded"); 25 | FileUtil.write(fail, file + "failed"); 26 | System.out.println("Encoded all URLs in: " + ((System.currentTimeMillis() - start) / 1000) + " seconds."); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/bit/BitManipulation.java: -------------------------------------------------------------------------------- 1 | package bit; 2 | 3 | public class BitManipulation { 4 | 5 | /* 6 | * There are two 32 bit number - n and m. Two integers j and i where j > i. 7 | * Insert m into n between these bit positions j and i. 8 | */ 9 | public static int insertNumber(int n, int m, int j, int i) { 10 | int mask = (int) (Math.pow(2, j - i + 1) - 1); 11 | mask = ~(mask << 2); 12 | m = m << i; 13 | return (n & mask) | m; 14 | } 15 | 16 | public static void main(String[] args) { 17 | int n = Integer.valueOf("10000001000", 2); 18 | int m = Integer.parseInt("11011", 2); 19 | int res = BitManipulation.insertNumber(n, m, 5, 1); 20 | System.out.println(Integer.toBinaryString(res)); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/bit/FractionalRepresentation.java: -------------------------------------------------------------------------------- 1 | package bit; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class FractionalRepresentation { 6 | 7 | public static String representFractionalNumberInBinary(BigDecimal num) { 8 | 9 | BigDecimal one = new BigDecimal(1); 10 | BigDecimal zero = new BigDecimal(0); 11 | BigDecimal two = new BigDecimal(2); 12 | 13 | if (num.compareTo(one) == 0 || num.compareTo(one) == 1 || num.compareTo(zero) == -1) { 14 | return "Error"; 15 | } 16 | StringBuilder sb = new StringBuilder(); 17 | while (num.compareTo(zero) == 0 || num.compareTo(zero) == 1) { 18 | if (sb.length() >= 32) { 19 | return "Error"; 20 | } 21 | num.multiply(two); 22 | if (num.compareTo(one) == 0 || num.compareTo(one) == 1) { 23 | num.subtract(one); 24 | sb.append("1"); 25 | } else { 26 | sb.append("0"); 27 | } 28 | } 29 | return sb.toString(); 30 | } 31 | 32 | public static void main(String[] args) { 33 | System.out.println(FractionalRepresentation.representFractionalNumberInBinary(new BigDecimal(0.72))); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/bit/MaxNumberWithoutComparison.java: -------------------------------------------------------------------------------- 1 | package bit; 2 | 3 | /* 4 | * Find the max between two numbers without using the comparison operator. 5 | */ 6 | 7 | public class MaxNumberWithoutComparison { 8 | 9 | public static int max(int x, int y) { 10 | int z = x - y; 11 | int i = (z >> 31) & 0x1; 12 | int max = x - i * z; 13 | return max; 14 | } 15 | 16 | int flip(int a) { 17 | return 1 ^ a; 18 | } 19 | 20 | int sign(int a) { 21 | return a >> 31; 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(max(10, 5)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/book/mcdowell/AllCombinationOfLength.java: -------------------------------------------------------------------------------- 1 | package book.mcdowell; 2 | 3 | /** 4 | * Given a set of characters, print all combinations of length k. 5 | * 6 | * Link: 7 | * http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in 8 | * -a-given-array-of-size-n/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class AllCombinationOfLength { 13 | 14 | public static void print(char[] c, int k, int index, String s) { 15 | if (index == k) { 16 | System.out.println(s); 17 | return; 18 | } 19 | for (int i = 0; i < c.length; i++) { 20 | print(c, k, index + 1, s + c[i]); 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | char[] c = new char[] { 'a', 'b', 'c' }; 26 | print(c, 2, 0, ""); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/book/mcdowell/AllCombinations.java: -------------------------------------------------------------------------------- 1 | package book.mcdowell; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * @author shivam.maharshi 8 | */ 9 | public class AllCombinations { 10 | 11 | public static void printAllSets(char[] c) { 12 | List list = new ArrayList(); 13 | list.add(""); 14 | printSets(c, 0, list); 15 | } 16 | 17 | private static void printSets(char[] c, int index, List list) { 18 | if(index==c.length) return; 19 | int len = list.size(); 20 | for(int i=0; i max) { 30 | max = sum; 31 | } 32 | first = i - m + 1; 33 | next = i + 1; 34 | } 35 | 36 | return max; 37 | } 38 | 39 | public static void main(String[] args) { 40 | System.out.println(circularArrayMaximumSum(new int[] { 12, 0, 1, 5, 40, 2, 3, 10, 15, 12 }, 3)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/book/mcdowell/MedianOfIntStream.java: -------------------------------------------------------------------------------- 1 | package book.mcdowell; 2 | 3 | /** 4 | * Given that integers are read from a data stream. Find median of elements read 5 | * so for in efficient way. For simplicity assume there are no duplicates. For 6 | * example, let us consider the stream 5, 15, 1, 3. 7 | * 8 | * Link: 9 | * http://www.geeksforgeeks.org/median-of-stream-of-integers-running-integers/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class MedianOfIntStream { 14 | 15 | // TODO: 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/dp/BinomialCoefficient.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | /** 4 | * Calculate binomial co-effcient. 5 | * 6 | * Link: 7 | * http://www.geeksforgeeks.org/dynamic-programming-set-9-binomial-coefficient/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class BinomialCoefficient { 12 | 13 | public static void main(String[] args) { 14 | int n = 5; 15 | int k = 2; 16 | System.out.println(get(n, k, new int[n + 1][k + 1])); 17 | System.out.println(val(n, k, new int[n + 1][k + 1])); 18 | } 19 | 20 | public static int val(int n, int k, int[][] dp) { 21 | for(int i=0; i g[i][k] + g[k][j]) 26 | r[i][j] = g[i][k] + g[k][j]; 27 | print(r); 28 | return r; 29 | } 30 | 31 | public static void print(int[][] r) { 32 | for (int[] rr : r) { 33 | for (int n : rr) 34 | System.out.print(n + " "); 35 | System.out.println(); 36 | } 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/dp/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | /** 4 | * Return the length of the longest common subsequence. 5 | * 6 | * Link: http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common- 7 | * subsequence/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class LongestCommonSubsequence { 12 | 13 | public static int get(String a, String b) { 14 | int[][] dp = new int[a.length() + 1][b.length() + 1]; 15 | for(int i=0; i < a.length(); i++) { 16 | for(int j=0; j < b.length(); j++) { 17 | if (a.charAt(i) == b.charAt(j)) 18 | dp[i+1][j+1] = dp[i][j] + 1; 19 | else 20 | dp[i+1][j+1] = Math.max(dp[i][j+1], dp[i+1][j]); 21 | } 22 | } 23 | return dp[a.length()][b.length()]; 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(get("AGGTAB", "GXTXAYB")); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/dp/LongestPalindromicSubsequence.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | /** 4 | * Find the longest palindromic subsequence. 5 | * 6 | * Link: 7 | * http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class LongestPalindromicSubsequence { 12 | 13 | public static void main(String[] args) { 14 | System.out.println(lps("bbabcbcab")); // babcbab 15 | } 16 | 17 | public static int lps(String s) { 18 | int[][] dp = new int[s.length()][s.length()]; 19 | 20 | for (int i = 0; i < s.length(); i++) 21 | dp[i][i] = 1; 22 | 23 | for (int len = 1; len < s.length(); len++) { 24 | for (int i = 0; i + len < s.length(); i++) { 25 | dp[i][i + len] = Math.max(dp[i + 1][i + len], dp[i][i + len - 1]); 26 | if (s.charAt(i) == s.charAt(i + len)) 27 | dp[i][i + len] = Math.max(dp[i][i + len], 2 + dp[i + 1][i + len - 1]); 28 | } 29 | } 30 | 31 | return dp[0][s.length() - 1]; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/dp/MaximumSumIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | 7 | import junit.framework.TestCase; 8 | 9 | /** 10 | * Link: 11 | * http://www.geeksforgeeks.org/dynamic-programming-set-14-maximum-sum-increasing-subsequence/ 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class MaximumSumIncreasingSubsequence extends TestCase { 16 | 17 | @Test 18 | public void test() { 19 | assertEquals(106, maxSumSub(new int[] { 1, 101, 2, 3, 100, 4, 5 })); 20 | assertEquals(306, maxSumSub(new int[] { 1, 105, 2, 3, 200, 4, 5 })); 21 | } 22 | 23 | public static int maxSumSub(int[] a) { 24 | if (a == null || a.length == 0) 25 | return 0; 26 | int[] dp = new int[a.length]; 27 | Arrays.fill(dp, Integer.MIN_VALUE); 28 | dp[0] = a[0]; 29 | int max = Integer.MIN_VALUE; 30 | for (int i = 1; i < a.length; i++) 31 | for (int j = 0; j < i; j++) 32 | if (a[i] > a[j]) { 33 | dp[i] = Math.max(dp[i], dp[j] + a[i]); 34 | max = Math.max(max, dp[i]); 35 | } 36 | return max; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/dp/MinCostPath.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | /** 4 | * You can only move right, down or diagonal. 5 | * 6 | * Link: http://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class MinCostPath { 11 | 12 | // Bottom up dynamic approach. 13 | public static int minPathSum(int[][] grid) { 14 | int h = grid.length; 15 | int w = grid[0].length; 16 | int[][] dp = new int[h][w]; 17 | dp[0][0] = grid[0][0]; 18 | for (int i = 1; i < h; i++) 19 | dp[i][0] = dp[i - 1][0] + grid[i][0]; 20 | for (int j = 1; j < w; j++) 21 | dp[0][j] = dp[0][j - 1] + grid[0][j]; 22 | 23 | for (int i = 1; i < h; i++) { 24 | for (int j = 1; j < w; j++) { 25 | dp[i][j] = grid[i][j] + Math.min(dp[i][j - 1], Math.min(dp[i - 1][j], dp[i-1][j-1])); 26 | } 27 | } 28 | return dp[h - 1][w - 1]; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/dp/PrintMaximumAWithFourKeys.java: -------------------------------------------------------------------------------- 1 | package dp; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: 9 | * http://www.geeksforgeeks.org/how-to-print-maximum-number-of-a-using-given-four-keys/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class PrintMaximumAWithFourKeys extends TestCase { 14 | 15 | @Test 16 | public void test() { 17 | assertEquals(3, max(3)); 18 | assertEquals(9, max(7)); 19 | } 20 | 21 | public static int max(int n) { 22 | int[] dp = new int[n], cp = new int[n]; 23 | dp[0] = 1; 24 | dp[1] = 2; 25 | dp[2] = 3; 26 | cp[2] = 1; 27 | for (int i = 3; i < n; i++) { 28 | cp[i] = dp[i - 2]; 29 | dp[i] = Math.max(i + 1, Math.max(2 * dp[i - 3], dp[i - 3] + cp[i - 1])); 30 | } 31 | return dp[n - 1]; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/ds/DoubleHash.java: -------------------------------------------------------------------------------- 1 | package ds; 2 | 3 | /** 4 | * Represents a double hash function. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class DoubleHash { 9 | 10 | private Hash h; 11 | 12 | public DoubleHash(long max) { 13 | this.h = new Hash(max); 14 | } 15 | 16 | /** 17 | * Calculates a 32 bit hash by using the 32 lower & upper bits of a 64 bit 18 | * hash. 19 | */ 20 | public int getHash(long n, int mul) { 21 | long hash64 = h.getHash(n); 22 | return ((int) hash64) + mul * ((int) (hash64 >> 32)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/ds/Edge.java: -------------------------------------------------------------------------------- 1 | package ds; 2 | 3 | /** 4 | * Standard representation of an Edge. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class Edge { 9 | int wieght; 10 | int src; 11 | int des; 12 | 13 | public Edge(int src, int des, int wieght) { 14 | this.src = src; 15 | this.des = des; 16 | this.wieght = wieght; 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return "Edge [wieght=" + wieght + ", src=" + src + ", des=" + des + "]"; 22 | } 23 | 24 | public int getWieght() { 25 | return wieght; 26 | } 27 | 28 | public void setWieght(int wieght) { 29 | this.wieght = wieght; 30 | } 31 | 32 | public int getSrc() { 33 | return src; 34 | } 35 | 36 | public void setSrc(int src) { 37 | this.src = src; 38 | } 39 | 40 | public int getDes() { 41 | return des; 42 | } 43 | 44 | public void setDes(int des) { 45 | this.des = des; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/ds/Hash.java: -------------------------------------------------------------------------------- 1 | package ds; 2 | 3 | /** 4 | * Represents a hash function. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class Hash { 9 | 10 | private long max; 11 | 12 | public Hash(long max) { 13 | this.max = max; 14 | } 15 | 16 | // A very naive hash function. 17 | public long getHash(long n) { 18 | return n % max; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/ds/Node.java: -------------------------------------------------------------------------------- 1 | package ds; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Standard representation of a Node. Should remove adjNodes from it. 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class Node { 11 | 12 | private int id; 13 | private int level; 14 | private State state; 15 | private List adjNodes; 16 | 17 | public Node(int id) { 18 | this(id, null); 19 | } 20 | 21 | public Node(int id, List nodes) { 22 | this.id = id; 23 | this.adjNodes = nodes; 24 | this.level = 0; 25 | this.state = State.UNVISITED; 26 | } 27 | 28 | public int getId() { 29 | return id; 30 | } 31 | 32 | public void setId(int id) { 33 | this.id = id; 34 | } 35 | 36 | public int getLevel() { 37 | return level; 38 | } 39 | 40 | public void setLevel(int level) { 41 | this.level = level; 42 | } 43 | 44 | public List getAdjNodes() { 45 | return adjNodes; 46 | } 47 | 48 | public void setAdjNodes(List adjNodes) { 49 | this.adjNodes = adjNodes; 50 | } 51 | 52 | public State getState() { 53 | return state; 54 | } 55 | 56 | public void setState(State state) { 57 | this.state = state; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/ds/State.java: -------------------------------------------------------------------------------- 1 | package ds; 2 | 3 | /** 4 | * Standard Node state representation. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public enum State { 9 | VISITED, VISITING, UNVISITED; 10 | } -------------------------------------------------------------------------------- /src/main/java/ds/Union.java: -------------------------------------------------------------------------------- 1 | package ds; 2 | 3 | /** 4 | * Standard representation of a Union data structure. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class Union { 9 | int[] a; 10 | 11 | public Union(int n) { 12 | a = new int[n]; 13 | for (int i = 0; i < n; i++) { 14 | a[i] = i; 15 | } 16 | } 17 | 18 | public boolean isConnected(int n1, int n2) { 19 | return getParent(n1) == getParent(n2); 20 | } 21 | 22 | public void connect(int n1, int n2) { 23 | int p1 = getParent(n1); 24 | int p2 = getParent(n2); 25 | int pMin = Math.min(p1, p2); 26 | int pMax = Math.max(p1, p2); 27 | for (int i = 0; i < a.length; i++) { 28 | if (a[i] == pMax) { 29 | a[i] = pMin; 30 | } 31 | } 32 | } 33 | 34 | private int getParent(int id) { 35 | return a[id]; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/ds/java/StackApp.java: -------------------------------------------------------------------------------- 1 | package ds.java; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * Play with the usage of the Java data structures. Examine there behavior. 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class StackApp { 11 | 12 | private static Stack st = new Stack(); 13 | 14 | public static void checkStack() { 15 | Stack st = StackApp.st; 16 | System.out.println(st.add(5)); // Adds item to the bottom. 17 | System.out.println(st.push(10)); // Adds item to the top. 18 | System.out.println(st.pop()); // Removes the top and returns it. 19 | System.out.println(st.peek()); // Returns the top without removing it. 20 | // Same as pop but throws exception. 21 | System.out.println(st.remove(20)); // Removes the first occurrence of 22 | // the element. 23 | } 24 | 25 | public static void main(String[] args) { 26 | StackApp.checkStack(); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/graph/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import ds.GraphAdjList; 4 | 5 | /** 6 | * Standard Depth First Search implementation for various graph representation. 7 | * 8 | * Link: http://www.geeksforgeeks.org/depth-first-traversal-for-a-graph 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class DepthFirstSearch { 13 | 14 | // O(E+V) 15 | public static void dfs(GraphAdjList graph, int v) { 16 | boolean[] visited = new boolean[graph.size()]; 17 | dfs(graph, v, visited); 18 | } 19 | 20 | private static void dfs(GraphAdjList graph, int v, boolean[] visited) { 21 | if (!visited[v]) { 22 | System.out.print(v + " "); 23 | visited[v] = true; 24 | for (int i = 0; i < graph.getAdjList(v).size(); i++) { 25 | dfs(graph, graph.getAdjList(v).get(i), visited); 26 | } 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | dfs(GraphAdjList.getPopulatedCyclicDirectedGraph(), 2); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/graph/DetectCycleInDirectedGraph.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import ds.GraphAdjList; 4 | 5 | /** 6 | * Given a directed graph, check whether the graph contains a cycle or not. 7 | * 8 | * Link: http://www.geeksforgeeks.org/detect-cycle-in-a-graph 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class DetectCycleInDirectedGraph { 13 | 14 | // O(E+V) 15 | public static boolean isCyclic(GraphAdjList graph) { 16 | boolean[] visited = new boolean[graph.size()]; 17 | return isCyclic(graph, 0, visited); 18 | } 19 | 20 | private static boolean isCyclic(GraphAdjList graph, int v, boolean[] visited) { 21 | if (visited[v]) 22 | return true; 23 | visited[v] = true; 24 | for (int i = 0; i < graph.getAdjList(v).size(); i++) { 25 | if (isCyclic(graph, graph.getAdjList(v).get(i), visited)) 26 | return true; 27 | else 28 | visited[graph.getAdjList(v).get(i)] = false; // Backtrack. 29 | } 30 | return false; 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(isCyclic(GraphAdjList.getPopulatedCyclicDirectedGraph())); 35 | System.out.println(isCyclic(GraphAdjList.getPopulatedNonCyclicDirectedGraph())); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/graph/DetectCycleInUndirectedGraph.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import ds.GraphAdjList; 4 | 5 | /** 6 | * Given an undirected graph, check whether the graph contains a cycle or not. 7 | * 8 | * Link: http://www.geeksforgeeks.org/detect-cycle-undirected-graph 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class DetectCycleInUndirectedGraph { 13 | 14 | // O(E+V) 15 | public static boolean isCyclic(GraphAdjList graph) { 16 | boolean[] visited = new boolean[graph.size()]; 17 | return isCyclic(graph, 0, -1, visited); 18 | } 19 | 20 | private static boolean isCyclic(GraphAdjList graph, int v, int vParent, boolean[] visited) { 21 | if (visited[v]) 22 | return true; 23 | visited[v] = true; 24 | for (int i = 0; i < graph.getAdjList(v).size(); i++) { 25 | if (graph.getAdjList(v).get(i) != vParent && isCyclic(graph, graph.getAdjList(v).get(i), v, visited)) 26 | return true; 27 | else 28 | visited[graph.getAdjList(v).get(i)] = false; // Backtrack. 29 | } 30 | return false; 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(isCyclic(GraphAdjList.getPopulatedCyclicUndirectedGraph())); 35 | System.out.println(isCyclic(GraphAdjList.getPopulatedNonCyclicUndirectedGraph())); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/graph/DetectCycleInUndirectedGraphUsingUnion.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import ds.GraphAdjList; 4 | import ds.Union; 5 | 6 | /** 7 | * Detect cycle in an undirected graph via Union Find algorithm using Disjoint 8 | * Data Set. 9 | * 10 | * Link: http://www.geeksforgeeks.org/union-find 11 | * 12 | * @author shivam.maharshi 13 | */ 14 | public class DetectCycleInUndirectedGraphUsingUnion { 15 | 16 | public static boolean isCyclic(GraphAdjList graph) { 17 | Union u = new Union(graph.size()); 18 | for (int i = 0; i < graph.size(); i++) { 19 | for (int j = 0; j < graph.getAdjList(i).size(); j++) { 20 | if (graph.getAdjList(i).get(j) > i) { 21 | /* 22 | * This condition is required because of the non directed 23 | * graph implied transitive property. A->B = B->A 24 | */ 25 | if (!u.isConnected(i, graph.getAdjList(i).get(j))) 26 | u.connect(i, graph.getAdjList(i).get(j)); 27 | else 28 | return true; 29 | } 30 | } 31 | } 32 | return false; 33 | } 34 | 35 | public static void main(String[] args) { 36 | System.out.println(isCyclic(GraphAdjList.getPopulatedCyclicUndirectedGraph())); 37 | System.out.println(isCyclic(GraphAdjList.getPopulatedNonCyclicUndirectedGraph())); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/graph/IsUndirectedGraphATree.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import ds.GraphAdjList; 4 | 5 | /** 6 | * Check if the undirected graph is a tree. An undirected graph is tree if it 7 | * has the following properties. 1) There is no cycle. 2) The graph is connected. 8 | * 9 | * Link: http://geeksquiz.com/check-given-graph-tree/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class IsUndirectedGraphATree { 14 | 15 | public static boolean isTree(GraphAdjList graph) { 16 | return IsUndirectedGraphConnected.isConnected(graph) && !DetectCycleInUndirectedGraph.isCyclic(graph); 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println(isTree(GraphAdjList.getPopulatedCyclicUndirectedGraph())); 21 | System.out.println(isTree(GraphAdjList.getPopulatedNonCyclicUndirectedGraph())); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/graph/IsUndirectedGraphConnected.java: -------------------------------------------------------------------------------- 1 | package graph; 2 | 3 | import ds.GraphAdjList; 4 | 5 | /** 6 | * Check if the undirected graph is connected, which means that every node can 7 | * be reached from any other node. 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class IsUndirectedGraphConnected { 12 | 13 | // Will follow the DFS approach. 14 | public static boolean isConnected(GraphAdjList graph) { 15 | boolean[] visited = new boolean[graph.size()]; 16 | dfs(graph, 0, visited); 17 | for (boolean v : visited) 18 | if (!v) 19 | return false; 20 | return true; 21 | } 22 | 23 | private static void dfs(GraphAdjList graph, int v, boolean[] visited) { 24 | if (!visited[v]) { 25 | visited[v] = true; 26 | for (int i = 0; i < graph.getAdjList(v).size(); i++) { 27 | dfs(graph, graph.getAdjList(v).get(i), visited); 28 | } 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | System.out.println(isConnected(GraphAdjList.getPopulatedCyclicUndirectedGraph())); 34 | System.out.println(isConnected(GraphAdjList.getPopulatedNonCyclicUndirectedGraph())); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/BetweenTwoSets.java: -------------------------------------------------------------------------------- 1 | package hackerrank; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.junit.Test; 7 | 8 | import junit.framework.TestCase; 9 | 10 | /** 11 | * Link: https://www.hackerrank.com/contests/w25/challenges/between-two-sets 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class BetweenTwoSets extends TestCase { 16 | 17 | @Test 18 | public void test() { 19 | int[] a = new int[] { 2, 4 }; 20 | int[] b = new int[] { 16, 32, 96 }; 21 | assertEquals(3, get(a, b)); 22 | } 23 | 24 | public static int get(int[] a, int[] b) { 25 | List n = new ArrayList<>(); 26 | for (int i = 1; i <= 100; i++) { 27 | for (int j = 0; j < a.length; j++) { 28 | if (i % a[j] == 0 && j == a.length - 1) { 29 | n.add(i); 30 | } else if (i % a[j] != 0) { 31 | break; 32 | } 33 | } 34 | } 35 | 36 | for (int i = 0; i < n.size(); i++) { 37 | for (int j = 0; j < b.length; j++) { 38 | if ((b[j] % n.get(i)) != 0) { 39 | n.remove(i); 40 | i--; 41 | break; 42 | } 43 | } 44 | } 45 | 46 | return n.size(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/HalloweenParty.java: -------------------------------------------------------------------------------- 1 | package hackerrank; 2 | 3 | /** 4 | * Given the number of cuts as k, cut a given infinite cake into the maximum 5 | * pieces. 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class HalloweenParty { 10 | 11 | public static void main(String[] args) { 12 | int[] a = new int[] { 10000000 }; 13 | int[] r = max_Chocolates(a); 14 | for (int rr : r) 15 | System.out.print(rr + " "); 16 | } 17 | 18 | public static int[] max_Chocolates(int[] arr) { 19 | int[] r = new int[arr.length]; 20 | for (int i = 0; i < arr.length; i++) 21 | r[i] = max(arr[i]); 22 | 23 | return r; 24 | } 25 | 26 | public static int max(int n) { 27 | int x = n / 2; 28 | return (n - x) * x; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/IsPossible.java: -------------------------------------------------------------------------------- 1 | package hackerrank; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Given a number pair can 9 | * @author shivam.maharshi 10 | * 11 | */ 12 | public class IsPossible extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals("Yes", isPossible(1, 4, 1, 4)); 17 | assertEquals("Yes", isPossible(1, 4, 5, 9)); 18 | assertEquals("No", isPossible(1, 4, 5, 10)); 19 | assertEquals("No", isPossible(1, 4, 1, 2)); 20 | assertEquals("No", isPossible(1, 4, 0, 4)); 21 | assertEquals("No", isPossible(1, 4, 0, 3)); 22 | assertEquals("No", isPossible(1, 1, 1000, 1000)); 23 | } 24 | 25 | public static String isPossible(int a, int b, int c, int d) { 26 | return p(a, b, c, d, new Boolean[a + b + 1 + c][a + b + 1 + d]) ? "Yes" : "No"; 27 | } 28 | 29 | public static boolean p(int a, int b, int c, int d, Boolean[][] dp) { 30 | if (a > c || b > d) 31 | return false; 32 | 33 | if (a == c && b == d) 34 | return true; 35 | 36 | if (dp[a][b] != null) 37 | return dp[a][b]; 38 | 39 | dp[a][b] = p(a + b, b, c, d, dp) || p(a, a + b, c, d, dp); 40 | 41 | return dp[a][b]; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/hackerrank/LoveLetterMystery.java: -------------------------------------------------------------------------------- 1 | package hackerrank; 2 | 3 | public class LoveLetterMystery { 4 | 5 | public static void main(String[] args) { 6 | String[] l = new String[]{"abc", "abcba", "abcd"}; 7 | int[] n = mystery(l); 8 | for (int nn : n) 9 | System.out.print(nn + " "); 10 | } 11 | 12 | public static int[] mystery(String[] letter) { 13 | int[] r = new int[letter.length]; 14 | for (int i = 0; i < letter.length; i++) { 15 | int c = 0; 16 | String[] s = letter[i].split(" "); 17 | for (String ss : s) 18 | c += mystery(ss); 19 | r[i] = c; 20 | } 21 | return r; 22 | } 23 | 24 | public static int mystery(String s) { 25 | int l = 0, h = s.length() - 1; 26 | int r = 0; 27 | while (h > l) { 28 | r += diff(s.charAt(l), s.charAt(h)); 29 | l++; 30 | h--; 31 | } 32 | return r; 33 | } 34 | 35 | public static int diff(char l, char h) { 36 | return Math.abs(((int) l) - ((int) h)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/interview/amazon/OddTimesNumber.java: -------------------------------------------------------------------------------- 1 | package interview.amazon; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import org.junit.Test; 7 | 8 | import junit.framework.TestCase; 9 | 10 | /** 11 | * Find out the number present odd number of times in the given list. 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class OddTimesNumber extends TestCase { 16 | 17 | @Test 18 | public void test() { 19 | assertEquals(5, get(Arrays.asList(new Integer[] { 1, 4, 2, 2, 7, 5, 7, 4, 1 })).intValue()); 20 | } 21 | 22 | public static Integer get(List l) { 23 | if (l == null || l.isEmpty()) 24 | return null; 25 | Integer r = l.get(0); 26 | for (int i = 1; i < l.size(); i++) 27 | r ^= l.get(i); 28 | return r; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/interview/goldman_sachs/SumPairs.java: -------------------------------------------------------------------------------- 1 | package interview.goldman_sachs; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.junit.Test; 7 | 8 | import junit.framework.TestCase; 9 | 10 | /** 11 | * Given an array count the number of distinct pairs that sum up to a particular 12 | * number. 13 | * 14 | * @author shivam.maharshi 15 | */ 16 | public class SumPairs extends TestCase { 17 | 18 | @Test 19 | public void test() { 20 | assertEquals(0, count(new int[] {}, 6)); 21 | assertEquals(2, count(new int[] { 1, 2, 3, 4, 5, 6 }, 6)); 22 | assertEquals(1, count(new int[] { 1, 2, 3, 4, 5, 5 }, 10)); 23 | } 24 | 25 | public static int count(int[] a, int t) { 26 | int c = 0; 27 | Map m = new HashMap<>(); 28 | for (int i = 0; i < a.length; i++) { 29 | if (m.containsKey(t - a[i])) 30 | m.put(t - a[i], a[i]); 31 | else 32 | m.put(a[i], null); 33 | } 34 | 35 | for (Integer k : m.keySet()) 36 | if (m.get(k) != null) 37 | c++; 38 | 39 | return c; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/interview/google/FibonacciNumberLessThanN.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | /** 4 | * How many Fibonacci numbers exists less than a given number n.Can you find a 5 | * function in terms of n , to get the number of fibonacci number less than n. 6 | * Example : n = 6 Answer: 6 as (0, 1, 1, 2, 3, 5) 7 | * 8 | * Link: http://www.careercup.com/question?id=5713892824055808 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class FibonacciNumberLessThanN { 13 | 14 | public static long findFibCount(long n) { 15 | if (n == 0) 16 | return 0; 17 | if (n == 1) 18 | return 1; 19 | double sqrtFive = Math.sqrt(5); 20 | double fi = (1.0 + sqrtFive) / 2.0; 21 | int index = (int) (Math.log(n * sqrtFive + 0.5) / Math.log(fi)); 22 | int res = (int) ((Math.pow(fi, index) / sqrtFive) + 0.5); 23 | if (res != n) { 24 | index += 1; 25 | } 26 | System.out.println(index); 27 | return index; 28 | } 29 | 30 | public static void main(String[] args) { 31 | findFibCount(6); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/interview/google/FindNumRepeatsMoreThanInSortedArr.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | /** 4 | * Given a sorted array of size N of int32, find an element that repeats > 5 | * ceil(N / 2) times. Your algo may assume that there will be always such 6 | * element. Space/time O(1). Follow up question: Now element repeats > ceil(N / 7 | * 4) times. Space/time O(1) 8 | * 9 | * Link: http://www.careercup.com/question?id=5647871593414656 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class FindNumRepeatsMoreThanInSortedArr { 14 | 15 | // For ceil(n/2) 16 | public static int getNby2(int[] a) { 17 | return a[a.length / 2]; 18 | } 19 | 20 | // For ceil(n/4) 21 | public static int getNby4(int[] a) { 22 | for (int i = 1; i < 3; i++) { 23 | if (a[(a.length * i) / 4] == a[(a.length * (i + 1)) / 4]) { 24 | return a[(a.length * i) / 4]; 25 | } 26 | } 27 | return 0; // Should never reach. 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[] a = { 1, 2, 2, 2, 2, 2, 2, 2, 5, 5 }; 32 | System.out.println(getNby2(a)); 33 | System.out.println(getNby4(a)); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/interview/google/FruitIntoBaskets.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * https://leetcode.com/explore/interview/card/google/67/sql-2/3046 8 | */ 9 | public class FruitIntoBaskets { 10 | 11 | public int totalFruit(int[] fruits) { 12 | int left = 0, maxFruitCount = 0; 13 | final Map map = new HashMap<>(); 14 | 15 | for (int right=0; right 2) { 19 | map.put(fruits[left], map.get(fruits[left]) -1); 20 | if (map.get(fruits[left]) == 0) { 21 | map.remove(fruits[left]); 22 | } 23 | left++; 24 | } 25 | 26 | maxFruitCount = Math.max(maxFruitCount, right - left + 1); 27 | } 28 | 29 | return maxFruitCount; 30 | } 31 | 32 | public static void main(String[] args) { 33 | int count = new FruitIntoBaskets().totalFruit(new int[]{3,3,3,1,2,1,1,2,3,3,4}); 34 | System.out.println(count); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/interview/google/GCD.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://www.interviewbit.com/problems/greatest-common-divisor/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class GCD extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(0, gcd(2, 0)); 17 | assertEquals(2, gcd(2, 2)); 18 | assertEquals(2, gcd(2, 4)); 19 | assertEquals(4, gcd(4, 8)); 20 | assertEquals(3, gcd(6, 9)); 21 | } 22 | 23 | public static int gcd(int a, int b) { 24 | int max = Math.max(a, b), min = Math.min(a, b); 25 | if (min == 0) 26 | return max; 27 | while (max % min != 0) { 28 | max = max - min; 29 | if (max < min) { 30 | int t = min; 31 | min = max; 32 | max = t; 33 | } 34 | } 35 | return min; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/interview/google/GridUniquePaths.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://www.interviewbit.com/problems/grid-unique-paths/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class GridUniquePaths extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(1, uniquePaths(1, 2)); 17 | assertEquals(1, uniquePaths(2, 1)); 18 | assertEquals(2, uniquePaths(2, 2)); 19 | } 20 | 21 | public static int uniquePaths(int a, int b) { 22 | if (a <= 0 || b <= 0) 23 | return 0; 24 | int[][] dp = new int[a][b]; 25 | for (int i = 0; i < a; i++) 26 | dp[i][0] = 1; 27 | for (int i = 0; i < b; i++) 28 | dp[0][i] = 1; 29 | for (int i = 1; i < a; i++) 30 | for (int j = 1; j < b; j++) 31 | dp[i][j] = dp[i][j - 1] + dp[i - 1][j]; 32 | return dp[a - 1][b - 1]; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/interview/google/JumpGame.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | /** 4 | * https://leetcode.com/explore/interview/card/google/59/array-and-strings/3053 5 | */ 6 | public class JumpGame { 7 | 8 | public boolean canJump(int[] nums) { 9 | if (nums.length == 1) { 10 | return true; 11 | } 12 | int[] dp = new int[nums.length]; 13 | dp[0] = nums[0]; 14 | for (int i=1; i getRow(int a) { 28 | ArrayList l = new ArrayList<>(), t = new ArrayList<>(); 29 | if (a < 0) 30 | return l; 31 | int i = 1; 32 | t.add(1); 33 | while (i <= a) { 34 | l.add(1); 35 | for (int j = 0; j < i - 1; j++) 36 | l.add(t.get(j) + t.get(j + 1)); 37 | l.add(1); 38 | t = l; 39 | l = new ArrayList<>(); 40 | i++; 41 | } 42 | return t; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/interview/google/LicenseKeyFormatting.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | /** 4 | * https://leetcode.com/explore/interview/card/google/67/sql-2/472 5 | */ 6 | public class LicenseKeyFormatting { 7 | 8 | public String licenseKeyFormatting(String s, int k) { 9 | final String inputWithoutDashes = removeDashes(s); 10 | final String processedInput = toUpperCase(inputWithoutDashes); 11 | final StringBuilder resultStringBuilder = new StringBuilder(); 12 | int currentSegmentCount = 0; 13 | 14 | for (int i=processedInput.length()-1; i>=0; i--) { 15 | if (currentSegmentCount == k) { 16 | resultStringBuilder.append("-"); 17 | currentSegmentCount = 0; 18 | } 19 | resultStringBuilder.append(processedInput.charAt(i)); 20 | currentSegmentCount++; 21 | } 22 | 23 | return resultStringBuilder.reverse().toString(); 24 | } 25 | 26 | private String removeDashes(final String input) { 27 | return input.replace("-", ""); 28 | } 29 | 30 | private String toUpperCase(final String input) { 31 | return input.toUpperCase(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/interview/google/LongestSubstringWithAtMostTwoDistinctCharacters.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * https://leetcode.com/explore/interview/card/google/59/array-and-strings/3054 8 | */ 9 | public class LongestSubstringWithAtMostTwoDistinctCharacters { 10 | 11 | public int lengthOfLongestSubstringTwoDistinct(String s) { 12 | int left = 0, right = 0, maxLength = 0; 13 | final Map map = new HashMap<>(); 14 | 15 | while (right < s.length()) { 16 | char rChar = s.charAt(right); 17 | map.put(rChar, map.getOrDefault(rChar, 0) + 1); 18 | right++; 19 | 20 | while (map.size() > 2) { 21 | char lChar = s.charAt(left); 22 | map.put(lChar, map.get(lChar) - 1); 23 | if (map.get(lChar) == 0) { 24 | map.remove(lChar); 25 | } 26 | left++; 27 | } 28 | 29 | maxLength = Math.max(maxLength, right - left); 30 | } 31 | 32 | return maxLength; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/interview/google/LongestSubstringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * https://leetcode.com/explore/interview/card/google/59/array-and-strings/3047 8 | */ 9 | public class LongestSubstringWithoutRepeatingCharacters { 10 | 11 | public int lengthOfLongestSubstring(String s) { 12 | int left = 0, maxSubstringLength = 0; 13 | final Set set = new HashSet<>(); 14 | 15 | for (int right = 0; right < s.length(); right++) { 16 | if (!set.contains(s.charAt(right))) { 17 | set.add(s.charAt(right)); 18 | } else { 19 | while(s.charAt(right) != s.charAt(left)) { 20 | set.remove(s.charAt(left)); 21 | left++; 22 | } 23 | left++; 24 | } 25 | 26 | maxSubstringLength = Math.max(maxSubstringLength, right - left + 1); 27 | } 28 | 29 | return maxSubstringLength; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/interview/google/MedianOfArray.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Link: https://www.interviewbit.com/problems/median-of-array/ Link: 7 | * http://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class MedianOfArray { 12 | 13 | public static double findMedianSortedArrays(final List a, final List b) { 14 | if ((a == null || a.size() == 0) && (b == null || b.size() == 0)) 15 | return -1; 16 | if (a == null || a.size() == 0) 17 | return b.size() % 2 == 1 ? b.get(b.size() / 2) : b.get((b.size() / 2) - 1); 18 | if (b == null || b.size() == 0) 19 | return a.size() % 2 == 1 ? a.get(a.size() / 2) : a.get((a.size() / 2) - 1); 20 | int as = a.size(), bs = b.size(), sum = as + bs; 21 | return sum % 2 == 1 ? find(a, b, sum / 2, 0, as, 0, bs, true) : find(a, b, (sum - 1) / 2, 0, as, 0, bs, false); 22 | } 23 | 24 | public static double find(List a, List b, int k, int la, int ha, int lb, int hb, boolean odd) { 25 | double r = 0; 26 | return r; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/interview/google/MissingRanges.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | /** 8 | * https://leetcode.com/explore/interview/card/google/59/array-and-strings/3055 9 | */ 10 | public class MissingRanges { 11 | 12 | public List> findMissingRanges(int[] nums, int lower, int upper) { 13 | final List> result = new ArrayList<>(); 14 | if (nums.length == 0) { 15 | result.add(getList(lower, upper)); 16 | return result; 17 | } 18 | 19 | int low = lower, high = upper, i = 0; 20 | 21 | while (i < nums.length) { 22 | if (nums[i] > low) { 23 | result.add(getList(low, nums[i] - 1)); 24 | low = nums[i] + 1; 25 | } else if (nums[i] == low) { 26 | low = nums[i] + 1; 27 | } 28 | i++; 29 | } 30 | 31 | if (low <= upper) { 32 | result.add(getList(low, high)); 33 | } 34 | 35 | return result; 36 | } 37 | 38 | private List getList(int lower, int upper) { 39 | return Arrays.asList(lower, upper); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/interview/google/NthSmallestMulFromSet.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.TreeMap; 4 | 5 | /** 6 | * Find the n-th smallest multiple given a set of numbers. For example, set = 7 | * {4, 6}, n = 6. The sequence is: 4, 6, 8, 12, 16, 18, etc... Answer is 18. 8 | * 9 | * Link: http://www.careercup.com/question?id=5686055997014016 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class NthSmallestMulFromSet { 14 | 15 | // O(n*log(m)). M is size of set. 16 | public static int get(int[] set, int n) { 17 | TreeMap map = new TreeMap<>(); 18 | for (int a : set) { 19 | map.put(a, a); 20 | } 21 | int num = 0; 22 | while (n > 0) { 23 | num = map.firstKey(); 24 | int value = map.get(num); 25 | map.remove(num); 26 | if (!map.containsKey(num + value)) { 27 | map.put(num + value, value); 28 | } else { 29 | map.put(num + 2 * value, value); 30 | } 31 | n--; 32 | } 33 | System.out.println(num); 34 | return num; 35 | } 36 | 37 | public static void main(String[] args) { 38 | int[] set = { 2, 3 }; 39 | get(set, 6); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/interview/google/PlusOne.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | /** 4 | * https://leetcode.com/explore/interview/card/google/59/array-and-strings/339 5 | */ 6 | public class PlusOne { 7 | 8 | public int[] plusOne(int[] digits) { 9 | int toAdd = 1; 10 | for (int i=digits.length-1; i>-1; i--) { 11 | if (toAdd == 1) { 12 | if (digits[i] != 9) { 13 | digits[i] = digits[i] + 1; 14 | toAdd = 0; 15 | break; 16 | } else { 17 | digits[i] = 0; 18 | } 19 | } 20 | } 21 | 22 | if (toAdd !=0) { 23 | int [] result = new int[digits.length + 1]; 24 | result[0] = 1; 25 | for (int i=0; i maxL) { 16 | maxL = height[i]; 17 | } 18 | } 19 | 20 | for (int j=height.length-1; j>=0; j--) { 21 | maxRight[j] = maxR; 22 | if (height[j] > maxR) { 23 | maxR = height[j]; 24 | } 25 | } 26 | 27 | for (int i=1; i uniqueEmails = new HashSet<>(); 13 | for (String email : emails) { 14 | final String[] emailWithSplitLocalDomain = email.split("@"); 15 | final String domain = emailWithSplitLocalDomain[1]; 16 | final String normalizedLocal = getNormalizedLocal(emailWithSplitLocalDomain[0]); 17 | uniqueEmails.add(normalizedLocal + "@" + domain); 18 | } 19 | return uniqueEmails.size(); 20 | } 21 | 22 | private static String getNormalizedLocal(final String local) { 23 | final String localWithoutPeriods = local.replace(".", ""); 24 | return localWithoutPeriods.split("\\+")[0]; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/interview/google/ValidParentheses.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.ArrayDeque; 4 | 5 | /** 6 | * https://leetcode.com/explore/interview/card/google/59/array-and-strings/467 7 | */ 8 | public class ValidParentheses { 9 | 10 | public boolean isValid(String s) { 11 | final ArrayDeque q = new ArrayDeque<>(); 12 | 13 | for (char c: s.toCharArray()) { 14 | if (c == '(' || c == '{' || c == '[') { 15 | q.addFirst(c); 16 | } else { 17 | if (q.size() == 0 || !matchParenthesis(q.pollFirst(), c)) { 18 | return false; 19 | } 20 | } 21 | } 22 | 23 | return q.size() == 0; 24 | } 25 | 26 | private boolean matchParenthesis(char open, char close) { 27 | if ((open == '(' && close != ')') || (open == '{' && close != '}') || (open == '[' && close != ']')) { 28 | return false; 29 | } 30 | 31 | return true; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/interview/google/WaveArray.java: -------------------------------------------------------------------------------- 1 | package interview.google; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | 6 | /** 7 | * Link: https://www.interviewbit.com/problems/wave-array/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class WaveArray { 12 | 13 | public static ArrayList wave(ArrayList a) { 14 | if (a == null || a.isEmpty() || a.size() == 1) 15 | return a; 16 | Collections.sort(a); 17 | int i = 1, j = a.size() - 1; 18 | while ( i < j ) { 19 | int t = a.get(i); 20 | a.set(i, a.get(j)); 21 | a.set(j, t); 22 | i += 2; 23 | j -= 2; 24 | } 25 | return a; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/interview/microsoft/IntegerAverage.java: -------------------------------------------------------------------------------- 1 | package interview.microsoft; 2 | 3 | /** 4 | * The definition of integer average is the highest smaller integer if average 5 | * is floating point number. Also the condition is that they can not use any 6 | * type casting or any data type other than int. 7 | * 8 | * Example: a = 4, b = 5, avg = 4 a = 4, b = 6, avg = 5 a = -4, b = -6, avg = -5 9 | * a = 4, b = -5, avg = -1 a = -4, b = -5, avg = -5 10 | * 11 | * Link: https://leetcode.com/discuss/85484/find-integer-average-of-2-integers 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class IntegerAverage { 16 | 17 | public static int average(int a, int b) { 18 | int sum = a + b; 19 | if(sum < 0 && sum%2==-1) 20 | return (sum / 2) - 1; 21 | else 22 | return sum/2; 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println(average(2, 3)); 27 | System.out.println(average(2, -6)); 28 | System.out.println(average(-5, -2)); 29 | System.out.println(average(-6, 7)); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/interview/microsoft/ReverseDoublyLinkList.java: -------------------------------------------------------------------------------- 1 | package interview.microsoft; 2 | 3 | /** 4 | * Given a Doubly Linked List. Reverse it such that all the nodes are pointing 5 | * in the reverse direction. Can you do it in-place? 6 | * 7 | * Link: https://leetcode.com/discuss/79766/reverse-a-doubly-link-list 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class ReverseDoublyLinkList { 12 | 13 | public static void reverse(DoublyLinkedList list) { 14 | Link curr = list.first; 15 | Link prev = curr.prev; 16 | Link next = curr.next; 17 | while(curr!=null) { 18 | curr.next = prev; 19 | curr.prev = next; 20 | curr = next; 21 | prev = curr.prev; 22 | next = curr.next; 23 | } 24 | } 25 | 26 | class DoublyLinkedList { 27 | private Link first; 28 | } 29 | 30 | public class Link { 31 | private Link prev; 32 | private Link next; 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/main/java/interview/twitter/Kraken.java: -------------------------------------------------------------------------------- 1 | package interview.twitter; 2 | 3 | /** 4 | * Find out all the ways to reach from top left corner to bottom right corner of 5 | * a matrix if we are allowed to move down, right and diagonally down. 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class Kraken { 10 | 11 | public static int krakenCount(int m, int n) { 12 | if (m == 0 && n == 0) 13 | return 0; 14 | 15 | int[][] dp = new int[m][n]; 16 | for (int i = 0; i < m; i++) 17 | dp[i][0] = 1; 18 | for (int i = 0; i < n; i++) 19 | dp[0][i] = 1; 20 | 21 | for (int i = 1; i < m; i++) { 22 | for (int j = 1; j < n; j++) { 23 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + dp[i - 1][j - 1]; 24 | } 25 | } 26 | 27 | return dp[m - 1][n - 1]; 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(krakenCount(2, 2)); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/interview/visa/data.txt: -------------------------------------------------------------------------------- 1 | This is just a text file Yes file is a text file now search for things in file -------------------------------------------------------------------------------- /src/main/java/leetcode/ListNode.java: -------------------------------------------------------------------------------- 1 | package leetcode; 2 | 3 | public class ListNode { 4 | public int val; 5 | public ListNode next; 6 | 7 | public ListNode(int x) { 8 | val = x; 9 | } 10 | 11 | @Override 12 | public String toString() { 13 | return "ListNode{" + 14 | "val=" + val + 15 | ", next=" + next + 16 | '}'; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/leetcode/competition/LicenseKeyFormatting.java: -------------------------------------------------------------------------------- 1 | package leetcode.competition; 2 | 3 | public class LicenseKeyFormatting { 4 | 5 | public static String licenseKeyFormatting(String S, int K) { 6 | String s = S.toUpperCase(); 7 | StringBuilder sb = new StringBuilder(); 8 | for (char c : s.toCharArray()) { 9 | if (c != '-') 10 | sb.append(c); 11 | } 12 | int l = sb.length(); 13 | for (int i = l - K; i > 0; i -= K) 14 | sb.insert(i, '-'); 15 | return sb.toString(); 16 | } 17 | 18 | public static void main(String[] args) { 19 | System.out.println(licenseKeyFormatting("2-4A0r7-4k", 1)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/leetcode/competition/MagicalString.java: -------------------------------------------------------------------------------- 1 | package leetcode.competition; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class MagicalString { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(magicalString(17)); 10 | } 11 | 12 | public static int magicalString(int n) { 13 | if (n <= 0) 14 | return 0; 15 | if (n < 3) 16 | return 1; 17 | List l = new ArrayList<>(); 18 | l.add(1); 19 | l.add(2); 20 | l.add(2); 21 | int i = 2, v = 1; 22 | while (l.size() < n) { 23 | if (l.get(i) == 2) { 24 | l.add(v); 25 | l.add(v); 26 | } else { 27 | l.add(v); 28 | } 29 | i++; 30 | v = v == 1 ? 2 : 1; 31 | } 32 | int r = 0; 33 | for (i = 0; i < n; i++) { 34 | if (l.get(i) == 1) 35 | r++; 36 | } 37 | return r; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/leetcode/competition/NumberComplement.java: -------------------------------------------------------------------------------- 1 | package leetcode.competition; 2 | 3 | public class NumberComplement { 4 | 5 | public static int findComplement(int num) { 6 | String n = Integer.toBinaryString(num); 7 | String s = ""; 8 | for (char c : n.toCharArray()) { 9 | if (c == '0') 10 | s += '1'; 11 | else 12 | s += '0'; 13 | } 14 | return Integer.parseInt(s,2); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/E108_ConvertSortedArrayToBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | /** 4 | * Link: 5 | * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class E108_ConvertSortedArrayToBinarySearchTree { 10 | 11 | public static TreeNode sortedArrayToBST(int[] nums) { 12 | if (nums == null || nums.length == 0) 13 | return null; 14 | return populateTree(nums, 0, nums.length - 1); 15 | } 16 | 17 | private static TreeNode populateTree(int[] nums, int l, int h) { 18 | if (l > h) 19 | return null; 20 | int m = l + (h - l) / 2; 21 | TreeNode r = new TreeNode(nums[m]); 22 | r.left = populateTree(nums, l, m - 1); 23 | r.right = populateTree(nums, m + 1, h); 24 | return r; 25 | } 26 | 27 | @SuppressWarnings("unused") 28 | private static class TreeNode { 29 | int val; 30 | TreeNode left; 31 | TreeNode right; 32 | 33 | TreeNode(int x) { 34 | val = x; 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/E144_BinaryTreePreorderTraversal.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Link: https://leetcode.com/problems/binary-tree-preorder-traversal 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class E144_BinaryTreePreorderTraversal { 12 | 13 | public static List preorderTraversal(TreeNode root) { 14 | List l = new ArrayList<>(); 15 | if (root != null) 16 | preorder(root, l); 17 | return l; 18 | } 19 | 20 | public static void preorder(TreeNode n, List l) { 21 | l.add(n.val); 22 | if (n.left != null) 23 | preorder(n.left, l); 24 | if (n.right != null) 25 | preorder(n.right, l); 26 | } 27 | 28 | private static class TreeNode { 29 | int val; 30 | TreeNode left; 31 | TreeNode right; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/E14_LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/longest-common-prefix 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class E14_LongestCommonPrefix extends TestCase { 13 | 14 | public String longestCommonPrefix(String[] strs) { 15 | String res = ""; 16 | if(strs.length>0) 17 | res = strs[0]; 18 | for(int i=1; i stack = new Stack(); 18 | for(char c : s.toCharArray()) { 19 | if(c=='(' || c=='{' || c=='[') 20 | stack.push(c); 21 | else { 22 | if(stack.empty()) 23 | return false; 24 | Character p = stack.pop(); 25 | char v = p.charValue(); 26 | if((v=='(' && c!=')') || (v=='{' && c!='}') || (v=='[' && c!=']')) 27 | return false; 28 | } 29 | } 30 | return stack.isEmpty(); 31 | } 32 | 33 | @Test 34 | public void test() { 35 | E20_ValidParenthesis vp = new E20_ValidParenthesis(); 36 | //assertEquals(true, vp.isValid("")); 37 | //assertEquals(true, vp.isValid("[{((()))}]")); 38 | assertEquals(false, vp.isValid("([)]")); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/E268_MissingNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/missing-number 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class E268_MissingNumber extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(2, missingNumber(new int[]{0,1,3})); 17 | assertEquals(0, missingNumber(new int[]{1,2,3})); 18 | assertEquals(7, missingNumber(new int[]{0,1,2,3,4,5,6,8,9})); 19 | } 20 | 21 | public static int missingNumber(int[] nums) { 22 | int r = 0; 23 | for(int i=0; i inorderTraversal(TreeNode root) { 14 | List l = new ArrayList<>();; 15 | if (root != null) 16 | parse(root, l); 17 | return l; 18 | } 19 | 20 | public static void parse(TreeNode root, List l) { 21 | if (root.left != null) 22 | parse(root.left, l); 23 | l.add(root.val); 24 | if (root.right != null) 25 | parse(root.right, l); 26 | } 27 | 28 | private static class TreeNode { 29 | int val; 30 | TreeNode left; 31 | TreeNode right; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/leetcode/easy/E70_ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package leetcode.easy; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/climbing-stairs 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class E70_ClimbingStairs extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(3, climbStairs(3)); 17 | } 18 | 19 | public static int climbStairs(int n) { 20 | if (n==0 || n==1 || n==2) 21 | return n; 22 | int[] dp = new int[n]; 23 | dp[0] = 1; 24 | dp[1] = 2; 25 | for (int i = 2; i < n; i++) 26 | dp[i] = dp[i - 1] + dp[i - 2]; 27 | return dp[n - 1]; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/hard/H327_CountOfRangeSum.java: -------------------------------------------------------------------------------- 1 | package leetcode.hard; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/count-of-range-sum 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class H327_CountOfRangeSum extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | } 17 | 18 | public static int countRangeSum(int[] nums, int lower, int upper) { 19 | return 0; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/leetcode/hard/H330_PatchingArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.hard; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/patching-array 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class H330_PatchingArray extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(1, minPatches(new int[] { 1, 3 }, 6)); 17 | assertEquals(2, minPatches(new int[] { 1, 5, 10 }, 20)); 18 | } 19 | 20 | public static int minPatches(int[] nums, int n) { 21 | int r = 0, i = 0; 22 | long miss = 1; 23 | while (miss <= n) { 24 | if (i < nums.length && nums[i] <= miss) { 25 | miss += nums[i]; 26 | i++; 27 | } else { 28 | miss += miss; 29 | r++; 30 | } 31 | } 32 | return r; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/hard/H41_FirstMissingPositive.java: -------------------------------------------------------------------------------- 1 | package leetcode.hard; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/first-missing-positive 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class H41_FirstMissingPositive extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(3, firstMissingPositive(new int[] { 1, 2, 0 })); 17 | assertEquals(2, firstMissingPositive(new int[] { 3, 4, -1, 1 })); 18 | assertEquals(6, firstMissingPositive(new int[] { 1, 3, 4, -1, 1, 5, 2 })); 19 | assertEquals(8, firstMissingPositive(new int[] { 1, 2, 3, 5, 4, 6, 7 })); 20 | } 21 | 22 | public static int firstMissingPositive(int[] nums) { 23 | if (nums == null || nums.length == 0) 24 | return 1; 25 | for (int i = 0; i < nums.length; i++) 26 | while (nums[i] > 0 && nums[i] < nums.length && nums[nums[i] - 1] != nums[i]) { 27 | int temp = nums[i]; 28 | nums[i] = nums[nums[i] - 1]; 29 | nums[temp - 1] = temp; 30 | } 31 | for (int i = 0; i < nums.length; i++) 32 | if (nums[i] != i + 1) 33 | return i + 1; 34 | return nums.length + 1; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/leetcode/hard/H4_SortedArrayMedian.java: -------------------------------------------------------------------------------- 1 | package leetcode.hard; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/median-of-two-sorted-arrays 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class H4_SortedArrayMedian { 9 | 10 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 11 | return getMedian(nums1, 0, nums1.length, nums2, 0, nums2.length, (nums1.length + nums2.length - 1) / 2); 12 | } 13 | 14 | private double getMedian(int[] a, int al, int ah, int[] b, int bl, int bh, int i) { 15 | if (i == 0) 16 | return calculateMedian(a, al, ah, b, bl, bh); 17 | int am = al + (ah - al - 1) / 2; 18 | int bm = bl + (bh - bl - 1) / 2; 19 | if (a[am] < b[bm]) 20 | return getMedian(a, am, ah, b, bl, bh, i - am); 21 | else 22 | return getMedian(a, al, ah, b, bm, bh, i - bm); 23 | } 24 | 25 | private double calculateMedian(int[] a, int al, int ah, int[] b, int bl, int bh) { 26 | return 0; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M116_PopulatingNextRightPointersInEachNode.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /** 7 | * Link: 8 | * https://leetcode.com/problems/populating-next-right-pointers-in-each-node 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M116_PopulatingNextRightPointersInEachNode { 13 | 14 | public static void connect(TreeLinkNode root) { 15 | if (root == null) 16 | return; 17 | Queue q = new LinkedList<>(); 18 | root.next = null; 19 | q.add(root); 20 | q.add(null); 21 | while (!q.isEmpty()) { 22 | TreeLinkNode n = q.poll(); 23 | if (n != null) { 24 | n.next = q.peek(); 25 | q.add(n.left); 26 | q.add(n.right); 27 | if (q.peek() == null) 28 | q.add(null); 29 | } 30 | } 31 | } 32 | 33 | @SuppressWarnings("unused") 34 | private static class TreeLinkNode { 35 | int val; 36 | TreeLinkNode left, right, next; 37 | 38 | TreeLinkNode(int x) { 39 | val = x; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M117_PopulatingNextRightPointersInEachNodeII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /** 7 | * Link: https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class M117_PopulatingNextRightPointersInEachNodeII { 12 | 13 | public void connect(TreeLinkNode root) { 14 | if (root == null) 15 | return; 16 | Queue q = new LinkedList<>(); 17 | root.next = null; 18 | q.add(root); 19 | q.add(null); 20 | while (!q.isEmpty()) { 21 | TreeLinkNode n = q.poll(); 22 | if (n != null) { 23 | n.next = q.peek(); 24 | if (n.left != null) 25 | q.add(n.left); 26 | if (n.right != null) 27 | q.add(n.right); 28 | if (q.peek() == null) 29 | q.add(null); 30 | } 31 | } 32 | } 33 | 34 | class TreeLinkNode { 35 | int val; 36 | TreeLinkNode left, right, next; 37 | 38 | TreeLinkNode(int x) { 39 | val = x; 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M11_ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Leetcode: https://leetcode.com/problems/container-with-most-water 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M11_ContainerWithMostWater extends TestCase { 13 | 14 | public int maxArea(int[] height) { 15 | int res=0, temp=0; 16 | int i=0, j=height.length-1; 17 | while(i 0 ? prices[i + 1] - prices[i] : 0; 16 | return r; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M167_TwoSumIIInputArraySorted.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M167_TwoSumIIInputArraySorted { 9 | 10 | public static int[] twoSum(int[] numbers, int target) { 11 | int l = 0, h = numbers.length - 1; 12 | while (l < h) { 13 | int sum = numbers[l] + numbers[h]; 14 | if (sum == target) 15 | return new int[] { l + 1, h + 1 }; 16 | else if (sum < target) 17 | l++; 18 | else 19 | h--; 20 | } 21 | return new int[] { -1, -1 }; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M19_RemoveNthNodeFromEndOfLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/remove-nth-node-from-end-of-list 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M19_RemoveNthNodeFromEndOfLinkedList { 9 | 10 | public LNode removeNthFromEnd(LNode head, int n) { 11 | LNode cur = head; 12 | LNode sec = head; 13 | 14 | while (n != 0) { 15 | cur = cur.next; 16 | n--; 17 | } 18 | 19 | if (cur == null) 20 | return head.next; 21 | 22 | while (cur.next != null) { 23 | cur = cur.next; 24 | sec = sec.next; 25 | } 26 | LNode temp = sec.next; 27 | sec.next = sec.next.next; 28 | temp.next = null; 29 | return head; 30 | } 31 | 32 | } 33 | 34 | class LNode { 35 | 36 | int val; 37 | LNode next; 38 | 39 | LNode(int x) { 40 | val = x; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M201_BitwiseAndOfNumbersRange.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/bitwise-and-of-numbers-range 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M201_BitwiseAndOfNumbersRange extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(5, rangeBitwiseAnd(5, 5)); 17 | assertEquals(4, rangeBitwiseAnd(5, 7)); 18 | assertEquals(10231880, rangeBitwiseAnd(10231881, 10231882)); 19 | } 20 | 21 | public static int rangeBitwiseAnd(int m, int n) { 22 | int diff = m ^ n, maskBits = 0; 23 | while (diff > 0) { 24 | diff = diff>>1; 25 | maskBits++; 26 | } 27 | int mask = (Integer.MAX_VALUE >> maskBits) << maskBits; 28 | return n & mask; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M216_CombinationSumIII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Link: https://leetcode.com/problems/combination-sum-iii 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class M216_CombinationSumIII { 12 | 13 | public static List> combinationSum3(int k, int n) { 14 | List> r = new ArrayList>(); 15 | cs(k, n, 1, new ArrayList(), r); 16 | return r; 17 | } 18 | 19 | public static void cs(int k, int sum, int n, List l, List> r) { 20 | if (sum == 0 && k==0) { 21 | r.add(new ArrayList<>(l)); 22 | return; 23 | } 24 | 25 | if (k == 0) 26 | return; 27 | 28 | for (int i = n; i < 10; i++) { 29 | if (i <= sum) { 30 | l.add(i); 31 | cs(k - 1, sum - i, i + 1, l, r); 32 | l.remove(l.size()-1); 33 | } else { 34 | break; 35 | } 36 | } 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M22_GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Leetcode: https://leetcode.com/problems/generate-parentheses 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class M22_GenerateParentheses { 12 | 13 | public List generateParenthesis(int n) { 14 | List res = new ArrayList<>(); 15 | generate(n, n, "", res); 16 | return res; 17 | } 18 | 19 | public void generate(int no, int nc, String s, List res) { 20 | if (no == 0 && nc == 0) { 21 | res.add(s); 22 | return; 23 | } 24 | if (no > 0) 25 | generate(no - 1, nc, s + "(", res); 26 | if (nc > no) 27 | generate(no, nc - 1, s + ")", res); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M238_ProductOfArrayExceptSelf.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/product-of-array-except-self 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M238_ProductOfArrayExceptSelf { 9 | 10 | public static void main(String[] args) { 11 | int[] a = productExceptSelf(new int[] { 1, 2, 3, 4 }); 12 | for (int aa : a) 13 | System.out.print(aa + " "); 14 | } 15 | 16 | public static int[] productExceptSelf(int[] nums) { 17 | int[] r = new int[nums.length], a1 = new int[nums.length], a2 = new int[nums.length]; 18 | a1[0] = 1; 19 | a2[a2.length - 1] = 1; 20 | for (int i = 1; i < nums.length; i++) 21 | a1[i] = a1[i - 1] * nums[i - 1]; 22 | 23 | for (int i = nums.length - 1; i > 0; i--) 24 | a2[i - 1] = a2[i] * nums[i]; 25 | 26 | for (int i = 0; i < nums.length; i++) 27 | r[i] = a1[i] * a2[i]; 28 | 29 | return r; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M24_SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import leetcode.ListNode; 4 | 5 | /** 6 | * Link: https://leetcode.com/problems/swap-nodes-in-pairs 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class M24_SwapNodesInPairs { 11 | 12 | public ListNode swapPairs(ListNode head) { 13 | if (head == null || head.next == null) 14 | return head; 15 | head = swap(head, head.next); 16 | ListNode start = head.next; 17 | while (start != null && start.next != null) { 18 | ListNode temp = swap(start.next, start.next.next); 19 | start.next = temp; 20 | start = temp.next; 21 | } 22 | return head; 23 | } 24 | 25 | public ListNode swap(ListNode f, ListNode s) { 26 | if (f != null && s == null) 27 | return f; 28 | else { 29 | ListNode temp = s.next; 30 | s.next = f; 31 | f.next = temp; 32 | return s; 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M260_SingleNumberIII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/single-number-iii 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M260_SingleNumberIII extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(5, singleNumber(new int[] { 3, 5 })[0]); 17 | } 18 | 19 | public static int[] singleNumber(int[] nums) { 20 | int x = 0, mask = 1; 21 | for (int i = 0; i < nums.length; i++) 22 | x ^= nums[i]; 23 | 24 | // First 1 bit from right. 25 | while ((x & mask) == 0) 26 | mask = mask << 1; 27 | 28 | int n1 = 0, n2 = 0; 29 | for (int i = 0; i < nums.length; i++) { 30 | if ((nums[i] & mask) == 0) 31 | n1 ^= nums[i]; 32 | else 33 | n2 ^= nums[i]; 34 | } 35 | 36 | return new int[] { n1, n2 }; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M287_FindTheDuplicateNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/find-the-duplicate-number 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M287_FindTheDuplicateNumber { 9 | 10 | public int findDuplicate(int[] nums) { 11 | int slow = 0; 12 | int fast = 0; 13 | 14 | do { 15 | slow = nums[slow]; 16 | fast = nums[nums[fast]]; 17 | } while (slow != fast); 18 | 19 | int find = 0; 20 | 21 | while (find != slow) { 22 | slow = nums[slow]; 23 | find = nums[find]; 24 | } 25 | return find; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M2_AddTwoNumbers.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import leetcode.ListNode; 4 | 5 | /** 6 | * Link: https://leetcode.com/problems/add-two-numbers 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class M2_AddTwoNumbers { 11 | 12 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 | return addTwoNumbers(l1, l2, 0); 14 | } 15 | 16 | public ListNode addTwoNumbers(ListNode l1, ListNode l2, int carry) { 17 | if (l1 == null && l2 == null) 18 | return carry != 0 ? new ListNode(carry) : null; 19 | else { 20 | int sum = 0; 21 | if (l1 != null) { 22 | sum += l1.val; 23 | l1 = l1.next; 24 | } 25 | if (l2 != null) { 26 | sum += l2.val; 27 | l2 = l2.next; 28 | } 29 | if (carry != 0) 30 | sum += carry; 31 | int c = sum / 10; 32 | ListNode node = new ListNode(sum % 10); 33 | node.next = addTwoNumbers(l1, l2, c); 34 | return node; 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | ListNode l1 = new ListNode(1); 40 | l1.next = new ListNode(8); 41 | ListNode l2 = new ListNode(0); 42 | ListNode resultNode = new M2_AddTwoNumbers().addTwoNumbers(l1, l2); 43 | System.out.println(resultNode); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M313_SuperUglyNumber.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/super-ugly-number 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M313_SuperUglyNumber extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(1, nthSuperUglyNumber(1, new int[] { 2, 7, 13, 19 })); 17 | assertEquals(8, nthSuperUglyNumber(4, new int[] { 2 })); 18 | assertEquals(7, nthSuperUglyNumber(4, new int[] { 2, 7, 13, 19 })); 19 | } 20 | 21 | public static int nthSuperUglyNumber(int n, int[] primes) { 22 | int[] r = new int[n]; 23 | int[] times = new int[primes.length]; 24 | r[0] = 1; 25 | for (int i = 1; i < n; i++) { 26 | r[i] = Integer.MAX_VALUE; 27 | for (int j = 0; j < primes.length; j++) 28 | r[i] = Math.min(r[i], primes[j] * r[times[j]]); 29 | for (int j = 0; j < primes.length; j++) 30 | if ((primes[j] * r[times[j]]) == r[i]) 31 | times[j]++; 32 | } 33 | return r[n - 1]; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M318_MaximumProductOfWordLengths.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/maximum-product-of-word-lengths 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M318_MaximumProductOfWordLengths extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(16, maxProduct(new String[] { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" })); 17 | assertEquals(0, maxProduct(new String[] {"a", "aa", "aaa", "aaaa"})); 18 | } 19 | 20 | public static int maxProduct(String[] words) { 21 | int[] a = new int[words.length]; 22 | // Setting j'th bit as 1. 23 | for (int i = 0; i < words.length; i++) 24 | for (int j = 0; j < words[i].length(); j++) 25 | a[i] |= 1 << (words[i].charAt(j) - 'a'); 26 | 27 | int r = 0; 28 | for (int i = 0; i < words.length; i++) 29 | for (int j = i + 1; j < words.length; j++) 30 | r = (a[i] & a[j]) == 0 ? Math.max(words[i].length() * words[j].length(), r) : r; 31 | 32 | return r; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M319_BulbSwitcher.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/bulb-switcher 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M319_BulbSwitcher { 9 | 10 | /* 11 | * Any number with even number of factors will be off at the end. Since 12 | * factors exists in pairs (1,n), (2, n/2)..etc. Hence only the numbers that 13 | * are perfect squares till n will be on by the end. 14 | */ 15 | public static int bulbSwitch(int n) { 16 | return (int)Math.sqrt(n); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M31_NextPermutation.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Arrays; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Leetcode: https://leetcode.com/problems/next-permutation 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M31_NextPermutation extends TestCase { 13 | 14 | public void nextPermutation(int[] nums) { 15 | boolean solExists = false; 16 | outer: 17 | for (int i = nums.length - 2; i >= 0; i--) { 18 | for (int j = nums.length - 1; j > i; j--) { 19 | if (nums[j] > nums[i]) { 20 | swap(nums, j, i); 21 | Arrays.sort(nums, i+1, nums.length); 22 | solExists = true; 23 | break outer; 24 | } 25 | } 26 | } 27 | if(!solExists) { 28 | Arrays.sort(nums); 29 | } 30 | 31 | } 32 | 33 | public void swap(int[] nums, int i, int j) { 34 | int temp = nums[i]; 35 | nums[i] = nums[j]; 36 | nums[j] = temp; 37 | } 38 | 39 | public static void main(String[] args) { 40 | int[] nums = new int[] {1,3,2}; 41 | new M31_NextPermutation().nextPermutation(nums); 42 | for(int n : nums) 43 | System.out.print(n + " "); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M322_CoinChange.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Link: https://leetcode.com/problems/coin-change 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class M322_CoinChange { 11 | 12 | public static int coinChange(int[] coins, int amount) { 13 | if(coins.length==0) 14 | return -1; 15 | int[] cc = new int[amount + 1]; 16 | Arrays.fill(cc, Integer.MAX_VALUE - 1); 17 | cc[0] = 0; 18 | for ( int j=0; j = coins[j] )) { 21 | cc[i] = Math.min(cc[i], 1 + cc[i - coins[j]]); 22 | } 23 | } 24 | } 25 | return cc[amount] == Integer.MAX_VALUE - 1 ? -1 : cc[amount]; 26 | } 27 | 28 | public static void main(String[] args) { 29 | int[] a = { 186, 419, 83, 408 }; 30 | System.out.println(coinChange(a, 6249)); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M328_OddEvenLinkedList.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import leetcode.ListNode; 4 | 5 | /** 6 | * Link: https://leetcode.com/problems/odd-even-linked-list 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class M328_OddEvenLinkedList { 11 | 12 | public static ListNode oddEvenList(ListNode head) { 13 | if (head == null || head.next == null) 14 | return head; 15 | ListNode odd = head; 16 | ListNode feven = odd.next; 17 | ListNode even = odd.next; 18 | while (true) { 19 | if (even != null) { 20 | if (even.next == null) { 21 | odd.next = feven; 22 | break; 23 | } else { 24 | odd.next = even.next; 25 | odd = odd.next; 26 | } 27 | } else { 28 | odd.next = feven; 29 | break; 30 | } 31 | even.next = odd.next; 32 | even = even.next; 33 | } 34 | return head; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M343_IntegerBreak.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/integer-break 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M343_IntegerBreak extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(1, integerBreak(2)); 17 | assertEquals(2, integerBreak(3)); 18 | assertEquals(4, integerBreak(4)); 19 | assertEquals(6, integerBreak(5)); 20 | assertEquals(9, integerBreak(6)); 21 | assertEquals(12, integerBreak(7)); 22 | assertEquals(18, integerBreak(8)); 23 | } 24 | 25 | public static int integerBreak(int n) { 26 | if (n == 2) 27 | return 1; 28 | if (n == 3) 29 | return 2; 30 | if (n == 4) 31 | return 4; 32 | 33 | if (n % 3 == 2) { 34 | return (int) Math.pow(3, n / 3) * 2; 35 | } else if (n % 3 == 1) { 36 | return (int) Math.pow(3, n / 3 - 1) * 4; 37 | } else { 38 | return (int) Math.pow(3, n / 3); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M357_CountNumbersWithUniqueDigits.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/count-numbers-with-unique-digits 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M357_CountNumbersWithUniqueDigits extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(1, countNumbersWithUniqueDigits(0)); 17 | assertEquals(10, countNumbersWithUniqueDigits(1)); 18 | assertEquals(91, countNumbersWithUniqueDigits(2)); 19 | assertEquals(739, countNumbersWithUniqueDigits(3)); 20 | } 21 | 22 | public static int countNumbersWithUniqueDigits(int n) { 23 | int r = 1, p = 9, l = 9; 24 | for (int i = 0; i < n; i++) { 25 | r += p; 26 | p *= l; 27 | l--; 28 | } 29 | return r; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M375_GuessNumberHigherOrLowerII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/guess-number-higher-or-lower-ii 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M375_GuessNumberHigherOrLowerII extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(0, getMoneyAmount(1)); 17 | assertEquals(1, getMoneyAmount(2)); 18 | assertEquals(2, getMoneyAmount(3)); 19 | assertEquals(4, getMoneyAmount(4)); 20 | assertEquals(6, getMoneyAmount(5)); 21 | assertEquals(8, getMoneyAmount(6)); 22 | } 23 | 24 | public static int getMoneyAmount(int n) { 25 | return get(new int[n + 1][n + 1], 1, n); 26 | } 27 | 28 | // Top Down DP 29 | public static int get(int[][] dp, int s, int e) { 30 | if (s >= e) 31 | return 0; 32 | if (dp[s][e] != 0) 33 | return dp[s][e]; 34 | int r = Integer.MAX_VALUE; 35 | for (int i = s; i <= e; i++) 36 | r = Math.min(r, i + Math.max(get(dp, s, i - 1), get(dp, i + 1, e))); 37 | dp[s][e] = r; 38 | return r; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M384_ShuffleAnArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Link: https://leetcode.com/problems/shuffle-an-array 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class M384_ShuffleAnArray { 11 | 12 | private int[] a; 13 | private int[] n; 14 | 15 | public M384_ShuffleAnArray(int[] nums) { 16 | this.a = Arrays.copyOf(nums, nums.length); 17 | this.n = nums; 18 | } 19 | 20 | /** Resets the array to its original configuration and return it. */ 21 | public int[] reset() { 22 | return n; 23 | } 24 | 25 | /** Returns a random shuffling of the array. */ 26 | public int[] shuffle() { 27 | for (int i=1; i < n.length; i++) { 28 | int index = (int)((i + 1) * Math.random()); 29 | int temp = a[index]; 30 | a[index] = a[i]; 31 | a[i] = temp; 32 | } 33 | return a; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M388_LongestAbsoluteFilePath.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/longest-absolute-file-path 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M388_LongestAbsoluteFilePath { 9 | 10 | public static int lengthLongestPath(String input) { 11 | if (input == null || input.isEmpty() || !input.contains(".")) 12 | return 0; 13 | int n = 0; 14 | return n; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M390_EliminationGame.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/elimination-game 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M390_EliminationGame extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(1, lastRemaining(1)); 17 | assertEquals(2, lastRemaining(2)); 18 | assertEquals(2, lastRemaining(3)); 19 | assertEquals(2, lastRemaining(4)); 20 | assertEquals(2, lastRemaining(5)); 21 | assertEquals(4, lastRemaining(6)); 22 | assertEquals(4, lastRemaining(7)); 23 | assertEquals(6, lastRemaining(8)); 24 | assertEquals(6, lastRemaining(9)); 25 | } 26 | 27 | public static int lastRemaining(int n) { 28 | int s = 1, c = 1, size = n; 29 | boolean toRight = true; 30 | while (size > 1) { 31 | if (toRight) { 32 | s += c; 33 | } else { 34 | if (size % 2 == 1) 35 | s += c; 36 | } 37 | size /= 2; 38 | c *= 2; 39 | toRight = !toRight; 40 | } 41 | return s; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M3_LongestSubstringWithoutRepeatingCharacters.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/longest-substring-without-repeating-characters 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M3_LongestSubstringWithoutRepeatingCharacters { 9 | 10 | int[] cc = new int[256]; 11 | 12 | public int lengthOfLongestSubstring(String s) { 13 | if(s==null || s.isEmpty()) 14 | return 0; 15 | int i=0,j=0, len=0; 16 | while(j len) 23 | len = j-i+1; 24 | j++; 25 | } 26 | return len; 27 | } 28 | 29 | public boolean hasRepetitions() { 30 | for(int i=0;i<256;i++) { 31 | if(cc[i]>1) 32 | return true; 33 | } 34 | return false; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M419_BattleshipsInABoard.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/battleships-in-a-board 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M419_BattleshipsInABoard { 9 | 10 | public static int countBattleships(char[][] board) { 11 | if (board == null || board.length == 0) 12 | return 0; 13 | 14 | int c = 0; 15 | for (int i = 0; i < board.length; i++) { 16 | for (int j = 0; j < board[0].length; j++) { 17 | if (board[i][j] == 'X') { 18 | c++; 19 | board[i][j] = '.'; 20 | uv(board, i, j); 21 | } 22 | } 23 | } 24 | return c; 25 | } 26 | 27 | public static void uv(char[][] b, int y, int x) { 28 | int i = y + 1, j = x + 1; 29 | while (i < b.length) { 30 | if (b[i][x] == 'X') { 31 | b[i][x] = '.'; 32 | i++; 33 | } else 34 | break; 35 | } 36 | 37 | while (j < b[0].length) { 38 | if (b[y][j] == 'X') { 39 | b[y][j] = '.'; 40 | j++; 41 | } else 42 | break; 43 | } 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M421_MaximumXOROfTwoNumbersInAnArray.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | import org.junit.Test; 7 | 8 | import junit.framework.TestCase; 9 | 10 | /** 11 | * Link: https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class M421_MaximumXOROfTwoNumbersInAnArray extends TestCase { 16 | 17 | @Test 18 | public void test() { 19 | assertEquals(28, findMaximumXOR(new int[] { 3, 10, 5, 25, 2, 8 })); 20 | } 21 | 22 | public static int findMaximumXOR(int[] nums) { 23 | int max = 0, mask = 0; 24 | for (int i = 31; i >= 0; i--) { 25 | mask = mask | (1 << i); 26 | Set set = new HashSet<>(); 27 | for (int num : nums) { 28 | set.add(num & mask); 29 | } 30 | int tmp = max | (1 << i); 31 | for (int prefix : set) { 32 | if (set.contains(tmp ^ prefix)) { 33 | max = tmp; 34 | break; 35 | } 36 | } 37 | } 38 | return max; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M452_MinimumNumberOfArrowsToBurstBalloons.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | import org.junit.Test; 7 | 8 | import junit.framework.TestCase; 9 | 10 | /** 11 | * Link: 12 | * https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons 13 | * 14 | * @author shivam.maharshi 15 | */ 16 | public class M452_MinimumNumberOfArrowsToBurstBalloons extends TestCase { 17 | 18 | @Test 19 | public void test() { 20 | assertEquals(2, findMinArrowShots(new int[][] { { 10, 16 }, { 2, 8 }, { 1, 6 }, { 7, 12 } })); 21 | } 22 | 23 | public static int findMinArrowShots(int[][] points) { 24 | int r = 0; 25 | Arrays.sort(points, new Comp()); 26 | for (int i = 0; i < points.length;) { 27 | r++; 28 | int h = points[i][1]; 29 | while (i < points.length && h >= points[i][0]) 30 | h = Math.min(points[i++][1], h); 31 | } 32 | return r; 33 | } 34 | 35 | private static class Comp implements Comparator { 36 | @Override 37 | public int compare(int[] o1, int[] o2) { 38 | return o1[0] < o2[0] ? -1 : 1; 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M454_FourSumII.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Link: https://leetcode.com/problems/4sum-ii 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class M454_FourSumII { 12 | 13 | // O(n^2) solution. Can do better with a O(nLog(n)) solution. 14 | public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { 15 | int c = 0; 16 | Map m = new HashMap<>(); 17 | for (int i = 0; i < A.length; i++) 18 | for (int j = 0; j < B.length; j++) { 19 | if (!m.containsKey(A[i] + B[j])) 20 | m.put(A[i] + B[j], 0); 21 | m.put(A[i] + B[j], m.get(A[i] + B[j]) + 1); 22 | } 23 | 24 | for (int i = 0; i < C.length; i++) 25 | for (int j = 0; j < D.length; j++) 26 | c += m.containsKey(-(C[i] + D[j])) ? m.get(-(C[i] + D[j])) : 0; 27 | 28 | return c; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M474_OnesAndZeroes.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/ones-and-zeroes 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M474_OnesAndZeroes extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(4, findMaxForm(new String[] { "10", "0001", "111001", "1", "0" }, 5, 3)); 17 | assertEquals(2, findMaxForm(new String[] { "10", "1", "0" }, 1, 1)); 18 | assertEquals(3, findMaxForm(new String[] { "11", "1", "1", "0" }, 1, 2)); 19 | } 20 | 21 | // Awesome Bottom Up DP backwards. 22 | public static int findMaxForm(String[] strs, int m, int n) { 23 | int[][] dp = new int[m + 1][n + 1]; 24 | for (String s : strs) { 25 | int[] c = count(s); 26 | for (int i = m; i >= c[0]; i--) 27 | for (int j = n; j >= c[1]; j--) 28 | dp[i][j] = Math.max(dp[i][j], 1 + dp[i - c[0]][j - c[1]]); 29 | } 30 | return dp[m][n]; 31 | } 32 | 33 | public static int[] count(String s) { 34 | int[] r = new int[2]; 35 | for (char c : s.toCharArray()) 36 | r[c - '0']++; 37 | return r; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M48_RotateImage.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/rotate-image 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M48_RotateImage { 9 | 10 | public static void main(String[] args) { 11 | int[][] m = {{1,2}, {3,4}}; 12 | rotate(m); 13 | } 14 | 15 | public static void rotate(int[][] matrix) { 16 | swapAcrossHorizontalAxis(matrix); 17 | transpose(matrix); 18 | } 19 | 20 | public static void swapAcrossHorizontalAxis(int[][] m) { 21 | int l = 0, h = m.length - 1; 22 | while (l < h) { 23 | for (int i = 0; i < m.length; i++) { 24 | int temp = m[l][i]; 25 | m[l][i] = m[h][i]; 26 | m[h][i] = temp; 27 | } 28 | l++; 29 | h--; 30 | } 31 | } 32 | 33 | public static void transpose(int[][] m) { 34 | for (int i = 0; i < m.length; i++) { 35 | for (int j = i; j < m.length; j++) { 36 | int temp = m[i][j]; 37 | m[i][j] = m[j][i]; 38 | m[j][i] = temp; 39 | } 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M50_Pow.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/powx-n 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M50_Pow extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(-64.0, myPow(-4, 3)); 17 | assertEquals(0.0, myPow(0, 1)); 18 | assertEquals(64.0, myPow(4, 3)); 19 | assertEquals(1.0, myPow(-4, 0)); 20 | assertEquals(0.04, myPow(-5, -2)); 21 | } 22 | 23 | public static double myPow(double x, int n) { 24 | return n >= 0 ? pow(x, n) : 1 / pow(x, n); 25 | } 26 | 27 | public static double pow(double x, int n) { 28 | if (n == 0) 29 | return 1; 30 | 31 | if (n == 1) 32 | return x; 33 | 34 | if (n % 2 == 0) { 35 | return pow(x * x, n / 2); 36 | } else { 37 | return pow(x * x, n / 2) * x; 38 | } 39 | 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M53_MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/maximum-subarray 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M53_MaximumSubarray { 9 | 10 | public int maxSubArray(int[] nums) { 11 | int res = Integer.MIN_VALUE, sum = 0; 12 | for (int i = 0; i < nums.length; i++) { 13 | sum += nums[i]; 14 | res = Math.max(res, sum); 15 | if (sum < 0) 16 | sum = 0; 17 | } 18 | return res; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M55_JumpGame.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/jump-game 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M55_JumpGame extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(true, canJump(new int[]{2})); 17 | assertEquals(true, canJump(new int[]{2,3})); 18 | assertEquals(false, canJump(new int[]{0,1})); 19 | assertEquals(true, canJump(new int[]{2,3,1,1,4})); 20 | assertEquals(false, canJump(new int[]{3,2,1,0,4})); 21 | } 22 | 23 | public static boolean canJump(int[] nums) { 24 | if (nums == null || nums.length == 0 || nums.length == 1) 25 | return true; 26 | int last = nums.length - 1; 27 | for (int i = nums.length - 2; i >= 0; i--) 28 | if (i + nums[i] >= last) 29 | last = i; 30 | return last == 0; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M62_UniquePaths.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/unique-paths 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M62_UniquePaths extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(1, uniquePaths(1, 1)); 17 | assertEquals(1, uniquePaths(1, 2)); 18 | assertEquals(1, uniquePaths(2, 1)); 19 | assertEquals(2, uniquePaths(2, 2)); 20 | } 21 | 22 | public static int uniquePaths(int m, int n) { 23 | int[][] dp = new int[m][n]; 24 | for (int i = 0; i < m; i++) 25 | dp[i][0] = 1; 26 | for (int i = 0; i < n; i++) 27 | dp[0][i] = 1; 28 | 29 | for (int i = 1; i < m; i++) 30 | for (int j = 1; j < n; j++) 31 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 32 | 33 | return dp[m-1][n-1]; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M64_MinPathSum.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * You can only move right, down or diagonal. 5 | * 6 | * Leetcode: https://leetcode.com/problems/minimum-path-sum 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class M64_MinPathSum { 11 | 12 | // Bottom up dynamic approach. 13 | public static int minPathSum(int[][] grid) { 14 | int h = grid.length; 15 | int w = grid[0].length; 16 | int[][] dp = new int[h][w]; 17 | dp[0][0] = grid[0][0]; 18 | for (int i = 1; i < h; i++) 19 | dp[i][0] = dp[i - 1][0] + grid[i][0]; 20 | for (int j = 1; j < w; j++) 21 | dp[0][j] = dp[0][j - 1] + grid[0][j]; 22 | 23 | for (int i = 1; i < h; i++) { 24 | for (int j = 1; j < w; j++) { 25 | dp[i][j] = grid[i][j] + Math.min(dp[i][j - 1], dp[i - 1][j]); 26 | } 27 | } 28 | return dp[h - 1][w - 1]; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M74_SearchA2DMatrix.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/search-a-2d-matrix 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M74_SearchA2DMatrix { 9 | 10 | public static boolean searchMatrix(int[][] matrix, int target) { 11 | int i = matrix.length - 1, j = 0; 12 | while (i>-1 && j target) { 16 | i--; 17 | j = 0; 18 | } else 19 | j++; 20 | } 21 | return false; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M75_SortColors.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Link: https://leetcode.com/problems/sort-colors 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class M75_SortColors { 11 | 12 | public static void main(String[] args) { 13 | int[] a = new int[]{1,0}; 14 | sortColors(a); 15 | System.out.println(Arrays.toString(a)); 16 | } 17 | 18 | // Single pass solution. 19 | public static void sortColors(int[] nums) { 20 | int l = 0, h = nums.length - 1, i = 0; 21 | while (i <= h) { 22 | if (nums[i] == 0) { 23 | if (l==i) { 24 | i++; 25 | l++; 26 | } else { 27 | if (nums[l] != 0) 28 | swap(nums, l, i); 29 | l++; 30 | } 31 | } else if (nums[i] == 2) { 32 | if (nums[h] != 2) 33 | swap(nums, i, h); 34 | h--; 35 | } else { 36 | i++; 37 | } 38 | } 39 | } 40 | 41 | public static void swap(int[] n, int l, int h) { 42 | int t = n[l]; 43 | n[l] = n[h]; 44 | n[h] = t; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M77_Combinations.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/combinations 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M77_Combinations { 13 | 14 | public static void main(String[] args) { 15 | List> r = combine(3, 2); 16 | for (List l : r) 17 | System.out.println(Arrays.toString(l.toArray())); 18 | } 19 | 20 | public static List> combine(int n, int k) { 21 | List> r = new ArrayList<>(); 22 | combine(n, k, 1, new ArrayList(), r); 23 | return r; 24 | } 25 | 26 | @SuppressWarnings("unchecked") 27 | public static void combine(int n, int k, int s, ArrayList r, List> res) { 28 | if (r.size() == k) { 29 | res.add((List) r.clone()); 30 | return; 31 | } 32 | for (int i = s; i <= n; i++) { 33 | r.add(i); 34 | combine(n, k, i + 1, r, res); 35 | r.remove(r.size() - 1); 36 | } 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M78_Subsets.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/subsets 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M78_Subsets { 13 | 14 | public static void main(String[] args) { 15 | subsets(new int[] { 1, 2, 3 }); 16 | } 17 | 18 | public static List> subsets(int[] nums) { 19 | List> r = new ArrayList>(); 20 | subset(nums, r, new ArrayList<>(), 0); 21 | for (List l : r) 22 | System.out.println(Arrays.toString(l.toArray())); 23 | return r; 24 | } 25 | 26 | @SuppressWarnings({ "rawtypes", "unchecked" }) 27 | public static void subset(int[] nums, List> r, List t, int i) { 28 | if (i >= nums.length) { 29 | r.add((List) ((ArrayList) t).clone()); 30 | return; 31 | } 32 | subset(nums, r, t, i + 1); 33 | t.add(nums[i]); 34 | subset(nums, r, t, i + 1); 35 | t.remove(t.size() - 1); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M7_ReverseInteger.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | /** 4 | * Link: https://leetcode.com/problems/reverse-integer 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class M7_ReverseInteger { 9 | 10 | public int reverse(int x) { 11 | int num = Math.abs(x); 12 | Long res = new Long(0); 13 | while(num!=0) { 14 | res = 10 * res + num % 10; 15 | num = num/10; 16 | } 17 | if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) 18 | return 0; 19 | return x < 0 ? -1 * res.intValue() : res.intValue(); 20 | } 21 | 22 | public static void main(String[] args) { 23 | int result = new M7_ReverseInteger().reverse(-123); 24 | System.out.println(result); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M89_GrayCode.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | import org.junit.Test; 9 | 10 | import junit.framework.TestCase; 11 | 12 | /** 13 | * Link: https://leetcode.com/problems/gray-code 14 | * 15 | * @author shivam.maharshi 16 | */ 17 | public class M89_GrayCode extends TestCase { 18 | 19 | @Test 20 | public void test() { 21 | List r = grayCode(3); 22 | for (int n : r) 23 | System.out.print(n + " "); 24 | } 25 | 26 | public static List grayCode(int n) { 27 | List r = new ArrayList(); 28 | if (n == 0) 29 | return r; 30 | Set s = new HashSet(); 31 | int num = 0, c = 1 << n; 32 | while (c > 0) { 33 | num = getNext(num, s); 34 | s.add(num); 35 | r.add(num); 36 | c--; 37 | } 38 | return r; 39 | } 40 | 41 | public static Integer getNext(int num, Set s) { 42 | int t = 0, invertBit = 1, i = 0; 43 | while (s.contains(t)) { 44 | t = num ^ (invertBit << i); 45 | i++; 46 | } 47 | return new Integer(t); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/leetcode/medium/M96_UniqueBinarySearchTrees.java: -------------------------------------------------------------------------------- 1 | package leetcode.medium; 2 | 3 | import org.junit.Test; 4 | 5 | import junit.framework.TestCase; 6 | 7 | /** 8 | * Link: https://leetcode.com/problems/unique-binary-search-trees 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class M96_UniqueBinarySearchTrees extends TestCase { 13 | 14 | @Test 15 | public void test() { 16 | assertEquals(5, numTrees(3)); 17 | } 18 | 19 | public static int numTrees(int n) { 20 | if (n == 0) 21 | return 1; 22 | int[] dp = new int[n + 1]; 23 | dp[0] = 1; 24 | dp[1] = 1; 25 | for (int i = 2; i < n + 1; i++) 26 | for (int j = 0; j < i; j++) 27 | dp[i] += dp[j] * dp[i - j - 1]; 28 | return dp[n]; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/math/BabylonianForSquareRoot.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find out the square root of a given number. 5 | * 6 | * Link: http://www.geeksforgeeks.org/square-root-of-a-perfect-square/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class BabylonianForSquareRoot { 11 | 12 | public static float get(float n) { 13 | float x = n; 14 | float y = 1; 15 | float aprx = 0.00001F; 16 | while (Math.abs(x - y) > aprx) { 17 | x = (x + y) / 2; 18 | y = n / x; 19 | } 20 | System.out.println(x); 21 | return x; 22 | } 23 | 24 | public static void main(String[] args) { 25 | BabylonianForSquareRoot.get(50); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/math/BinomialCoefficient.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Calculate binomial coefficient for k and n in O(k) time and no additional 5 | * space. 6 | * 7 | * Link: 8 | * http://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class BinomialCoefficient { 13 | 14 | public static int get(int n, int k) { 15 | int num = 1; 16 | int den = 1; 17 | if (k < n - k) { 18 | k=n-k; 19 | } 20 | for (int i = n; i >= n-k+1; i--) { 21 | num *= i; 22 | } 23 | for (int i = k; i >= 1; i--) { 24 | den *= i; 25 | } 26 | return num / den; 27 | } 28 | 29 | public static void main(String[] args) { 30 | System.out.println(get(5, 2)); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/math/BirthdayParadox.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * How many people must be there in a room to make the probability 50% that two 5 | * people in the room have same birthday? 6 | * 7 | * Very important. Must read the theory behind it. 8 | * 9 | * Link: http://www.geeksforgeeks.org/birthday-paradox/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class BirthdayParadox { 14 | 15 | public static int getPeople(double p) { 16 | return (int) Math.ceil(Math.sqrt(2 * 365 * Math.log((1 / (1 - p))))); 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println(getPeople(.50)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/math/CalculateClockAngle.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Calculate the angle between hour hand and minute hand 5 | * 6 | * Link: http://www.geeksforgeeks.org/calculate-angle-hour-hand-minute-hand/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class CalculateClockAngle { 11 | 12 | public static double get(int hour, int minute) { 13 | double angle = 0; 14 | if (hour == 12) 15 | hour = 0; 16 | double ha = hour * 30 + minute/2; 17 | double ma = minute * 6; 18 | angle = Math.abs(ha - ma); 19 | return angle > 180 ? 360 - angle : angle; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(get(3, 30)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/math/CalculateEToPowerX.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Calculate e^x in the most efficient manner. We used Taylor series for it. 5 | * 6 | * Link: http://www.geeksforgeeks.org/program-to-efficiently-calculate-ex/ 7 | * 8 | * Taylor Series: e^x = 1 + x/1! + x^2/2! + x^3/3! + ...... 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class CalculateEToPowerX { 13 | 14 | public static double calculate(int x) { 15 | double res = 1; 16 | double i = getIteration(x, 0.1); 17 | while (i > 0) { 18 | res *= x / i--; 19 | res += 1; 20 | } 21 | return res; 22 | } 23 | 24 | private static double getIteration(double x, double threshold) { 25 | double i = 0; 26 | double val = 1; 27 | while (val >= threshold) { 28 | i++; 29 | val *= x / i; 30 | } 31 | return i; 32 | } 33 | 34 | public static void main(String[] args) { 35 | System.out.println(calculate(4)); 36 | System.out.println(Math.pow(Math.E, 4)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/math/CatalanNumbers.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find the nth catalan number. They occur naturally in: 1. Count combination of 5 | * valid parenthesis. 2. Count possible BST with n keys. 3. Count possible full 6 | * Binary tree. 7 | * 8 | * Link: http://www.geeksforgeeks.org/program-nth-catalan-number/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class CatalanNumbers { 13 | 14 | // Time complexity O(n^2). 15 | public static int get(int n, int[] dp) { 16 | if (n <= 1) 17 | return 1; 18 | if (dp[n] != 0) 19 | return dp[n]; 20 | int res = 0; 21 | for (int i = 0; i < n; i++) { 22 | res += get(i, dp) * get(n - i - 1, dp); 23 | } 24 | dp[n] = res; 25 | return res; 26 | } 27 | 28 | public static void main(String[] args) { 29 | int n = 10; 30 | int[] dp = new int[n + 1]; 31 | System.out.println(get(n, dp)); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/math/ContSubseqAddiTo9Count.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given a number as a string, write a function to find the number of substrings 5 | * (or contiguous subsequences) of the given string which recursively add up to 6 | * 9. 7 | * 8 | * Link: http://geeksquiz.com/given-number-find-number-contiguous-subsequences- 9 | * recursively-add-9/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class ContSubseqAddiTo9Count { 14 | 15 | public static int count(String num) { 16 | int count = 0; 17 | for (int i = 0; i < num.length(); i++) { 18 | int sum = (int) num.charAt(i) - 48; 19 | if (sum == 9) 20 | count++; 21 | for (int j = i + 1; j < num.length(); j++) { 22 | sum += ((int) num.charAt(j) - 48) % 9; 23 | if (sum % 9 == 0) 24 | count++; 25 | } 26 | } 27 | return count; 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(count("4189")); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/math/ContiguousArrayLargestSum.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find the contiguous array largest sum. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class ContiguousArrayLargestSum { 9 | 10 | public static int contiguousArrayLargestSum(int[] arr) { 11 | int max = 0, total = 0; 12 | for (int i = 0; i < arr.length; i++) { 13 | total += arr[i]; 14 | max = Math.max(max, total); 15 | if (total < 0) { 16 | total = 0; 17 | } 18 | } 19 | return max; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] arr = new int[] { 2, 3, -8, -1, 2, 4, -2, 3 }; 24 | System.out.println(ContiguousArrayLargestSum.contiguousArrayLargestSum(arr)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/math/ConvertToBase8.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given a decimal number, convert it to base 8. Taking care of the negative 5 | * numbers is a very important thing in this question. 6 | * 7 | * Company : Google 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class ConvertToBase8 { 12 | 13 | public static String convert(int n) { 14 | String res = ""; 15 | boolean isNeg = false; 16 | if (n < 0) { 17 | isNeg = true; 18 | n *= -1; 19 | } 20 | while (n != 0) { 21 | res = n % 8 + res; 22 | n = n / 8; 23 | } 24 | return isNeg ? "-" + res : res; 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(convert(-123)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/math/CountDecodingsOfDigitSeq.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Count Possible Decodings of a given Digit Sequence 5 | * 6 | * Link: 7 | * http://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class CountDecodingsOfDigitSeq { 12 | 13 | public static int count(int[] digit, int index) { 14 | if (index == digit.length || index == digit.length - 1) 15 | return 1; 16 | int res = 0; 17 | if (isValidDoubleDigit(digit, index)) 18 | res += count(digit, index + 2); 19 | res += count(digit, index + 1); 20 | return res; 21 | } 22 | 23 | private static boolean isValidDoubleDigit(int[] digit, int index) { 24 | return digit[index] == 1 || (digit[index] == 2 && digit[index + 1] < 7); 25 | } 26 | 27 | public static void main(String[] args) { 28 | int[] digit = new int[] { 1, 2, 3, 4 }; 29 | System.out.println(count(digit, 0)); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/math/CountNoOfTwos.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given a number n, count the number of two present till that number. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | 9 | // !! This does not work correctly. This has to be done again. 10 | public class CountNoOfTwos { 11 | 12 | public static int countNoOfTwo(int n) { 13 | if (n < 2) 14 | return 0; 15 | if (n >= 2 && n < 10) 16 | return 1; 17 | int power = findPower(n); 18 | int ld = findLastDigit(n, power); 19 | int subProb = (int) (n % Math.pow(10, power)); 20 | int res = countNoOfTwo(subProb); 21 | if (ld > 2) { 22 | res += Math.pow(10, power); 23 | } else if (ld == 2) { 24 | res += subProb + 1; 25 | } 26 | return res; 27 | } 28 | 29 | static int findPower(int n) { 30 | int power = 0; 31 | while (n / 10 != 0) { 32 | power++; 33 | n = n / 10; 34 | } 35 | return power; 36 | } 37 | 38 | static int findLastDigit(int n, int power) { 39 | return (int) (n / Math.pow(10, power)); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/math/CountNonConsOneBinaryString.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given a positive integer N, count all possible distinct binary strings of 5 | * length N such that there are no consecutive 1s. 6 | * 7 | * Link: 8 | * http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive- 9 | * 1s/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class CountNonConsOneBinaryString { 14 | 15 | public static int count(int n, boolean isPrevOne) { 16 | if (n == 0 || n == 1) 17 | return 1; 18 | int res = 0; 19 | res = count(n - 1, false); 20 | if (!isPrevOne) { 21 | // Adding one because one chain increased. 22 | res += 1 + count(n - 1, true); 23 | } 24 | return res; 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(count(3, false)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/math/DFABasedDivision.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find out if a number is divisible by another number. Also calculate the 5 | * remainder. 6 | * 7 | * Link: http://www.geeksforgeeks.org/dfa-based-division/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class DFABasedDivision { 12 | 13 | public static int getRemainder(int n, int k) { 14 | 15 | int[][] table = new int[k][2]; 16 | for (int i = 0; i < k; i++) { 17 | table[i][0] = 2 * i < k ? 2 * i : 2 * i - k; 18 | table[i][1] = 2 * i + 1 < k ? 2 * i + 1 : 2 * i + 1 - k; 19 | } 20 | String s = Integer.toBinaryString(n); 21 | int nextStage = 0; 22 | for (int i = 0; i < s.length(); i++) { 23 | if (s.charAt(i) == '0') { 24 | nextStage = table[nextStage][0]; 25 | } else { 26 | nextStage = table[nextStage][1]; 27 | } 28 | } 29 | return nextStage; 30 | } 31 | 32 | public static void main(String[] args) { 33 | int remainder = DFABasedDivision.getRemainder(45, 7); 34 | System.out.println(remainder); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/math/DivisibleBy7.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Check if the given number is divisible by 7. Number 10a + b is divisible by 7 5 | * if a -2b is divisible by 7. Untill the number is less than 10, if it is 0 or 6 | * 7, it is divisible. 7 | * 8 | * Link: http://www.geeksforgeeks.org/divisibility-by-7/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class DivisibleBy7 { 13 | 14 | public static boolean isDivisible(int n) { 15 | if (n < 0) 16 | return isDivisible(-1 * n); 17 | if (n == 0 || n == 7) 18 | return true; 19 | if (n < 10) 20 | return false; 21 | return isDivisible((n / 10) - 2 * (n - (n / 10) * 10)); 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(isDivisible(98)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/math/DrawCircle.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Draw a circle without floating point arithmetic. Given a radius of a circle, 5 | * draw the circle without using floating point arithmetic 6 | * 7 | * Link: http://geeksquiz.com/draw-circle-without-floating-point-arithmetic/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class DrawCircle { 12 | 13 | public static void draw(double radius) { 14 | for (double x = 0; x < 2 * radius + 1; x++) { 15 | for (double y = 0; y < 2 * radius + 1; y++) { 16 | if (Math.sqrt(((radius - x) * (radius - x)) + ((radius - y) * (radius - y))) <= radius) { 17 | System.out.print("*"); 18 | } else { 19 | System.out.print(" "); 20 | } 21 | } 22 | System.out.println(); 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | draw(10); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/math/FactorialMaximumTrailingZero.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Return the maximum number of trailing zeroes in the factorial of a num n. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | 9 | public class FactorialMaximumTrailingZero { 10 | 11 | public static int maxTrailingZero(int num) { 12 | int count = 0, factor = 5; 13 | if (num < 0) 14 | return -1; 15 | while (num / factor != 0) { 16 | count += num / factor; 17 | factor *= 5; 18 | } 19 | return count; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(FactorialMaximumTrailingZero.maxTrailingZero(150)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/math/FancyNumber.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.util.HashMap; 4 | 5 | /** 6 | * Find if a number is fancy. A number is fancy when it is rotated by 180 7 | * degrees and it still remains the same. 8 | * 9 | * Link: http://www.geeksforgeeks.org/check-if-a-given-number-is-fancy/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class FancyNumber { 14 | 15 | private static HashMap fancyMap = new HashMap<>(); 16 | 17 | private static void init() { 18 | fancyMap.put(0, 0); 19 | fancyMap.put(1, 1); 20 | fancyMap.put(6, 9); 21 | fancyMap.put(8, 8); 22 | fancyMap.put(9, 6); 23 | } 24 | 25 | public static boolean isFancy(int num) { 26 | init(); 27 | int n = num; 28 | int revNum = 0; 29 | while (n != 0) { 30 | revNum *= 10; 31 | revNum += n % 10; 32 | n = n / 10; 33 | } 34 | System.out.println("RevNum : " + revNum); 35 | while (num != 0) { 36 | if (fancyMap.get(num % 10) == null || fancyMap.get(num % 10) != revNum % 10) 37 | return false; 38 | num /= 10; 39 | revNum /= 10; 40 | } 41 | return true; 42 | } 43 | 44 | public static void main(String[] args) { 45 | System.out.println(FancyNumber.isFancy(121)); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/math/FindExcelColumn.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * MS Excel columns has a pattern like A, B, C, more , Z, AA, AB, AC, more ,AZ, BA, BB, 5 | * more ZZ, AAA, AAB, more. In other words, column 1 is named as A, column 2 as 6 | * B, column 27 as AA. 7 | * 8 | * Link: http://www.geeksforgeeks.org/find-excel-column-name-given-number/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class FindExcelColumn { 13 | 14 | public static String find(int col) { 15 | String res = ""; 16 | col--; 17 | while (col >= 0) { 18 | res = getChar(col % 26) + res; 19 | col /= 26; 20 | col--; 21 | } 22 | return res; 23 | } 24 | 25 | // Returns the corresponding char. 26 | private static char getChar(int n) { 27 | return (char) (n + 65); 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(find(1)); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/math/FirstKDigitsOfReciprocalOfN.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given a positive integer n, print first k digits after point in value of 1/n. 5 | * Your program should avoid overflow and floating point arithmetic. 6 | * 7 | * Link: http://geeksquiz.com/print-first-k-digits-1n-n-positive-integer/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class FirstKDigitsOfReciprocalOfN { 12 | 13 | public static int get(int n, int k) { 14 | int rem = 10; 15 | int res = 0; 16 | while (k > 0) { 17 | res = res*10 + rem/n; 18 | rem = (rem%n)*10; 19 | k--; 20 | } 21 | return res; 22 | } 23 | 24 | public static void main(String[] args) { 25 | System.out.println(get(50, 4)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/math/GenerateAllNumbers.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Generate all numbers using the same digit as in the given numbers. 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class GenerateAllNumbers { 11 | 12 | public static void generate(int[] num) { 13 | generateRec(num, 0); 14 | printNum(num); 15 | } 16 | 17 | private static void generateRec(int[] num, int index) { 18 | if (index == num.length) 19 | return; 20 | generateRec(num, index+1); 21 | for (int i = index+1; i < num.length; i++) { 22 | int[] swapped = swap(num, index, i); 23 | generateRec(swapped, index+1); 24 | } 25 | } 26 | 27 | private static void printNum(int[] num) { 28 | String res = ""; 29 | for (int i = 0; i < num.length; i++) { 30 | res += num[i]; 31 | } 32 | System.out.println(res); 33 | } 34 | 35 | private static int[] swap(int[] num, int i, int j) { 36 | int[] arr = Arrays.copyOf(num, num.length); 37 | int temp = arr[i]; 38 | arr[i] = arr[j]; 39 | arr[j] = temp; 40 | return arr; 41 | } 42 | 43 | public static void main(String[] args) { 44 | int[] num = new int[] { 1, 2, 3 }; 45 | GenerateAllNumbers.generate(num); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/math/GroupOfMultipleOf3.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Count all possible groups of size 2 or 3 that have sum as multiple of 3 5 | * 6 | * Link: 7 | * http://www.geeksforgeeks.org/count-possible-groups-size-2-3-sum-multiple-3/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class GroupOfMultipleOf3 { 12 | 13 | public static int count(int[] a) { 14 | int res = 0; 15 | int[] r = new int[3]; 16 | for (int i = 0; i < a.length; i++) { 17 | r[a[i] % 3]++; 18 | } 19 | // Pair of two. 20 | res += nC2(r[0]) + r[1] * r[2]; 21 | // Pair of three. 22 | res += nC3(r[0]) + nC3(r[1]) + nC3(r[2]) + r[0] * r[1] * r[2]; 23 | return res; 24 | } 25 | 26 | private static int nC2(int n) { 27 | return n * (n - 1) / 2; 28 | } 29 | 30 | private static int nC3(int n) { 31 | return n * (n - 1) * (n - 2) / 6; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] a = new int[] { 3, 6, 7, 2, 9 }; 36 | System.out.println(count(a)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/math/HornersPolynomialEvaluation.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Horners polynomial evaluation method. Given a polynomial of the form cnxn + 5 | * cn-1xn-1 + cn-2xn-2 + more + c1x + c0 and a value of x, find the value of 6 | * polynomial for a given value of x. Here cn, cn-1, etc. are integers (maybe 7 | * negative) and n is a positive integer. 8 | * 9 | * Link: http://www.geeksforgeeks.org/horners-method-polynomial-evaluation/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class HornersPolynomialEvaluation { 14 | 15 | public static int calculate(int[] poly, int x) { 16 | int res = poly[0]; 17 | for (int i = 1; i < poly.length; i++) { 18 | res = res * x + poly[i]; 19 | } 20 | return res; 21 | } 22 | 23 | public static void main(String[] args) { 24 | int[] poly = new int[] { 2, -6, 2, -1 }; 25 | System.out.println(calculate(poly, 3)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/math/IsFibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Check if the given number is a Fibonacci number. A number is Fibonacci if and 5 | * only if one or both of (5*n2 + 4) or (5*n2 - 4) is a perfect square 6 | * 7 | * Link: http://www.geeksforgeeks.org/check-number-fibonacci-number/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class IsFibonacciNumber { 12 | 13 | public static boolean isFibonacci(int n) { 14 | return isPerfectSquare(5 * n * n - 4) || isPerfectSquare(5 * n * n + 4); 15 | } 16 | 17 | private static boolean isPerfectSquare(int n) { 18 | int sqrt = (int) Math.sqrt(n); 19 | return sqrt * sqrt == n; 20 | } 21 | 22 | public static void main(String[] args) { 23 | for (int i = 1; i < 100; i++) { 24 | if (isFibonacci(i)) { 25 | System.out.println(i + " is a Fibonacci Number."); 26 | } else { 27 | System.out.println(i + " is not a Fibonacci Number."); 28 | } 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/math/LargestMultipleOf2_5_3.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find the largest multiple of 2, 5 and 3 from a given array of integers. 5 | * 6 | * Link: http://www.geeksforgeeks.org/find-the-largest-multiple-of-2-3-and-5/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class LargestMultipleOf2_5_3 { 11 | 12 | public static void print(int[] a) { 13 | // Array must have one zero to be divisible by 5 & 2. 14 | boolean valid = false; 15 | for (int n : a) { 16 | if (n == 0) { 17 | valid = true; 18 | } 19 | } 20 | if (!valid) { 21 | System.out.println("Not possible"); 22 | return; 23 | } 24 | LargestMultipleOf3.get(a); 25 | } 26 | 27 | public static void main(String[] args) { 28 | print(new int[] { 1, 8, 7, 6, 0 }); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/math/LexicographicalRankOfString.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find the lexicographic rank of a string in its permutation. 5 | * 6 | * Link: http://www.geeksforgeeks.org/lexicographic-rank-of-a-string/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class LexicographicalRankOfString { 11 | 12 | public static int getRank(String s) { 13 | char[] c = s.toCharArray(); 14 | int r = 0; 15 | int[] a = new int[26]; 16 | for (char cc : c) { 17 | a[cc - 97]++; 18 | } 19 | for (int i = 0; i < c.length; i++) { 20 | a[(int) c[i] - 97] = -1; 21 | int d = getSmallerChar(a, c[i]); 22 | r += d * fact(c.length - i - 1); 23 | } 24 | return r + 1; 25 | } 26 | 27 | private static int fact(int n) { 28 | if (n == 0 || n == 1) 29 | return 1; 30 | return n * fact(n - 1); 31 | } 32 | 33 | public static int getSmallerChar(int[] a, char c) { 34 | int count = 0; 35 | for (int i = 0; i < (int) c - 97; i++) { 36 | if (a[i] == 1) { 37 | count++; 38 | } 39 | } 40 | return count; 41 | } 42 | 43 | public static void main(String[] args) { 44 | System.out.println(getRank("string")); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/math/LuckyNumbers.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * A number that doesn't get removed in a sequence given. 5 | * 6 | * Link: http://www.geeksforgeeks.org/lucky-numbers/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class LuckyNumbers { 11 | 12 | public static boolean isLucky(int n, int diff) { 13 | if (diff > n) 14 | return true; 15 | else if (n % diff == 0) 16 | return false; 17 | else { 18 | return isLucky(n - (n / diff), diff+1); 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(LuckyNumbers.isLucky(9,2)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/math/MakeFairCoinFromUnfairCoin.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Make a fair coin with equal probability from unfair coin with 60-40 5 | * probability. 6 | * 7 | * Link: http://www.geeksforgeeks.org/print-0-and-1-with-50-probability/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class MakeFairCoinFromUnfairCoin { 12 | 13 | public static int fairCoinToss() { 14 | int a = unfairCoinToss(); 15 | int b = flipUnfairToss(); 16 | while (a + b == 1) { 17 | a = unfairCoinToss(); 18 | b = flipUnfairToss(); 19 | } 20 | // Probability of 0,0 is 0.24. Probability of 1,1 is 0.24. 21 | return a + b == 0 ? 0 : 1; 22 | } 23 | 24 | private static int flipUnfairToss() { 25 | return unfairCoinToss() == 0 ? 1 : 0; 26 | } 27 | 28 | // Returns 0 with 60% probability. 29 | private static int unfairCoinToss() { 30 | return Math.random() < 0.6F ? 0 : 1; 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(fairCoinToss()); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/math/MultiplyBy7.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Multiply a number by 7 in the most efficient way. 5 | * 6 | * Link: http://www.geeksforgeeks.org/efficient-way-to-multiply-with-7/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class MultiplyBy7 { 11 | 12 | /** 13 | * Time complexity is O(1). However pay attention to overflow. Edge case 14 | * when multiply by 7 is not an overflow but multiply by 8 is. 15 | */ 16 | public static int multiply(int n) { 17 | int t = n << 3; 18 | return t - n; 19 | } 20 | 21 | public static void main(String[] args) { 22 | System.out.println(MultiplyBy7.multiply(7)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/math/MultiplyPolynomials.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given two polynomials represented by two arrays, write a function that 5 | * multiplies given two polynomials. 6 | * 7 | * Link: http://www.geeksforgeeks.org/multiply-two-polynomials-2/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class MultiplyPolynomials { 12 | 13 | // Naive solution O(n*m) complexity. Could do better with divide and 14 | // conquer. 15 | public static int[] multiply(int[] a, int[] b) { 16 | int[] res = new int[a.length + b.length - 1]; 17 | for (int i = 0; i < a.length; i++) { 18 | for (int j = 0; j < b.length; j++) { 19 | res[i + j] += a[i] * b[j]; 20 | } 21 | } 22 | for (int n : res) { 23 | System.out.print(n + " "); 24 | } 25 | return res; 26 | } 27 | 28 | public static void main(String[] args) { 29 | int[] a = new int[] { 5, 0, 10, 6 }; 30 | int[] b = new int[] { 1, 2, 4 }; 31 | multiply(a, b); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/math/NonNegativeIntegerPair.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given a positive number n, count all distinct Non-Negative Integer pairs (x, 5 | * y) that satisfy the inequality x*x + y*y < n. 6 | * 7 | * Link: 8 | * http://www.geeksforgeeks.org/count-distinct-non-negative-pairs-x-y-satisfy- 9 | * inequality-xx-yy-n-2/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class NonNegativeIntegerPair { 14 | 15 | public static int count(int n) { 16 | int max = (int) Math.sqrt(n); 17 | if (n == max * max) 18 | max--; 19 | int equiMax = (int) Math.sqrt(n / 2); 20 | if (n / 2 == equiMax * equiMax) 21 | equiMax--; 22 | return count(n, max, equiMax); 23 | } 24 | 25 | private static int count(int n, int max, int equiMax) { 26 | int res = 0; 27 | int a = equiMax; 28 | int b = equiMax; 29 | while (a >= 0) { 30 | while (a * a + b * b < n) { 31 | b++; 32 | } 33 | b--; 34 | res += (b - a + 1); 35 | a--; 36 | } 37 | res = 2 * res - ( equiMax + 1); 38 | return res; 39 | } 40 | 41 | public static void main(String[] args) { 42 | System.out.println(count(2)); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/math/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find if the given number is palindrome. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class PalindromeNumber { 9 | 10 | public static boolean isPalindrome(int n) { 11 | int a = n; 12 | int m = 0; 13 | while (a != 0) { 14 | m = 10 * m; 15 | m += a % 10; 16 | a = a / 10; 17 | } 18 | 19 | while (m != 0 && n != 0) { 20 | if (m % 10 != n % 10) 21 | return false; 22 | m /= 10; 23 | n /= 10; 24 | } 25 | 26 | return true; 27 | } 28 | 29 | public static void main(String[] args) { 30 | System.out.println(PalindromeNumber.isPalindrome(40504)); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/math/PascalsTriangle.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /** 7 | * Print pascal's triangle. 8 | * 9 | * Link: http://www.geeksforgeeks.org/pascal-triangle/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class PascalsTriangle { 14 | 15 | public static void print(int n) { 16 | Queue q = new LinkedList<>(); 17 | q.add(1); 18 | System.out.println(1); 19 | for (int i = 1; i < n; i++) { 20 | q.add(1); 21 | System.out.print(1); 22 | for (int j = 1; j < i; j++) { 23 | int a = q.remove(); 24 | int b = q.peek(); 25 | System.out.print(a + b); 26 | q.add(a + b); 27 | } 28 | q.add(1); 29 | q.remove(); 30 | System.out.print(1); 31 | System.out.println(); 32 | } 33 | } 34 | 35 | public static void main(String[] args) { 36 | print(5); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/math/PolynomialEvaluation.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Evaluate a polynomial expression for a given value of x. 5 | * 6 | * @author shivam.maharshi 7 | */ 8 | public class PolynomialEvaluation { 9 | 10 | public static int calculate(int[] poly, int x) { 11 | int res = 0; 12 | int xPow = 1; 13 | for (int co : poly) { 14 | res += xPow * co; 15 | xPow *= x; 16 | } 17 | return res; 18 | } 19 | 20 | public static void main(String[] args) { 21 | int[] poly = new int[] { 1, 3, 0, 2 }; 22 | System.out.println(calculate(poly, 2)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/math/PolynomialsAddition.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Add two polynomials. 5 | * 6 | * Link: http://geeksquiz.com/program-add-two-polynomials/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class PolynomialsAddition { 11 | 12 | public static int[] add(int[] a, int[] b) { 13 | int[] res = new int[Math.max(a.length, b.length)]; 14 | for (int i = 0; i < res.length; i++) { 15 | if (i < a.length) 16 | res[i] += a[i]; 17 | if (i < b.length) 18 | res[i] += b[i]; 19 | } 20 | return res; 21 | } 22 | 23 | public static void main(String[] args) { 24 | int[] a = new int[] { 5, 0, 10, 6 }; 25 | int[] b = new int[] { 1, 2, 4 }; 26 | int[] add = add(a, b); 27 | for (int co : add) { 28 | System.out.print(co + " "); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/math/PowerOperation.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Write power operation without using multiplication or division. 5 | * 6 | * Link: 7 | * http://www.geeksforgeeks.org/write-you-own-power-without-using-multiplication 8 | * -and-division/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class PowerOperation { 13 | 14 | public static int get(int n, int pow) { 15 | int a = n; 16 | int b = n; 17 | for (int i = 1; i < pow; i++) { 18 | for (int j = 1; j < n; j++) { 19 | a += b; 20 | } 21 | b = a; 22 | } 23 | System.out.println(a); 24 | return a; 25 | } 26 | 27 | /* 28 | * Converges logarithmically. To avoid using multiplication operator, just run 29 | * a for loop with addition. 30 | */ 31 | public static int pow(int n, int pow) { 32 | if (n == 1 || pow == 0) 33 | return 1; 34 | if (pow == 1) 35 | return n; 36 | else if (pow % 2 == 0) 37 | return pow(n * n, pow / 2); 38 | else 39 | return n * pow(n * n, (pow - 1) / 2); 40 | } 41 | 42 | public static void main(String[] args) { 43 | PowerOperation.get(5, 6); 44 | System.out.println(pow(5, 6)); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/math/PrintAllNumberCombination.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Print all the possible combination of how a number can be broken as sum of 1, 5 | * 2 or 3. Ordering is important. 6 | * 7 | * Link: 8 | * http://www.geeksforgeeks.org/write-you-own-power-without-using-multiplication 9 | * -and-division/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class PrintAllNumberCombination { 14 | 15 | public static void print(int n, String s) { 16 | if (n == 0) 17 | System.out.println(s); 18 | if (n < 0) 19 | return; 20 | print(n - 1, s + " " + 1); 21 | print(n - 2, s + " " + 2); 22 | print(n - 3, s + " " + 3); 23 | } 24 | 25 | public static void main(String[] args) { 26 | PrintAllNumberCombination.print(4, ""); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/math/PrintAllPrimeFactors.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Print all prime factors of a number. 5 | * 6 | * Link: http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class PrintAllPrimeFactors { 11 | 12 | public static void print(int n) { 13 | int i = 2; 14 | while (n % i == 0) { 15 | System.out.println(i); 16 | n /= i; 17 | } 18 | 19 | for (i = 3; i <= Math.sqrt(n); i += 2) { 20 | while (n % i == 0) { 21 | System.out.println(i); 22 | n /= i; 23 | } 24 | } 25 | 26 | if (n > 2) { 27 | System.out.println(n); 28 | } 29 | 30 | } 31 | 32 | public static void main(String[] args) { 33 | PrintAllPrimeFactors.print(1000); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/math/PrintCombinationOfRElements.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Print all possible combinations of r elements in a given array of size n 5 | * 6 | * Link: 7 | * http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in 8 | * -a-given-array-of-size-n/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class PrintCombinationOfRElements { 13 | 14 | public static void print(int[] a, int index, int r, String s) { 15 | if (r == 0) 16 | System.out.println(s); 17 | for (int i = index; i < a.length; i++) { 18 | print(a, i + 1, r - 1, s + " " + a[i]); 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] a = new int[] { 1, 2, 3, 4, 5 }; 24 | print(a, 0, 3, ""); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/math/PrintNumbersInLexographicalOrder.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * @author shivam.maharshi 5 | */ 6 | public class PrintNumbersInLexographicalOrder { 7 | 8 | public static void printLexographicalOrder(int num, int n) { 9 | if (n > num) 10 | return; 11 | else { 12 | System.out.println(n); 13 | printLexographicalOrder(num, n * 10); 14 | if (( (n + 1) / 10) % 10 != (n / 10) % 10) { 15 | return; 16 | } else { 17 | printLexographicalOrder(num, n + 1); 18 | } 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | PrintNumbersInLexographicalOrder.printLexographicalOrder(25, 1); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/math/ProductRepresentationCombination.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Print all the product representation of a given number. Don't print 5 | * duplicates. 6 | * 7 | * Link: http://www.careercup.com/question?id=12457661 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class ProductRepresentationCombination { 12 | 13 | public static void print(int n, String s, int startFactor) { 14 | if (n == 1) { 15 | return; 16 | } 17 | for (int i = startFactor; i <= Math.sqrt(n); i++) { 18 | if (n % i == 0) { 19 | if (s.isEmpty()) { 20 | System.out.println(i + " * " + n / i); 21 | print(n / i, "" + i, i); 22 | } else { 23 | System.out.println(s + " * " + i + " * " + n / i); 24 | print(n / i, s + " * " + i, i); 25 | } 26 | 27 | } 28 | } 29 | } 30 | 31 | public static void p(int n, int f, String s) { 32 | for(int i=f; i<=Math.sqrt(n); i++) { 33 | if(n%i==0) 34 | p(n/i, f, s + " * " + i); 35 | } 36 | System.out.println(s + " * " + n); 37 | } 38 | 39 | public static void main(String[] args) { 40 | // ProductRepresentationCombination.print(24, "", 2); 41 | p(24, 2, ""); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/math/RandGeneratorThreeNumGivenProb.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Write a function that generates one of 3 numbers according to given 5 | * probabilities 6 | * 7 | * Link: 8 | * http://www.geeksforgeeks.org/write-a-function-to-generate-3-numbers-according 9 | * -to-given-probabilities/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class RandGeneratorThreeNumGivenProb { 14 | 15 | public static int rand(int a, int b, int c, int pa, int pb, int pc) { 16 | int val = rand(1, 100); 17 | if (val < pa) 18 | return a; 19 | if (val < pa + pb) 20 | return b; 21 | else 22 | return c; 23 | } 24 | 25 | /* 26 | * Given a function rand(a, b) which generates equiprobable random numbers 27 | * between [a, b] inclusive. 28 | */ 29 | public static int rand(int a, int b) { 30 | return a + (int) Math.round((b - a) * Math.random()); 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(rand(40, 25, 35, 1, 2, 3)); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/math/ReachNthStair.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Count the ways to reach Nth stair when a person can climb one or two steps. 5 | * 6 | * Link: http://www.geeksforgeeks.org/count-ways-reach-nth-stair/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class ReachNthStair { 11 | 12 | public static int count(int n) { 13 | if (n <= 2) 14 | return n; 15 | return count(n - 1) + count(n - 2); 16 | } 17 | 18 | public static int countDp(int n, int[] dp) { 19 | if (n <= 2) 20 | return n; 21 | if (dp[n] != 0) 22 | return dp[n]; 23 | else 24 | dp[n] = countDp(n, dp); 25 | return dp[n]; 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(count(4)); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/math/Replace0With5.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Replace 0 with 5 in a number. 5 | * 6 | * Link: http://geeksquiz.com/replace-0-5-input-integer/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class Replace0With5 { 11 | 12 | public static int replace(int n) { 13 | int res = 0; 14 | int num = 0; 15 | while (n != 0) { 16 | if (n % 10 == 0) { 17 | num = 10 * num + 5; 18 | } else { 19 | num = 10 * num + n % 10; 20 | } 21 | n /= 10; 22 | } 23 | while (num != 0) { 24 | res = 10 * res + num % 10; 25 | num /= 10; 26 | } 27 | return res; 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(replace(12506)); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/math/ReservoirSamplingOptimized.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Select a number from a stream of numbers with equal probability. Use only 5 | * O(1) space. 6 | * 7 | * Link: 8 | * http://www.geeksforgeeks.org/select-a-random-number-from-stream-with-o1- 9 | * space/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class ReservoirSamplingOptimized { 14 | 15 | // The proof of equal probability for this is highly important. 16 | public static void getRand(int[] a) { 17 | int rand = 0; 18 | for (int i = 0; i < a.length; i++) { 19 | if (i == 0) { 20 | rand = a[i]; 21 | } else { 22 | int t = getRand(i + 1); 23 | if (i == t) { 24 | rand = a[i]; 25 | } 26 | } 27 | System.out.println(rand); 28 | } 29 | } 30 | 31 | public static int getRand(int n) { 32 | return (int) (n * Math.random()); 33 | } 34 | 35 | public static void main(String[] args) { 36 | getRand(new int[] { 1, 2, 3, 4 }); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/math/RussianPeasantMultiplication.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Given two integers, write a function to multiply them without using 5 | * multiplication operator. 6 | * 7 | * Link: http://www.geeksforgeeks.org/fast-multiplication-method-without-using- 8 | * multiplication-operator-russian-peasants-algorithm/ 9 | * 10 | * @author shivam.maharshi 11 | * 12 | */ 13 | public class RussianPeasantMultiplication { 14 | 15 | /* 16 | * The idea is to double the first number and half the second. If the second 17 | * number is odd, add the first number to the result and carry on. 18 | */ 19 | public static int multiply(int a, int b) { 20 | int res = a; 21 | int t = 0; 22 | while (b != 1) { 23 | int temp = res; 24 | res = res << 1; 25 | if ((b & 1) == 1) { 26 | t += temp; 27 | } 28 | b = b >> 1; 29 | } 30 | return res + t; 31 | } 32 | 33 | public static void main(String[] args) { 34 | System.out.println(multiply(100, 399)); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/math/ShuffleCardDeck.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Shuffle a deck of card with equal probability for all the cases. Assume pure 5 | * random generator. 6 | * 7 | * Link: http://www.geeksforgeeks.org/shuffle-a-given-array/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class ShuffleCardDeck { 12 | 13 | public static void shuffle(int[] arr) { 14 | for (int i = 0; i < arr.length; i++) { 15 | int j = rand(0, i); 16 | int temp = arr[i]; 17 | arr[i] = arr[j]; 18 | arr[j] = temp; 19 | } 20 | } 21 | 22 | public static int rand(int low, int high) { 23 | return low + (int) (Math.random() * (high - low + 1)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/math/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find out all the prime numbers less than a given number. Good for n<10Million. 5 | * 6 | * Link: http://www.geeksforgeeks.org/sieve-of-eratosthenes/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class SieveOfEratosthenes { 11 | 12 | public static boolean[] get(int n) { 13 | boolean[] a = new boolean[n]; 14 | for (int i = 1; i < n / 2; i++) { 15 | int num = 2 * (i + 1); 16 | while (num <= n) { 17 | a[num - 1] = true; 18 | num += i + 1; 19 | } 20 | } 21 | return a; 22 | } 23 | 24 | public static void printArr(boolean[] a) { 25 | for (int i = 0; i < a.length; i++) { 26 | if (!a[i]) 27 | System.out.println(i + 1); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | SieveOfEratosthenes.printArr(get(100)); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/math/SmallestTwin.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Find the smallest twins, which are two prime numbers with a difference of two 5 | * between them. They should lie in the given range. 6 | * 7 | * Link: 8 | * http://www.geeksforgeeks.org/find-the-smallest-twin-numbers-in-given-range/ 9 | * 10 | * @author shivam.maharshi 11 | * 12 | */ 13 | public class SmallestTwin { 14 | 15 | public static void get(int low, int high) { 16 | boolean[] a = new boolean[high + 1]; 17 | a[1] = true; 18 | getArray(high + 1, a); 19 | for (int i = low; i < high - 1; i++) { 20 | if (!(a[i] || a[i + 2])) { 21 | System.out.println("a: " + i + ", b: " + (i + 2)); 22 | } 23 | } 24 | } 25 | 26 | private static void getArray(int n, boolean[] a) { 27 | for (int i = 2; i <= Math.sqrt(n); i++) { 28 | for (int num = i; num <= n; num += i) { 29 | a[num] = true; 30 | } 31 | } 32 | } 33 | 34 | public static void main(String[] args) { 35 | SmallestTwin.get(50, 100); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/math/StreamAverage.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Calculate the average of a stream of numbers. 5 | * 6 | * Link: http://www.geeksforgeeks.org/average-of-a-stream-of-numbers/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class StreamAverage { 11 | 12 | private static float getAvg(float avg, float n, int num) { 13 | return (avg*n + num)/(n+1) ; 14 | } 15 | 16 | public static void printStreamAvg(int[] a) { 17 | float avg = 0F; 18 | for(int i=0;i>= 1; 28 | i++; 29 | } 30 | } 31 | for (int count : oneCountAtIthBit) { 32 | res += 2 * (a.length - count) * count; 33 | } 34 | return res; 35 | } 36 | 37 | public static void main(String[] args) { 38 | int[] a = { 1, 3, 5 }; 39 | System.out.println(count(a)); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/math/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Tower of Hanoi. 5 | * 6 | * Link: http://geeksquiz.com/c-program-for-tower-of-hanoi/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class TowerOfHanoi { 11 | 12 | public static void move(int n, char from, char to, char temp) { 13 | if (n <= 0) 14 | return; 15 | move(n - 1, from, temp, to); 16 | System.out.println("Move disk from " + from + " to " + to); 17 | move(n - 1, temp, to, from); 18 | } 19 | 20 | public static void main(String[] args) { 21 | move(4, 'A', 'C', 'B'); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/math/TrailingZeroesInFactorial.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * Count the number of trailing zeroes in the factorial of a number. 5 | * 6 | * Link: http://www.geeksforgeeks.org/count-trailing-zeroes-factorial-number/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class TrailingZeroesInFactorial { 11 | 12 | public static int count(int n) { 13 | int res = 0; 14 | while(n!=0) { 15 | n/=5; 16 | res += n; 17 | } 18 | return res; 19 | } 20 | 21 | public static void main(String[] args) { 22 | System.out.println(count(100)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/math/TwoVesselInfiniteWater.java: -------------------------------------------------------------------------------- 1 | package math; 2 | 3 | /** 4 | * There are two vessels of capacities a and b respectively. We have 5 | * infinite water supply. Give an efficient algorithm to make exactly 1 litre of 6 | * water in one of the vessels. You can throw all the water from any vessel any 7 | * point of time. Assume that a and b are co primes. 8 | * 9 | * Link: 10 | * http://www.geeksforgeeks.org/measure-1-litre-from-two-vessels-infinite-water- 11 | * supply/ 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class TwoVesselInfiniteWater { 16 | 17 | // We need to find x,y where y*b-x*a=1. 18 | public static void get(int a, int b) { 19 | int x = 1, y = 0; 20 | if (a != 1 && b != 1) { 21 | while (y * b - x * a != 1) { 22 | if (y * b > x * a) { 23 | x++; 24 | } else { 25 | y++; 26 | } 27 | } 28 | } 29 | System.out.println("X : " + x + " - Y : " + y); 30 | } 31 | 32 | public static void main(String[] args) { 33 | get(5, 8); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/pramp/Interview10.java: -------------------------------------------------------------------------------- 1 | package pramp; 2 | 3 | /** 4 | * Given a string and a character set, return the shortest substring that 5 | * contains all the characters. 6 | * 7 | * @author: shivam.maharshi 8 | */ 9 | 10 | public class Interview10 { 11 | 12 | public static String get(String s, char[] a) { 13 | if (a == null || a.length == 0 || s == null || s.length() == 0 || a.length > s.length()) 14 | return null; 15 | String r = null; 16 | int[] c = new int[256]; 17 | for (int i = 0; i < a.length; i++) 18 | c[s.charAt(i)]++; 19 | int i = 0, j = a.length - 1; 20 | while (i <= s.length() - a.length && j <= s.length()) { 21 | if (allPresent(a, c)) { 22 | r = (r == null || r.length() > j - i) ? s.substring(i, j) : r; // 5, 8 23 | if (r.length() == a.length) 24 | return r; 25 | c[s.charAt(i)]--; 26 | i++; 27 | } else { 28 | j++; 29 | c[s.charAt(j)]++; 30 | } 31 | } 32 | return r; 33 | } 34 | 35 | public static boolean allPresent(char[] a, int[] c) { 36 | for (char aa : a) { 37 | if (c[aa] == 0) 38 | return false; 39 | c[aa]--; 40 | } 41 | return true; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/pramp/Interview3.java: -------------------------------------------------------------------------------- 1 | package pramp; 2 | 3 | /** 4 | * Given an array of integer return an index where the value stored at it is the same as the index. 5 | * If no such value exists, return -1. Assume that the array is sorted in ascending order. 6 | * 7 | * @author: shivam.maharshi 8 | */ 9 | 10 | public class Interview3 { 11 | 12 | // {0} - 0 13 | // {-1, 1} - 1 14 | // {-1, 2} - -1 15 | // {3, 4} - -1 16 | // {-3, -2} - -1 17 | 18 | public static int get(int[] a) { 19 | if (a==null || a.length == 0) 20 | return -1; 21 | return get (a, 0, a.length - 1); 22 | } 23 | 24 | public static int get (int[] a, int l, int h) { 25 | if (h == l) 26 | return a[l] == l ? l : -1; 27 | int m = (h - l)/2 + l; 28 | return a[m] == m ? m : ( a[m] > m ? get(a, l, m) : get(a, m + 1, h)); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/pramp/Interview7.java: -------------------------------------------------------------------------------- 1 | package pramp; 2 | 3 | class Interview7 { 4 | 5 | public static int get(int[] n) { 6 | if (n == null || n.length == 0) 7 | return 1; 8 | 9 | for (int i = 0; i < n.length; i++) { 10 | while (n[i] != i + 1 && n[i] <= n.length && n[i] > 0) { 11 | int temp = n[i]; // 1 12 | n[i] = n[temp - 1]; // 10 13 | n[temp - 1] = temp; // n[0] = 1 14 | } 15 | } 16 | 17 | for (int i = 0; i < n.length; i++) 18 | if (n[i] != i + 1) 19 | return i + 1; 20 | 21 | return n.length + 1; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/pramp/Interview8.java: -------------------------------------------------------------------------------- 1 | package pramp; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Given an array find any pair that sums up to the given target. Take care of 8 | * overflows. 9 | * 10 | * @author: shivam.maharshi 11 | */ 12 | public class Interview8 { 13 | 14 | public static int[] get(int[] a, int s) { 15 | if (a == null || a.length == 0) 16 | return new int[] { -1 }; 17 | 18 | Map m = new HashMap<>(); 19 | 20 | for (int i = 0; i < a.length; i++) { 21 | if (m.containsKey(s - a[i])) 22 | return new int[] { i, m.get(s - a[i]) }; 23 | else 24 | m.put(a[i], i); 25 | } 26 | 27 | return new int[] { -1 }; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/pramp/Interview9.java: -------------------------------------------------------------------------------- 1 | package pramp; 2 | 3 | /** 4 | * Given time availabilities for two people and a duration for meeting between 5 | * them, find the earliest available time slot where they can conduct schedule 6 | * the meeting. If there is no such time slot then return an empty array. 7 | * 8 | * @author: shivam.maharshi 9 | */ 10 | public class Interview9 { 11 | 12 | public static int[] get(int[][] ta, int[][] tb, int dur) { 13 | int[] r = new int[2]; 14 | if (ta == null || ta.length == 0 || tb == null || tb.length == 0) 15 | return r; 16 | int i = 0, j = 0; 17 | 18 | while (i < ta.length && j < tb.length) { 19 | int start = Math.max(ta[i][0], tb[j][0]), end = Math.min(ta[i][1], tb[j][1]); 20 | if (end - start >= dur) { 21 | r[0] = start; 22 | r[1] = end; 23 | return r; 24 | } else { 25 | if (i == ta.length - 1) 26 | j++; 27 | else if (j == tb.length - 1) 28 | i++; 29 | else if (ta[i][1] < tb[j][1]) 30 | i++; 31 | else 32 | j++; 33 | } 34 | } 35 | return r; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/puzzles/CircularSwordKilling.java: -------------------------------------------------------------------------------- 1 | package puzzles; 2 | 3 | /** 4 | * People standing in a circle pass a sword and start killing the next one to 5 | * them. Who will be the one left at the end. 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class CircularSwordKilling { 10 | 11 | /* 12 | * If number is power of 2, the one who started sword passing is the one who 13 | * will survive at the end. If it is not, then the one person who has the 14 | * sword when the remaining people left are exactly power of 2 will be the 15 | * answer. 16 | */ 17 | public static int solve(int n) { 18 | int k = getMaxPowerOf2Value(n); 19 | return 2 * (n - k) + 1; 20 | } 21 | 22 | public static int getMaxPowerOf2Value(int n) { 23 | int num = 1; 24 | while (num <= n) { 25 | num *= 2; 26 | } 27 | return num / 2; 28 | } 29 | 30 | public static void main(String[] args) { 31 | System.out.println(solve(100)); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/recursion/CountDecoding.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | public class CountDecoding { 4 | 5 | public static int countDecoding(int[] digit, int n) { 6 | 7 | int res = 0; 8 | 9 | if (n == 0 || n == 1) { 10 | return 1; 11 | } 12 | 13 | res = countDecoding(digit, n - 1); 14 | 15 | if (digit[n] < 2 || (digit[n] == 2 && digit[n - 1] < 7)) { 16 | res += countDecoding(digit, n - 2); 17 | } 18 | 19 | return res; 20 | 21 | } 22 | 23 | public static void main(String[] args) { 24 | System.out.println(CountDecoding.countDecoding(new int[] { 4,3,2,1 }, 3)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/recursion/ExpressionTree.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import ds.BinaryTree; 4 | 5 | /** 6 | * Expression tree is a binary tree in which each internal node corresponds to 7 | * operator and each leaf node corresponds to operand 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class ExpressionTree { 12 | 13 | public static int calculateExpression(BinaryTree root) { 14 | // TODO: 15 | return 0; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/recursion/KnapSnackProblem.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | /** 4 | * Given numbers and their corresponding weights and a given max weight, find 5 | * the maximum sum achieved using the given numbers. 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class KnapSnackProblem { 10 | 11 | public static int getMaxSum(int[] n, int[] w, int W, int i) { 12 | if (i >= n.length || W == 0) { 13 | return 0; 14 | } else if (w[i] > W) { 15 | return getMaxSum(n, w, W, i+1); 16 | } else { 17 | return Math.max(n[i] + getMaxSum(n, w, W - w[i], i+i), getMaxSum(n, w, W, i+1)); 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | int[] n = new int[] { 60, 100, 120 }; 23 | int[] w = new int[] { 1, 2, 3 }; 24 | int W = 5; 25 | System.out.println(getMaxSum(n, w, W, 0)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/recursion/NonIncreasingSequence.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | // Print non increasing sequence that sum to the given value. 4 | public class NonIncreasingSequence { 5 | 6 | // TODO: Improve using dynamic programming. 7 | public static void getSequence(int n, int max, String s) { 8 | if (n == 0) { 9 | System.out.println(s); 10 | return; 11 | } 12 | for (int i = 1; i <= max; i++) { 13 | if (n >= i) { 14 | getSequence(n - i, i, s + i); 15 | } 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | NonIncreasingSequence.getSequence(3, 3, ""); 21 | } 22 | 23 | } 24 | 25 | class Set { 26 | int num; 27 | int max; 28 | 29 | public Set(int n, int m) { 30 | num = n; 31 | max = m; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/recursion/NumberToAlphabetDecoding.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | // Print all number to alphabet decoding. 7 | public class NumberToAlphabetDecoding { 8 | 9 | public static void printDecoding(int[] arr, int index, List res, String word) { 10 | if (index >= arr.length) { 11 | res.add(word); 12 | System.out.println(word); 13 | return; 14 | } 15 | String oneWord = word + getChar(arr[index]); 16 | printDecoding(arr, index + 1, res, oneWord); 17 | if (index < arr.length - 1) { 18 | int twoDigit = arr[index] * 10 + arr[index + 1]; 19 | if (twoDigit < 27) { 20 | String twoWord = word + getChar(twoDigit); 21 | printDecoding(arr, index + 2, res, twoWord); 22 | } 23 | } 24 | } 25 | 26 | private static char getChar(int num) { 27 | return (char) (num + 65); 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[] arr = new int[] {9,0}; 32 | NumberToAlphabetDecoding.printDecoding(arr, 0, new ArrayList(), ""); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/recursion/PossibleParenthesisCombination.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /* 7 | * Print all the possible valid combinations of parenthesis for a given N pair. 8 | */ 9 | public class PossibleParenthesisCombination { 10 | 11 | public static void printAllValidComb(int N, int openCount, int closeCount, List set, String s) { 12 | if (openCount > N || closeCount > N || closeCount > openCount) { 13 | return; 14 | } 15 | if (openCount == N && closeCount == N) { 16 | set.add(s); 17 | return; 18 | } 19 | if (openCount < N) { 20 | s += "("; 21 | printAllValidComb(N, openCount + 1, closeCount, set, s); 22 | } 23 | if (closeCount < N && closeCount <= openCount) { 24 | s += ")"; 25 | printAllValidComb(N, openCount, closeCount + 1, set, s); 26 | } 27 | } 28 | 29 | public static void main(String[] args) { 30 | List set = new ArrayList(); 31 | PossibleParenthesisCombination.printAllValidComb(3, 1, 0, set, "("); 32 | for (String s : set) { 33 | System.out.println(s); 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/recursion/PrintAllPossiblePathsInMatrix.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.List; 4 | 5 | public class PrintAllPossiblePathsInMatrix { 6 | 7 | public static void printAllPath ( Point s, Point d, List list) { 8 | if (s.equals(d)) { 9 | list.add(s); 10 | return; 11 | } 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/recursion/PrintAllSubset.java: -------------------------------------------------------------------------------- 1 | package recursion; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class PrintAllSubset { 7 | 8 | public static void printAllSubset(List set, int index, List subsets) { 9 | int length = set.size(); 10 | if (index == length) { 11 | return; 12 | } 13 | int subsetLength = subsets.size(); 14 | for (int i = 0; i < subsetLength; i++) { 15 | String subset = subsets.get(i) + set.get(index); 16 | System.out.println(subset); 17 | subsets.add(subset); 18 | } 19 | printAllSubset(set, ++index, subsets); 20 | } 21 | 22 | public static void main(String[] args) { 23 | List subsets = new ArrayList(); 24 | subsets.add(""); 25 | List set = new ArrayList(); 26 | set.add("a"); 27 | set.add("b"); 28 | set.add("c"); 29 | printAllSubset(set, 0, subsets); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/sorting/AlmostSortedArrSearch.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Given an array which is sorted, but after sorting some elements are moved to 5 | * either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or 6 | * arr[i-1]. 7 | * 8 | * Link: http://www.geeksforgeeks.org/search-almost-sorted-array/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class AlmostSortedArrSearch { 13 | 14 | // TODO: 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/sorting/BinaryInsertionSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | public class BinaryInsertionSort { 4 | 5 | /* 6 | * Write code for binary insertion sort. This is insertion sort with binary 7 | * technique followed to insert number. 8 | */ 9 | 10 | // TODO: 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/sorting/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Given a sorted array arr[] of n elements, write a function to search a given 5 | * element x in arr[]. 6 | * 7 | * Link: http://geeksquiz.com/binary-search/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class BinarySearch { 12 | 13 | // Return index of n by binary search. 14 | public static int find(int[] a, int n) { 15 | int l = 0, h = a.length - 1; 16 | while (h >= l) { 17 | // (l+h)/2 can cause overflow. 18 | // http://www.geeksforgeeks.org/problem-binary-search-implementations/ 19 | int mid = l + ((h - l) / 2); 20 | if (a[mid] == n) 21 | return mid; 22 | else if (a[mid] > n) 23 | h = mid - 1; 24 | else 25 | l = mid + 1; 26 | } 27 | return -1; // Never reachable. 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/sorting/BucketSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Sort numbers using Bucket Sort. 7 | * 8 | * Link: http://www.geeksforgeeks.org/bucket-sort-2/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class BucketSort { 13 | 14 | public static void sort(int[] a, int maxVal) { 15 | int[] bucket = new int[maxVal + 1]; 16 | 17 | for (int i = 0; i < bucket.length; i++) { 18 | bucket[i] = 0; 19 | } 20 | 21 | for (int i = 0; i < a.length; i++) { 22 | bucket[a[i]]++; 23 | } 24 | 25 | int outPos = 0; 26 | for (int i = 0; i < bucket.length; i++) { 27 | for (int j = 0; j < bucket[i]; j++) { 28 | a[outPos++] = i; 29 | } 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | int maxVal = 15; 35 | int[] data = { 5, 3, 0, 2, 4, 1, 0, 15, 2, 3, 1, 14 }; 36 | 37 | System.out.println("Before: " + Arrays.toString(data)); 38 | sort(data, maxVal); 39 | System.out.println("After: " + Arrays.toString(data)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/sorting/FindKClosestElement.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Given a sorted array arr[] and a value X, find the k closest elements to X in 5 | * arr[]. 6 | * 7 | * Link: http://www.geeksforgeeks.org/find-k-closest-elements-given-value/ 8 | * 9 | * @author shivam.maharshi 10 | */ 11 | public class FindKClosestElement { 12 | 13 | public static void find(int[] a, int n, int k) { 14 | int index = BinarySearch.find(a, n); 15 | int[] res = new int[k]; 16 | int i = index + 1, j = index - 1; 17 | int count = 0; 18 | while (count < k) { 19 | if (i >= a.length && j < 0) { 20 | break; 21 | } else if (i < a.length && j >= 0) { 22 | if (Math.abs(a[i] - n) <= Math.abs(a[j] - n)) { 23 | res[count] = a[i]; 24 | i++; 25 | } else { 26 | res[count] = a[j]; 27 | j--; 28 | } 29 | } else if (i < a.length) { 30 | res[count] = a[i]; 31 | i++; 32 | } else { 33 | res[count] = a[j]; 34 | j--; 35 | } 36 | count++; 37 | } 38 | for (int num : res) 39 | System.out.print(num + " "); 40 | } 41 | 42 | public static void main(String[] args) { 43 | int a[] = { 12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56 }; 44 | find(a, 35, 4); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/sorting/GivenSumTwoElements.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Find a pair in the array that sum to N. 8 | * 9 | * Link: http://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n- 10 | * numbers-and-another-number-x-determines-whether-or-not-there-exist-two- 11 | * elements-in-s-whose-sum-is-exactly-x/ 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class GivenSumTwoElements { 16 | 17 | public static void givenSumTwoElements(int[] arr, int sum) { 18 | 19 | Map set = new HashMap(); 20 | 21 | for (int i = 0; i < arr.length; i++) { 22 | int diff = sum - arr[i]; 23 | if (!set.containsKey(diff)) { 24 | set.put(arr[i], null); 25 | } else { 26 | System.out.println("Sum : " + sum + " = " + diff + " + " + arr[i]); 27 | } 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | givenSumTwoElements(new int[] { 4, 9, 1, 6, 3, 2 }, 7); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/sorting/InterpolationSearch.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Assumes uniform distribution of numbers. Gives average case O(log(log(n))). 5 | * Given numbers are sorted too. 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class InterpolationSearch { 10 | 11 | public static int interpolationSearch(int[] arr, int key) { 12 | int low = 0; 13 | int high = arr.length - 1; 14 | int mid; 15 | 16 | while (arr[high] != arr[low] && key >= arr[low] && key <= arr[high]) { 17 | mid = low + (key - arr[low]) * ((high - low) / (arr[high] - arr[low])); 18 | 19 | if (arr[mid] < key) 20 | low = mid + 1; 21 | else if (key < arr[mid]) 22 | high = mid - 1; 23 | else 24 | return mid; 25 | } 26 | 27 | if (key == arr[low]) 28 | return low; 29 | else 30 | return -1; 31 | } 32 | 33 | public static void main(String[] args) { 34 | int[] arr = new int[] { 1, 2, 3, 7, 9, 15, 20 }; 35 | System.out.println(InterpolationSearch.interpolationSearch(arr, 7)); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/sorting/LeastDifferencePair.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Given a sorted array and a number, find the pair whose sum is closest to 5 | * number. 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class LeastDifferencePair { 10 | 11 | public static Pair getClosestPair() { 12 | return new Pair(); 13 | // TODO: 14 | } 15 | 16 | } 17 | 18 | class Pair { 19 | int x; 20 | int y; 21 | } -------------------------------------------------------------------------------- /src/main/java/sorting/NearlyKSortedArrSorting.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | import ds.MinHeap; 4 | 5 | /** 6 | * Given an array of n elements, where each element is at most k away from its 7 | * target position, devise an algorithm that sorts in O(n log k) time. 8 | * 9 | * Link: http://www.geeksforgeeks.org/nearly-sorted-algorithm/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class NearlyKSortedArrSorting { 14 | 15 | public static int[] sort(int[] a, int k) { 16 | int[] res = new int[a.length]; 17 | 18 | MinHeap heap = new MinHeap<>(Integer.class, k); 19 | 20 | for (int i = 0; i < k; i++) { 21 | heap.add(new Integer(a[i])); 22 | } 23 | 24 | for (int i = k; i < a.length; i++) { 25 | res[i - k] = heap.extractMin(); 26 | heap.add(new Integer(a[i])); 27 | } 28 | 29 | for (int i = a.length - k; i < a.length; i++) { 30 | res[i] = heap.extractMin(); 31 | } 32 | 33 | for (int n : res) 34 | System.out.print(n + " "); 35 | 36 | return res; 37 | } 38 | 39 | public static void main(String[] args) { 40 | int a[] = { 2, 6, 3, 12, 56, 8 }; 41 | sort(a, 3); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/sorting/RadixSort.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * What if the elements are in range from 1 to n2? Radix Sort is the answer. In 5 | * linear time we can solve this. Here we have assumed the base as 10. For 6 | * linear time convert all the numbers into base n and then count sort them for 7 | * linear complexity. 8 | * 9 | * Link: http://www.geeksforgeeks.org/radix-sort/ 10 | * 11 | * @author shivam.maharshi 12 | */ 13 | public class RadixSort { 14 | 15 | // For simplicity base is considered 10. 16 | public static int[] sort(int[] arr, int n) { 17 | int[][] a = convert(arr, n); 18 | int digit = a[0].length; 19 | // TODO: 20 | return null; 21 | } 22 | 23 | public static int[][] convert(int[] arr, int n) { 24 | int[][] a = new int[arr.length][(int) Math.log10(n)+1]; 25 | for (int i = 0; i < a.length; i++) { 26 | int num = arr[i]; 27 | int j = a[0].length - 1; 28 | while (num != 0) { 29 | a[i][j] = num % 10; 30 | num /= 10; 31 | j--; 32 | } 33 | } 34 | return a; 35 | } 36 | 37 | public static void main(String[] args) { 38 | int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; 39 | convert(arr, 802); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/sorting/SortedBinaryArray.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Count 1's in a sorted binary array. Like - arr = [1,1,1,1,1,0,0,0,0,0] 5 | */ 6 | public class SortedBinaryArray { 7 | 8 | // Do a binary search, can do in O(log(n)). 9 | public static int getCount() { 10 | return 0; 11 | // TODO: 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/sorting/StrictlyIncreasingMatrix.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Find a number in a matrix that is strictly increasing, row and column wise. 5 | * Print its location. 6 | * 7 | * Link: http://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted- 8 | * matrix/ 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class StrictlyIncreasingMatrix { 13 | 14 | public static void findNum(int[][] arr, int num) { 15 | int row = 0; 16 | int col = arr[0].length - 1; 17 | while (col >= 0 && row < arr.length) { 18 | if (arr[row][col] == num) { 19 | System.out.println("Row : " + row + " , Col : " + col); 20 | return; 21 | } else if (num < arr[row][col]) { 22 | col--; 23 | } else { 24 | row++; 25 | } 26 | } 27 | System.out.println("Number not found."); 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[][] arr = new int[][] { { 1, 2, 3, 4 }, { 50, 600, 7000, 8000 }, { 90, 1000, 11000, 12000 }, 32 | { 130, 1400, 15000, 16000 } }; 33 | StrictlyIncreasingMatrix.findNum(arr, 15000); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/sorting/WaveSorting.java: -------------------------------------------------------------------------------- 1 | package sorting; 2 | 3 | /** 4 | * Given an unsorted array of integers, sort the array into a wave like array. 5 | * An array arr[0..n-1] is sorted in wave form if arr[0] >= arr[1] <= arr[2] 6 | * >= arr[3] <= arr[4] > 7 | * 8 | * Link: http://www.geeksforgeeks.org/sort-array-wave-form-2/ 9 | * 10 | * @author shivam.maharshi 11 | * 12 | */ 13 | public class WaveSorting { 14 | 15 | // TODO: 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/string/LongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Find the longest string (or strings) that is a substring (or are substrings) 5 | * of two or more strings. 6 | * 7 | * Link: 8 | * https://en.wikipedia.org/wiki/Longest_common_substring_problem#Suffix_tree 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class LongestCommonSubstring { 13 | 14 | // TODO: 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/string/Search2DArray.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Search the given pattern in all 8 directions for the given word in the given grid. 5 | * 6 | * Link: http://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/ 7 | * 8 | * @author shivam.maharshi 9 | */ 10 | public class Search2DArray { 11 | 12 | public static void getPattern(int[][] a, int pattern) { 13 | 14 | } 15 | 16 | public static void main(String[] args) { 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/string/SearchPatternNaive.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Search pattern naively with worst case complexity O(m*(n-m+1)). 8 | * 9 | * Link: 10 | * http://www.geeksforgeeks.org/searching-for-patterns-set-1-naive-pattern- 11 | * searching/ 12 | * 13 | * @author shivam.maharshi 14 | */ 15 | public class SearchPatternNaive { 16 | 17 | public static List match(String s, String p) { 18 | List pl = new ArrayList(); 19 | int start = 0, i = 0, j = 0; 20 | if (s.length() >= p.length()) { 21 | while (start <= s.length() - p.length()) { 22 | if (s.charAt(i) == p.charAt(j)) { 23 | if (j == p.length() - 1) { 24 | pl.add(start); 25 | j = 0; 26 | start++; 27 | i = start; 28 | } 29 | i++; 30 | j++; 31 | } else { 32 | j = 0; 33 | start++; 34 | i = start; 35 | } 36 | } 37 | } 38 | return pl; 39 | } 40 | 41 | public static void main(String[] args) { 42 | List pl = SearchPatternNaive.match("abcdefabcdgrabcdgr", "abcdgr"); 43 | for (int p : pl) 44 | System.out.println("Pattern at : " + p); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/string/SearchPatternNaiveOptimized.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Consider a situation where all characters of pattern are different. Can we 8 | * modify the original Naive String Matching algorithm so that it works better 9 | * for these types of patterns. 10 | * 11 | * Link: 12 | * http://www.geeksforgeeks.org/pattern-searching-set-4-a-naive-string-matching- 13 | * algo-question/ 14 | * 15 | * @author shivam.maharshi 16 | */ 17 | public class SearchPatternNaiveOptimized { 18 | 19 | public static List match(String s, String p) { 20 | List list = new ArrayList(); 21 | int i = 0, j = 0; 22 | while (i < s.length()) { 23 | if (s.charAt(i) == p.charAt(j)) { 24 | if (j == p.length() - 1) { 25 | list.add(i - p.length() + 1); 26 | j = 0; 27 | } else { 28 | j++; 29 | } 30 | i++; 31 | } else { 32 | if (j == 0) 33 | i++; 34 | else 35 | j = 0; 36 | } 37 | } 38 | for (int index : list) 39 | System.out.println("Pattern at : " + index); 40 | return list; 41 | } 42 | 43 | public static void main(String[] args) { 44 | match("ABCEABCDABCEABCD", "ABCD"); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/string/StringPermutationsWithoutDuplicateCharacters.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Print all string permutations for a string which doesn't have any duplicates 8 | * characters. 9 | * 10 | * @author shivam.maharshi 11 | */ 12 | public class StringPermutationsWithoutDuplicateCharacters { 13 | 14 | public static void main(String[] args) { 15 | print("abc"); 16 | } 17 | 18 | public static void print(String s) { 19 | List set = new ArrayList(); 20 | for (char c : s.toCharArray()) 21 | set.add(c); 22 | print("", set); 23 | } 24 | 25 | public static void print(String s, List cl) { 26 | if (cl.isEmpty()) 27 | System.out.println(s); 28 | 29 | for (int i = 0; i < cl.size(); i++) { 30 | char c = cl.get(i); 31 | cl.remove(i); // Remove from set as it is used. 32 | print(s + c, cl); 33 | cl.add(i, c); // Backtrack 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/string/ZigZagArray.java: -------------------------------------------------------------------------------- 1 | package string; 2 | 3 | /** 4 | * Create a zig zag array from a given array that contains highest, lowest, 5 | * second highest, second lowest and so on elements. O(nLog(n)) time. 6 | * 7 | * @author shivam.maharshi 8 | */ 9 | public class ZigZagArray { 10 | 11 | public static int[] wiggleArrangeArray(int[] intArr) { 12 | int[] res = new int[intArr.length]; 13 | java.util.Arrays.sort(intArr); 14 | res = new int[intArr.length]; 15 | int i = 0, l = 0, h = intArr.length - 1; 16 | while (i < intArr.length) { 17 | res[i] = intArr[h]; 18 | h--; 19 | i++; 20 | if (i < intArr.length) { 21 | res[i] = intArr[l]; 22 | l++; 23 | i++; 24 | } 25 | } 26 | return res; 27 | } 28 | 29 | } 30 | --------------------------------------------------------------------------------