├── .github └── workflows │ └── codeql-analysis.yml ├── .gitignore ├── AlgoExpert ├── AllKindsOfNodeDepths.java ├── ApartmentHunting.java ├── BSTConstruction.java ├── BoggleBoard.java ├── BreadthFirstSearch.java ├── CalenderMatching.java ├── ContinuousMedianHandlerImpl.java ├── FindClosestValueInBST.java ├── FindLoop.java ├── FindNodesDistanceK.java ├── FlattenBinaryTree.java ├── GlobalMatching.java ├── InterweavingStrings.java ├── InvertBinaryTree.java ├── InvertBisection.java ├── KnapsackProblem.java ├── LRUCacheImpl.java ├── LongestStringChain.java ├── LowestCommonManager.java ├── MaxProfitWithKTranactions.java ├── MaxSubSetSumNoAdjacent.java ├── MergeSortedArrays.java ├── MinMaxStackConstruction.java ├── MinNumberOfCoinsForChange.java ├── NumbersInPi.java ├── PalindromePartitioningMinCuts.java ├── PatternMatcher.java ├── QuickSelect.java ├── RectangleMania.java ├── RunLengthEncoding.java ├── ShiftLinkedList.java ├── ShortenPath.java ├── SmallestDifference.java ├── SpiralTraverse.java ├── SquareOfZeros.java ├── StaircaseTraversal.java ├── SubArraySort.java ├── SuffixTrieConstruction.java ├── ThreeNumberSum.java ├── ValidIPAddresses.java ├── ValidateSubsequence.java └── WaterArea.java ├── Algorithms ├── binarysearch │ ├── BinarySearch.java │ ├── BoatsToSavePeople.java │ ├── ClosestBinarySearch.java │ ├── ClosestBinarySearchTreeValue.java │ ├── CompareStringsByFrequencyOfTheSmallestCharacter.java │ ├── CreateSortedArrayThroughInstructions.java │ ├── FindKClosestElements.java │ ├── FindKthSmallestPairDistance.java │ ├── FindMinimumInRotatedSortedArray.java │ ├── FindMinimumInRotatedSortedArrayII.java │ ├── FindPeakElement.java │ ├── FindRange.java │ ├── FindSmallestLetterGreaterThanTarget.java │ ├── FirstBadVersion.java │ ├── FloorAndCeilingOfANumber.java │ ├── GuessNumberHigherOrLower.java │ ├── IntersectionOfTwoArrays.java │ ├── IntersectionOfTwoArraysII.java │ ├── KokoEatingBananas.java │ ├── KthSmallestElementInaBST.java │ ├── LeftmostColumnWithAtLeastAOne.java │ ├── LongestDuplicateSubstring.java │ ├── MaxInBitonicArray.java │ ├── MedianOfTwoSortedArrays.java │ ├── MinimumDifference.java │ ├── NextLetter.java │ ├── OrderAgnosticBinarySearch.java │ ├── Pow.java │ ├── PowerOfTwo.java │ ├── RandomPickWithBlacklist.java │ ├── RandomPickWithWeight.java │ ├── RandomPointInNonOverlappingRectangles.java │ ├── RotationCountOfRotatedArray.java │ ├── SearchA2DMatrixII.java │ ├── SearchBitonicArray.java │ ├── SearchForARange.java │ ├── SearchInASortedArrayOfUnknownSize.java │ ├── SearchInRotatedSortedArray.java │ ├── SearchInfiniteSortedArray.java │ ├── SearchInsertPosition.java │ ├── SearchRotatedArray.java │ ├── SingleElementInASortedArray.java │ ├── Sqrt.java │ └── TwoSumIIInputArrayIsSorted.java ├── coursera │ ├── CourseraAlgoRevision.java │ ├── README.md │ ├── Rough_Explanation.xlsx │ ├── Week1Assign1.java │ ├── Week1Assign2.java │ ├── Week2Fibonacci.java │ ├── Week2FibonacciLastDigit.java │ ├── Week2FibonacciLastDigitOfSum.java │ ├── Week2FibonacciLastDigitOfSumOfSquare.java │ ├── Week2FibonacciMod.java │ ├── Week2GCD.java │ ├── Week2LCM.java │ ├── Week3CarFueling.java │ ├── Week3CollectingSignatures.java │ ├── Week3GroupingChildren.java │ ├── Week3MaximizingTheNumberOfPrize.java │ ├── Week3MaximumAdvertisementRevenue.java │ ├── Week3MaximumSalary.java │ ├── Week3MaximumValueOfLoot.java │ ├── Week3MoneyChange.java │ ├── Week4BinarySearch.java │ ├── Week4ClosestPoints.java │ ├── Week4ImprovingQuickSort.java │ ├── Week4MajorityElement.java │ ├── Week4NumberOfInversions.java │ ├── Week4OrganizingALottery.java │ ├── Week5EditDistance.java │ ├── Week5LongestCommonSubsequenceOfThreeSequences.java │ ├── Week5LongestCommonSubsequenceOfTwoSequences.java │ ├── Week5MoneyChange.java │ ├── Week5PrimitiveCalculator.java │ ├── Week6MaximumAmountOfGold.java │ ├── Week6MaximumValueOfArithmeticExpression.java │ └── Week6PartitioningSouvenirs.java ├── cycle-sort │ ├── AllMissingNumbers.java │ ├── CycleSort.java │ ├── FindCorruptNums.java │ ├── FindDuplicate.java │ ├── FirstKMissingPositive.java │ └── FirstSmallestMissingPositive.java ├── design │ ├── CreateALeastRecentlyUsedRandomShufflePlaylist.java │ ├── DesignExcelSumFormula.java │ ├── DesignRestaurant.java │ ├── DesignSearchAutocompleteSystem.java │ ├── DesignT9Predictor.java │ ├── DesignTicTacToe.java │ ├── EncodeAndDecodeTinyURL.java │ ├── LFUCacheImpl.java │ ├── RLEIteratorImpl.java │ ├── RandomizedCollectionImpl.java │ ├── RangeModuleImpl.java │ └── TimeBasedKeyValueStore.java ├── dfs-bfs │ ├── ArrayNesting.java │ ├── BinaryTreePath.java │ ├── CountGoodNodesInBinaryTree.java │ ├── DeleteNodesAndReturnForest.java │ ├── FindAllTreePaths.java │ ├── FloodFill.java │ ├── HasCommonAncestor.java │ ├── JumpGameIII.java │ ├── KillProcess.java │ ├── LevelOrderSuccessor.java │ ├── LongestBinaryTreePath.java │ ├── LongestIncreasingPathInAMatrix.java │ ├── MaximumWidthOfBinaryTree.java │ ├── MostStonesRemovedWithSameRowOrColumn.java │ ├── PacificAtlanticWaterFlow.java │ ├── PathWithGivenSequence.java │ ├── ReachANumber.java │ ├── ReachableNodesInSubdividedGraph.java │ ├── ShortestDistanceFromAllBuildings.java │ ├── ShortestPathInAGridWithObstaclesElimination.java │ ├── ShortestPathWithAlternatingColors.java │ ├── TreeDiameter.java │ └── WordLadderII.java ├── divide-conquer │ └── ClosestPairOfPoints.java ├── dynamic-problem │ ├── ArithmeticSlicesIiSubsequence.java │ ├── ArrangingCoins.java │ ├── BellNumbers.java │ ├── BestTimeToBuyAndSellStockIII.java │ ├── BestTimeToBuyAndSellStockIV.java │ ├── BestTimeToBuyAndSellStockWithCooldown.java │ ├── BestTimeToBuyAndSellStockWithTransactionFee.java │ ├── BinomialCoefficient.java │ ├── CherryPickup.java │ ├── CherryPickupII.java │ ├── ConstructKPalindromeStrings.java │ ├── CountNumbersWithUniqueDigits.java │ ├── CountSquareSubmatriceswithAllOnes.java │ ├── DistinctSubsequences.java │ ├── DungeonGame.java │ ├── EditDistance.java │ ├── FlipStringToMonotoneIncreasing.java │ ├── GreatestSumDivisibleByThree.java │ ├── HouseRobberII.java │ ├── HouseRobberIII.java │ ├── IntegerBreak.java │ ├── LargestDivisibleSubset.java │ ├── LargestPlusSign.java │ ├── LevenshteinDistance.java │ ├── LongestCommonSubsequence.java │ ├── LongestIncreasingSubsequence.java │ ├── LongestPalindromicSubstring.java │ ├── LongestRepeatingSubsequence.java │ ├── LongestTurbulentSubarray.java │ ├── LongestValidParentheses.java │ ├── MaximalSquare.java │ ├── MaximumLengthOfPairChain.java │ ├── MaximumSubarray.java │ ├── MinimumCostForTickets.java │ ├── MinimumCostToMergeStones.java │ ├── MinimumDifficultyOfAJobSchedule.java │ ├── MinimumNumberOfRefuelingStops.java │ ├── MinimumPathSum.java │ ├── MinimumWindowSubstring.java │ ├── New21Game.java │ ├── NthCatalanNumber.java │ ├── NumberOfCoins.java │ ├── NumberOfLongestIncreasingSubsequence.java │ ├── NumberOfSubmatricesThatSumToTarget.java │ ├── NumberOfWaysOfCuttingAPizza.java │ ├── NumberOfWaysToMakeChange.java │ ├── PalindromePartitioningIii.java │ ├── PalindromeRemoval.java │ ├── PartitionArrayForMaximumSum.java │ ├── PartitionEqualSubsetSum.java │ ├── PatchingArray.java │ ├── PerfectSquares.java │ ├── RangeSumQuery2DImmutable.java │ ├── RegularExpressionMatching.java │ ├── RussianDollEnvelopes.java │ ├── ShoppingOffers.java │ ├── ShortestPalindrome.java │ ├── SplitArrayLargestSum.java │ ├── StoneGameIII.java │ ├── StudentAttendanceRecordII.java │ ├── SubMatricesWithSumZero.java │ ├── TargetSum.java │ ├── TheMostSimilarPathInAGraph.java │ ├── UglyNumbers.java │ ├── UncrossedLines.java │ ├── UniquePaths.java │ ├── UniquePathsII.java │ ├── WiggleSubsequence.java │ └── WildcardMatching.java ├── fast-slowPointer │ ├── CircularArrayLoop.java │ ├── HappyNumber.java │ ├── LinkedListCycleLength.java │ ├── LinkedListCycleStart.java │ ├── MiddleOfLinkedList.java │ ├── PalindromicLinkedList.java │ └── RearrangeList.java ├── geometry │ ├── BestPositionForAServiceCentre.java │ ├── MaximumNumberOfVisiblePoints.java │ └── ValidSquare.java ├── greedy-algorithum │ ├── AdvantageShuffle.java │ ├── BagOfTokens.java │ ├── BestTimeToBuyAndSellStockII.java │ ├── BreakAPalindrome.java │ ├── Candy.java │ ├── CarFleet.java │ ├── CoinChange2.java │ ├── CourseScheduleIII.java │ ├── FindTheMostCompetitiveSubsequence.java │ ├── GasStation.java │ ├── GreedyFlorist.java │ ├── JumpGame.java │ ├── JumpGameII.java │ ├── LuckBalance.java │ ├── MaxMin.java │ ├── MaximumUnitsOnATruck.java │ ├── MinimumAbsoluteDifferenceInAnArray.java │ ├── MinimumCostToMoveChipsToTheSamePosition.java │ ├── MinimumDeletionCostToAvoidRepeatingLetters.java │ ├── MinimumDeletionsToMakeCharacterFrequenciesUnique.java │ ├── MinimumDifferenceBetweenLargestAndSmallestValueInThreeMoves.java │ ├── MinimumOperationsToReduceXToZero.java │ ├── NonOverlappingIntervals.java │ ├── QueueReconstructionByHeight.java │ ├── RemoveDuplicateLetters.java │ ├── ReorganizeString.java │ ├── RestoreTheArrayFromAdjacentPairs.java │ ├── SmallestSubsequenceOfDistinctCharacters.java │ ├── TaskScheduler.java │ ├── TextJustification.java │ ├── TrappingRainWater.java │ ├── ValidParenthesisString.java │ └── WaterBetweenPillars.java ├── heaps │ ├── MaximizeCapital.java │ ├── MedianOfAStream.java │ ├── MinimumIntervalToIncludeEachQuery.java │ ├── NextInterval.java │ ├── SingleThreadedCPU.java │ └── SlidingWindowMedian.java ├── interval │ ├── ConflictingAppointments.java │ ├── EmployeeFreeTime.java │ ├── InsertInterval.java │ ├── IntervalsIntersection.java │ ├── MaximumCPULoad.java │ ├── MeetingRoomsII.java │ ├── MergeIntervals.java │ ├── MinimumMeetingRooms.java │ ├── MinimumNumberOfArrowsToBurstBalloons.java │ ├── MyCalendarI.java │ ├── PartitionLabels.java │ ├── ProcessTasksUsingServers.java │ ├── RemoveCoveredIntervals.java │ ├── SetIntersectionSizeAtLeastTwo.java │ ├── TheKWeakestRowsInAMatrix.java │ └── TwoCityScheduling.java ├── island │ └── FindTheGridOfRegionAverage.java ├── kmp │ └── FindPatternInString.java ├── others │ ├── AVeryBigSum.java │ ├── BirthdayCakeCandles.java │ ├── CaesarCipher.java │ ├── CamelCase.java │ ├── CircularPalindromes.java │ ├── CompareTheTriplets.java │ ├── DiagonalDifference.java │ ├── HackerRankInAString.java │ ├── JackGoesToRapture.java │ ├── MagicSquare.java │ ├── MarsExploration.java │ ├── MiniMaxSum.java │ ├── Pangrams.java │ ├── PlusMinus.java │ ├── SolveMeFirst.java │ ├── Staircase.java │ ├── StrongPassword.java │ ├── SuperReducedString.java │ ├── TimeConversion.java │ ├── TwoCharacters.java │ └── WeightedUniformStrings.java ├── path │ ├── LongestLineOfConsecutiveOneInMatrix.java │ ├── MakingALargeIsland.java │ ├── Minesweeper.java │ ├── MinimumCostToMakeAtLeastOneValidPathInAGrid.java │ ├── NumberOfCornerRectangles.java │ ├── NumberOfDistinctIslands.java │ ├── PathWithMinimumEffort.java │ ├── RectangleOverLap.java │ ├── ShortestBridge.java │ ├── SlidingPuzzle.java │ ├── SnakesAndLadders.java │ ├── SquirrelSimulation.java │ ├── TheMazeII.java │ └── UniquePathsIII.java ├── recursion-backtracking │ ├── AddTwoNumbers.java │ ├── BeautifulArrangement.java │ ├── BuildBinaryExpressionTreeFromInfixExpression.java │ ├── ClimbingStairs.java │ ├── CombinationSumIII.java │ ├── Combinations.java │ ├── ConstructQuadTree.java │ ├── ConvertBinarySearchTreeToSortedDoublyLinkedList.java │ ├── CountSortedVowelStrings.java │ ├── DecodeWays.java │ ├── DecodeWaysII.java │ ├── ExpressionAddOperators.java │ ├── FallingSquares.java │ ├── FindAllAnagramsInAString.java │ ├── GenerateParentheses.java │ ├── IteratorForCombination.java │ ├── KthSymbolInGrammar.java │ ├── LargestRectangleInHistogram.java │ ├── LetterCombinationsOfAPhoneNumber.java │ ├── MaxTime.java │ ├── MaximumDepthOfBinaryTree.java │ ├── NQueensII.java │ ├── NumbersWithSameConsecutiveDifferences.java │ ├── OptimalAccountBalancing.java │ ├── PalindromePartitioning.java │ ├── PermutationSequence.java │ ├── Permutations.java │ ├── Power.java │ ├── PrintBinaryTree.java │ ├── ProductSum.java │ ├── ReorderedPowerOf2.java │ ├── RestoreIPAddresses.java │ ├── ReverseString.java │ ├── RiverSize.java │ ├── RobotRoomCleaner.java │ ├── SameTree.java │ ├── SequentialDigits.java │ ├── Sort.java │ ├── StrobogrammaticNumber2.java │ ├── Subsets.java │ ├── SudokuSolver.java │ ├── SwapNodesInPairs.java │ ├── TheSkylineProblem.java │ └── UniqueBinarySearchTreesII.java ├── segmentTrees │ ├── RangeMinimumQuery.java │ ├── RangeSumQueryImmutable.java │ ├── RangeSumQueryMutable.java │ ├── SlidingWindowMaximum.java │ ├── SumsInTheMatrix.java │ └── SumsInTheMatrix.jpg ├── sliding-door │ ├── AverageOfSubarrayOfSizeK.java │ ├── CharacterReplacement.java │ ├── FruitsIntoBaskets.java │ ├── LongestContinuousSubarrayWithAbsoluteDiffLessThanOrEqualToLimit.java │ ├── LongestSubarray.java │ ├── LongestSubarrayWithOnesAfterReplacement.java │ ├── LongestSubstringWithAtLeastKRepeatingCharacters.java │ ├── LongestSubstringWithKDistinctCharacters.java │ ├── LongestSubstringWithSameLettersAfterReplacement.java │ ├── MaxValueOfEquation.java │ ├── MaximizeDistanceToClosestPerson.java │ ├── MaximumDistance.java │ ├── MaximumPointsYouCanObtainFromCards.java │ ├── MaximumSizeSubarraySumEqualsK.java │ ├── MaximumSumSubarrayOfSizeK.java │ ├── MinimumWindowSubsequence.java │ ├── MinimumWindowSubstringSD.java │ ├── NestedAnagrams.java │ ├── NoRepeatSubstring.java │ ├── NumberOfPartition.java │ ├── PartitionArrayIntoDisjointIntervals.java │ ├── PermutationInAString.java │ ├── ReplacingOnes.java │ ├── SmallestSubarrayWithAGivenSum.java │ ├── SmallestWindowContainingSubstring.java │ ├── StampingTheSequence.java │ ├── StringAnagrams.java │ ├── StringPermutation.java │ ├── SummaryRanges.java │ └── WordsConcatenation.java ├── sorting │ └── Sorting.java ├── subsets │ ├── CountUniqueTrees.java │ ├── EvaluateExpression.java │ ├── GeneralizedAbbreviation.java │ ├── LetterCaseStringPermutation.java │ ├── PartitionToKEqualSumSubsets.java │ ├── SubsetWithDuplicates.java │ └── UniqueTrees.java └── two-pointer │ ├── ArrayOfDoubledPairs.java │ ├── BackspaceCompare.java │ ├── BuddyStrings.java │ ├── DegreeOfAnArray.java │ ├── DetectCapital.java │ ├── DetermineIfTwoStringsAreClose.java │ ├── DutchFlag.java │ ├── ExpressiveWords.java │ ├── FindAllDuplicatesInAnArray.java │ ├── FindSmallestCommonElementInAllRows.java │ ├── FindTheCelebrity.java │ ├── FirstMissingPositive.java │ ├── KthMissingPositiveNumber.java │ ├── LongestMountainInArray.java │ ├── MaxNumberOfKSumPairs.java │ ├── MergeSortedArray.java │ ├── NextGreaterElementIII.java │ ├── NumberOfSubArraysOfSizeKAndAverageGreaterThanOrEqualToThreshold.java │ ├── OneEditDistance.java │ ├── PairWithTargetSum.java │ ├── QuadrupleSumToTarget.java │ ├── RemoveDuplicates.java │ ├── RemoveDuplicatesFromSortedArrayII.java │ ├── ReverseWordsInAStringII.java │ ├── SentenceScreenFitting.java │ ├── ShortestWindowSort.java │ ├── ShortestWordDistance.java │ ├── SortColors.java │ ├── SquaringASortedArray.java │ ├── SubarrayProductLessThanK.java │ ├── ThreeSumClosest.java │ ├── ThreeSumWithMultiplicity.java │ ├── TripletSumCloseToTarget.java │ ├── TripletSumToZero.java │ ├── TripletWithSmallerSum.java │ ├── TwoSumIIIDataStructureDesign.java │ ├── ValidMountainArray.java │ └── ValidPalindrome.java ├── All_Topics_top_leetcode_by_frequency.md ├── EPI_Questions_List.md ├── ImportantLinks.md ├── README.md ├── SECURITY.md ├── Top_LeetCode_Questions_By_Company.md ├── Top_LeetCode_Questions_By_Topic.md ├── blind75 ├── Blind75.md ├── arrays │ ├── BestTimeToBuyAndSellStock.java │ ├── ContainsDuplicate.java │ ├── FindMinimumInRotatedSortedArray.java │ ├── MaximumProductSubArray.java │ ├── MaximumSumSubArray.java │ ├── ProductOfArrayExceptSelf.java │ ├── ThreeSum.java │ └── TwoSum.java ├── interval │ ├── InsertInterval.java │ └── MergeInterval.java ├── linkedlist │ ├── LinkedListCycle.java │ ├── MergeKSortedLists.java │ ├── MergeTwoSortedLists.java │ ├── RemoveNthNodeFromEndOfList.java │ └── ReverseLinkedList.java ├── matrix │ ├── SetMatrixZeroes.java │ └── SpiralMatrix.java ├── strings │ ├── GroupAnagrams.java │ ├── LongestRepeatingCharacterReplacement.java │ ├── LongestSubstringWithoutRepeatingCharacters.java │ ├── MinimumWindowSubstring.java │ ├── ValidAnagram.java │ └── ValidParentheses.java ├── trees │ ├── BinaryTreeLevelOrderTraversal.java │ ├── BinaryTreeMaximumPathSum.java │ ├── InvertTree.java │ ├── MaximumDepthOfBinaryTree.java │ ├── SameTree.java │ └── SerializeAndDeserializeBinaryTree.java └── util │ ├── ListNode.java │ ├── Node.java │ ├── TreeNode.java │ └── Util.java ├── dataStructures ├── LinkedList │ ├── AddTwoNumbersII.java │ ├── AddTwoNumbersLinkedList.java │ ├── ConvertSortedListToBinarySearchTree.java │ ├── CopyListWithRandomPointer.java │ ├── DeepCopy.java │ ├── DesignLinkedList.java │ ├── FlattenAMultilevelDoublyLinkedList.java │ ├── FlattenNestedListIterator.java │ ├── InsertIntoACyclicSortedList.java │ ├── InsertingANodeIntoASortedDoublyLinkedList.java │ ├── IntersectionOfTwoLinkedLists.java │ ├── IsPalindrome.java │ ├── LinkedListCycle.java │ ├── LinkedListCycleII.java │ ├── LinkedListRandomNode.java │ ├── MergeKSortedLists.java │ ├── MergeTwoSortedLists.java │ ├── OddEvenLinkedList.java │ ├── PalindromeLinkedList.java │ ├── RemoveLinkedListElements.java │ ├── RemoveNthNodeFromEndOfList.java │ ├── ReorderList.java │ ├── ReverseEveryKElements.java │ ├── ReverseLinkedList.java │ ├── ReverseNodesInKGroup.java │ ├── ReverseSubList.java │ ├── RotateList.java │ ├── SortList.java │ └── SplitLinkedListInParts.java ├── arrays │ ├── CheckFirstUnique.java │ ├── CheckMinimum.java │ ├── CheckReArrange.java │ └── CheckSecondMax.java ├── arraysAndString │ ├── AddBinary.java │ ├── Anagram.java │ ├── AppleAndOrange.java │ ├── ArrayManipulation.java │ ├── ArrayPartitionI.java │ ├── BeautifulSegments.java │ ├── BestTimeToBuyAndSellStock.java │ ├── BetweenTwoSets.java │ ├── CaesarCipherEncryptor.java │ ├── CanYouSolveIt.java │ ├── CandiesDam.java │ ├── ChargedUpArray.java │ ├── CheckIfItIsAStraightLine.java │ ├── CityTravel.java │ ├── CompareVersionNumbers.java │ ├── CountAndSay.java │ ├── CountPrimes.java │ ├── CountingValleys.java │ ├── DesignerPDFViewer.java │ ├── DiagonalTraverse.java │ ├── DiagonalTraverseII.java │ ├── DynamicArray.java │ ├── EPIFormater.java │ ├── FastReader.java │ ├── FindPivotIndex.java │ ├── FindTheWinnerOfTheCircularGame.java │ ├── FindThreeLargestNumbers.java │ ├── FourSum.java │ ├── GameOfLife.java │ ├── GoatLatin.java │ ├── GoingToOffice.java │ ├── GradingStudents.java │ ├── GroupAnagrams.java │ ├── ImplementStrStr.java │ ├── IntegerToString.java │ ├── JumpingOnTheClouds.java │ ├── KPrefix.java │ ├── Kangaroo.java │ ├── LargestNumberAtLeastTwiceOfOthers.java │ ├── LargestRange.java │ ├── LeftRotation.java │ ├── LongestCommonPrefix.java │ ├── LongestPeak.java │ ├── LongestSubstringWithoutRepeating.java │ ├── Maahismathi.java │ ├── MaxConsecutiveOnes.java │ ├── MaximumSubArray.java │ ├── MaximumSubsetSumWithNoAdjesentElement.java │ ├── MaximumSumCircularSubarray.java │ ├── MaximumSumIncreasingSubSequence.java │ ├── MicroAndSweetDistribution.java │ ├── MinAndMaxStackConstruction.java │ ├── MinReward.java │ ├── MinimumDominoRotationsForEqualRow.java │ ├── MinimumSizeSubarraySum.java │ ├── MinimumSwaps.java │ ├── MissingRanges.java │ ├── MonkAndPowerOfTime.java │ ├── MonotonicArray.java │ ├── MoveElementToEnd.java │ ├── MoveZeroes.java │ ├── NSum.java │ ├── NeutralisationOfCharges.java │ ├── NewYearChaos.java │ ├── NextClosestTime.java │ ├── OnlineStockSpan.java │ ├── PairsHavingSimilarElements.java │ ├── PairsOfSongsWithTotalDurationsDivisibleBy60.java │ ├── PascalTriangle.java │ ├── PatternSyntaxChecker.java │ ├── PermutationInString.java │ ├── PlusOne.java │ ├── PossibleWordsPhone.java │ ├── PrefixMatch.java │ ├── RainSound.java │ ├── RansomNote.java │ ├── RemoveDuplicatesFromSortedArray.java │ ├── RemoveElement.java │ ├── RepeatedString.java │ ├── RepeatedSubstringPattern.java │ ├── ReverseWordsInAString.java │ ├── ReverseWordsInAStringIII.java │ ├── RotateArray.java │ ├── RotateArrayBy90.java │ ├── RottingOranges.java │ ├── RoyAndSymmetricLogos.java │ ├── SaveGotham.java │ ├── SearchInSortedMatrix.java │ ├── ShiftingLetters.java │ ├── SingleCycleCheck.java │ ├── SmallestString.java │ ├── SockMerchant.java │ ├── SortArrayByParityII.java │ ├── SortTheMatrixDiagonally.java │ ├── SparseArrays.java │ ├── SpiralMatrix.java │ ├── SpiralMatrixII.java │ ├── StudentAttendanceRecordI.java │ ├── ThreeSum.java │ ├── TrappingRain.java │ ├── TripletSum.java │ ├── TwoDArrayDS.java │ ├── TwoSum.java │ ├── TwoSumII.java │ ├── UglyNumber.java │ ├── UglyNumberII.java │ ├── VowelRecognition.java │ ├── WordBreak.java │ ├── WordBreakII.java │ ├── WordSearch.java │ ├── XTotalShapes.java │ ├── ZigZagConversion.java │ └── ZigZagTraversal.java ├── basicsAndMath │ ├── AddDigits.java │ ├── AngleBetweenHandsOfAClock.java │ ├── BillionUsersDay.java │ ├── BirthdayParty.java │ ├── ChampagneTower.java │ ├── CountingRhombi.java │ ├── DayOfTheWeek.java │ ├── DistributeCandiesToPeople.java │ ├── ExcelSheetColumnNumber.java │ ├── Java1DArrayPart2.java │ ├── JavaAnagrams.java │ ├── JavaArraylist.java │ ├── JavaBigDecimal.java │ ├── JavaComparator.java │ ├── JavaHashSet.java │ ├── JavaPrimalityTest.java │ ├── JavaPriorityQueue.java │ ├── JavaStack.java │ ├── JavaStringPalindrome.java │ ├── JavaStringTokens.java │ ├── JavaSubstringComparisons.java │ ├── LargestTimeForGivenDigits.java │ ├── MatrixRank.java │ ├── PoorPigs.java │ ├── PrisonCellsAfterNDays.java │ ├── RobotBoundedInCircle.java │ ├── RomanToInteger.java │ ├── ShuffleAnArrayImpl.java │ ├── SignOfTheProductOfAnArray.java │ ├── TagContentExtractor.java │ ├── TransformToChessboard.java │ └── ValidPerfectSquare.java ├── binarytree │ ├── AllElementsInTwoBinarySearchTrees.java │ ├── AllNodesDistanceKInBinaryTree.java │ ├── BalancedBinaryTree.java │ ├── BinarySearchTreeIterator.java │ ├── BinaryTree.java │ ├── BinaryTreeZigzagLevelOrderTraversal.java │ ├── BoundaryOfBinaryTree.java │ ├── BranchesSum.java │ ├── ConstructBinarySearchTreeFromPreorderTraversal.java │ ├── ConstructBinaryTreeFromInorderAndPostorderTraversal.java │ ├── ConstructBinaryTreeFromPreorderAndInorderTraversal.java │ ├── ConvertSortedArrayToBinarySearchTree.java │ ├── CountUnivalueSubtrees.java │ ├── CousinsInBinaryTree.java │ ├── CousinsInBinaryTreeII.java │ ├── DeleteNodeInABST.java │ ├── DesignAnExpressionTreeWithEvaluateFunction.java │ ├── DiameterOfBinaryTree.java │ ├── FindLargestValueInEachTreeRow.java │ ├── FindLeavesOfBinaryTree.java │ ├── FlipBinaryTreeToMatchPreorderTraversal.java │ ├── FlipEquivalentBinaryTrees.java │ ├── IncreasingOrderSearchTree.py │ ├── InorderSuccessorInBST.java │ ├── InsertIntoABinarySearchTree.java │ ├── KthLargestElementInAStream.java │ ├── LargestIndependentSet.java │ ├── LowestCommonAncestorOfABinarySearchTree.java │ ├── LowestCommonAncestorOfABinaryTree.java │ ├── MaximumAverageSubtree.java │ ├── MaximumDepthOfBinaryTree2.java │ ├── MaximumPathSum.java │ ├── MaximumProductOfSplittedBinaryTree.java │ ├── ModifyBinaryTree.java │ ├── PathSum.java │ ├── PathSumIII.java │ ├── PopulatingNextRightPointersInEachNode.java │ ├── PreOrderToPostOrder.java │ ├── PseudoPalindromicPathsInABinaryTree.java │ ├── RangeSumOfBST.java │ ├── SameBST.java │ ├── SameBSTs.java │ ├── SearchInABinarySearchTree.java │ ├── SerializeAndDeserializeBST.java │ ├── SerializeAndDeserializeBinaryTree.java │ ├── SmallestSubtreeWithAllTheDeepestNodes.java │ ├── SubtreeOfAnotherTree.java │ ├── SumOfLeftLeaves.java │ ├── SumOfRootToLeafBinaryNumbers.java │ ├── SymmetricTree.java │ ├── TraverseATree.java │ ├── ValentineSum.java │ ├── ValidateBinarySearchTree.java │ ├── VerifyPreorderSerializationOfABinaryTree.java │ └── VerticalOrderTraversalOfABinaryTree.java ├── bitwise │ ├── BitDifference.java │ ├── ConcatenationOfConsecutiveBinaryNumbers.java │ ├── ConvertANumberToHexadecimal.java │ ├── FindOdd.java │ ├── FindTheDuplicateNumber.java │ ├── FindTheMissingNumber.java │ ├── HammingDistance.java │ ├── MissingNumber.java │ ├── Mystery.java │ ├── NumberComplement.java │ ├── ReverseBits.java │ ├── SingleNumberIII.java │ └── SwapTwoNumber.java ├── coursera │ ├── README.md │ ├── W1CheckBrackets.java │ ├── W1ComputeTreeHeight.java │ ├── W1ExtendingStackInterface.java │ ├── W1NetworkPacketProcessingSimulation.java │ ├── W3DisJointSet.java │ ├── W3MakeHeap.java │ └── W3ParallelProcessing.java ├── graph │ ├── AlienDictionary.java │ ├── AllPathsFromSourceToTarget.java │ ├── CheapestFlightsWithinKStops.java │ ├── CircleOfStrings.java │ ├── CourseSchedule.java │ ├── CourseScheduleII.java │ ├── CriticalConnectionPointsAndBridge.java │ ├── CriticalConnectionsInANetwork.java │ ├── EulerPathAndCircuit.java │ ├── EvaluateDivision.java │ ├── FillSurroundedRegions.java │ ├── FindTheTownJudge.java │ ├── JumpGameIV.java │ ├── LowestCommonAncestor.java │ ├── MaximalNetworkRank.java │ ├── MaximumNumberOfAcceptedInvitations.java │ ├── MicroAndMaze.java │ ├── MinimizeMalwareSpread.java │ ├── MinimumHeightTrees.java │ ├── MinimumSpanningTree.java │ ├── NetworkDelayTime.java │ ├── NumberOfProvinces.java │ ├── OptimizeWaterDistributionInAVillage.java │ ├── PossibleBipartition.java │ ├── ReconstructItinerary.java │ ├── RemoveMaxNumberOfEdgesToKeepGraphFullyTraversable.java │ ├── RoadsAndLibraries.java │ ├── SerializeAndDeserializeGraph.java │ ├── ShortestPathProblem.java │ ├── TravelingSalesManProblem.java │ ├── UnionFindImpl.java │ └── hugeGraphData.txt ├── hashtable │ ├── AnagramTogether.java │ ├── AnalyzeUserWebsiteVisitPattern.java │ ├── BullsAndCows.java │ ├── CheckArrayFormationThroughConcatenation.java │ ├── ColorfulNumbers.java │ ├── ContainsDuplicate.java │ ├── ContainsDuplicateII.java │ ├── ContainsDuplicateIII.java │ ├── CountTriplets.java │ ├── DesignHashMap.java │ ├── DesignHashSet.java │ ├── DotProductOfTwoSparseVectors.java │ ├── DoubleShuffle.java │ ├── EmployeeImportance.java │ ├── EqualCountPairs.java │ ├── FindAndReplaceInString.java │ ├── FindDuplicateSubtrees.java │ ├── FindWinnerOnATicTacToeGame.java │ ├── FirstUniqueCharacterInAString.java │ ├── FirstUniqueNumber.java │ ├── FourSumII.java │ ├── FrequencyQueries.java │ ├── GroupShiftedStrings.java │ ├── HashTablesRansomNote.java │ ├── InsertDeleteGetRandom.java │ ├── IsomorphicStrings.java │ ├── JewelsAndStones.java │ ├── KdiffPairsInAnArray.java │ ├── LoggerRateLimiter.java │ ├── LongestSubstringWithoutRepeatingCharacters.java │ ├── MagicSquaresInGrid.java │ ├── MajorityElement.java │ ├── MaximumFrequencyStack.java │ ├── MaximumNumberOfBalloons.java │ ├── MinimumIndexSumOfTwoLists.java │ ├── NumberOfBoomerangs.java │ ├── NumberOfMatchingSubsequences.java │ ├── RepeatedDNASequences.java │ ├── Roman2Integer.java │ ├── SherlockAndAnagrams.java │ ├── SingleNumber.java │ ├── SingleNumberII.java │ ├── SnapshotArrayImpl.java │ ├── SortCharactersByFrequency.java │ ├── SubdomainVisitCount.java │ ├── TwoStrings.java │ ├── TwoSumArray.java │ ├── UniqueList.java │ ├── UniqueWordAbbreviation.java │ ├── ValidSudoku.java │ ├── VowelSpellchecker.java │ └── WordPattern.java ├── heapAndSort │ ├── ContiguousArray.java │ ├── FindRightInterval.java │ ├── HIndex.java │ ├── KClosestPointsToOrigin.java │ ├── LargestNumber.java │ ├── LastStoneWeight.java │ ├── MinHeapConstruction.java │ ├── MinimizeDeviationInArray.java │ ├── PancakeSorting.java │ ├── RemoveKDigits.java │ ├── SplitWordCount.java │ ├── TopKFrequentElements.java │ └── kClosestNeighbour.java ├── narraytree │ ├── AddAndSearchWordDataStructureDesign.java │ ├── EncodeNaryTreeToBinaryTree.java │ ├── ImplementTrie.java │ ├── MapSumPairs.java │ ├── MaximumDepthOfNaryTree.java │ ├── MaximumXOROfTwoNumbersInAnArray.java │ ├── NaryTreeLevelOrderTraversal.java │ ├── NaryTreePostorderTraversal.java │ ├── NaryTreePreorderTraversal.java │ ├── PalindromePairs.java │ ├── PrefixAndSuffixSearch.java │ ├── PrintFileStructure.java │ ├── ReplaceWords.java │ ├── SearchSuggestionsSystem.java │ ├── SerializeAndDeserializeNaryTree.java │ ├── StreamOfCharacters.java │ ├── SubtreeWithMaximumAverage.java │ ├── WordSearchII.java │ └── WordSquares.java ├── queue │ ├── CardRotation.java │ ├── DailyTemperatures.java │ ├── DecodeString.java │ ├── DesignCircularQueue.java │ ├── ImplementQueue.java │ ├── ImplementStack.java │ ├── IntervalListIntersections.java │ ├── KeysAndRooms.java │ ├── MinStackImpl.java │ ├── MovingAverageFromDataStream.java │ ├── NumberOfIslands.java │ ├── NumberOfRecentCalls.java │ ├── OpenTheLock.java │ ├── QueueUsingTwoStacks.java │ ├── ScoreOfParentheses.java │ ├── TeemoAttacking.java │ ├── WallsAndGates.java │ └── ZeroOneMatrix.java ├── stack │ ├── AsteroidCollision.java │ ├── BalancedBrackets.java │ ├── BasicCalculatorII.java │ ├── BinaryTreeInorderTraversal.java │ ├── BuildingsWithAnOceanView.java │ ├── Calculator.java │ ├── CloneGraph.java │ ├── EvaluateReversePolishNotation.java │ ├── FindPermutation.java │ ├── GetMinimumElement.java │ ├── MaximumNestingDepthOfTheParentheses.java │ ├── NumberOfVisiblePeopleInAQueue.java │ ├── RestrictiveCandyCrush.java │ ├── TagValidator.java │ └── ValidParentheses.java └── string │ ├── RemoveComments.java │ ├── RepeatedStringMatch.java │ ├── ReplaceAllSToAvoidConsecutiveRepeatingCharacters.java │ └── RotationalCipher.java ├── database └── TeamScoresInFootballTournament.sql ├── pramp ├── AbsoluteValueSort.java ├── ArrayIndexAndElementEquality.java ├── ArrayQuadruplet.java ├── AwardBudgetCuts.java ├── BSTSuccessorSearch.java ├── BasicRegexParser.java ├── BracketMatch.java ├── BusiestTimeInTheMall.java ├── DecodeVariants.java ├── DecryptMessage.java ├── DeletionDistance.java ├── DiffBetweenTwoStrings.java ├── DroneFlightPlanner.java ├── FlattenADictionary.java ├── HTreeConstruction.java ├── KMessedArraySort.java ├── Merging2Packages.java ├── NumberOfPaths.java ├── PairsWithGivenDifference.java ├── PancakeSort.java ├── RootOfNumber.java ├── SalesPath.java ├── SentenceReverse.java ├── ShiftedArraySearch.java ├── ShortestCellPath.java ├── SmallestSubstringOfAllCharacters.java ├── ToeplitzMatrix.java ├── ValidateIPAddress.java └── WordCountEngine.java ├── tools ├── back_of_the_envolop_calculation.html └── javascript_tools.html ├── topAmazonQuestions ├── AmazonFreshPromotion.java ├── AmazonFulfillmentBuilder.java ├── BaseballGame.java ├── CellStateAfterNDays.java ├── ChooseAFlask.java ├── ConnectRopes.java ├── CountReviewCombinations.java ├── CutoffRanks.java ├── DataCenterCriticalConnection.java ├── DivisibilityOfStrings.java ├── EarliestTimeToCompleteDeliveries.java ├── FileProcessRunner.java ├── FindCountriesWithTheLargestDeficit.java ├── FindCriticalNodes.java ├── FindRelatedProducts.java ├── FindSubstrings.java ├── FiveStarSellers.java ├── GiftingGroups.java ├── HighestTenure.java ├── ItemsInContainers.java ├── KNearestPostOffices.java ├── KeyPressedTimes.java ├── LRUCacheMisses.java ├── LargestItemAssociation.java ├── LoadBalancer.java ├── LoadTheCargo.java ├── LongestStringMadeUpOfOnlyVowels.java ├── MaximalMinimumValuePathI.java ├── MaximizeProfit.java ├── MaximumBoundedArray.java ├── MinCostToAddNewRoads.java ├── MinCostToRepairEdges.java ├── MinimumTotalContainerSize.java ├── MostCommonWord.java ├── MoveObstacle.java ├── MoviesOnFlight.java ├── MultiprocessorSystem.java ├── NearestCity.java ├── OptimizeMemoryUsage.java ├── PartitionList.java ├── PartitionString.java ├── RankingProducts.java ├── RearrangeString.java ├── RollDice.java ├── RoverControl.java ├── ScheduleTasks.java ├── SecretFruitList.java ├── ShopkeeperSale.java ├── ShoppingPatterns.java ├── SlowestKey.java ├── SquaredShortestDistance.java ├── SubstringsOfSizeKWithKDistinctChars.java ├── SubtreeMaximumAverageNode.java ├── TaggingSystem.java ├── TheMaxOfMinima.java ├── ThrottlingGateway.java ├── TopKFrequentWords.java ├── TransactionLogs.java ├── TreasureIslandI.java ├── TreasureIslandII.java ├── Turnstile.java ├── TwoSumUniquePairs.java ├── UniqueDeviceNames.java ├── UtilizationChecks.java └── ZombieMatrix.java ├── topFacebookQuestions ├── AboveAverageSubarrays.java ├── AccountsMerge.java ├── AddStrings.java ├── AnswerAQuery.java ├── BalanceBrackets.java ├── BinaryTreeMaximumPathSum.java ├── BinaryTreeRightSideView.java ├── ChangeInAForeignCurrency.java ├── CombinationSum.java ├── ContinuousSubarraySum.java ├── CountingTriangles.java ├── ElementSwapping.java ├── EncryptedWords.java ├── ExclusiveTimeOfFunctions.java ├── IntegerToEnglishWords.java ├── IsGraphBipartite.java ├── KthLargestElementInAnArray.java ├── LongestSubstringWithAtMostKDistinctCharacters.java ├── MatchingPairs.java ├── MaximumDifferenceBetweenNodeAndAncestor.java ├── MaximumSumOf3NonOverlappingSubarrays.java ├── MaximumSwap.java ├── MinimizingPermutations.java ├── MinimumLengthSubstrings.java ├── MinimumRemoveToMakeValidParentheses.java ├── MissingElementInSortedArray.java ├── NextPermutation.java ├── NodesInASubtree.java ├── NumberOfVisibleNodes.java ├── ProductOfArrayExceptSelf.java ├── QueueRemovals.java ├── RandomPickIndex.java ├── ReadNCharactersGivenRead4IICallMultipleTimes.java ├── RemoveInvalidParentheses.java ├── RevenueMilestones.java ├── ReverseOperations.java ├── SeatingArrangements.java ├── SlowSums.java ├── SparseMatrixMultiplication.java ├── SubarraySumEqualsK.java ├── ValidNumber.java ├── ValidPalindromeII.java ├── ValidateStackSequences.java └── VerifyingAnAlienDictionary.java ├── topMicrosoftQuestions ├── BenchmarkMatching.java ├── CountUniqueCharactersOfAllSubstringsOfAGivenString.java ├── DayOfWeekThatIsKDaysLater.java ├── FindNUniqueIntegersSumUpToZero.java ├── IP4ValidationWithCIDR.java ├── LargestKSuchThatBothKAndKExistInArray.java ├── LargestMAlignedSubset.java ├── LexicographicallySmallestString.java ├── LongestSemiAlternatingSubstring.java ├── LongestSubstringWithout3ContiguousOccurrencesOfLetter.java ├── MaxInsertsToObtainStringWithout3ConsecutiveA.java ├── MaxNetworkRank.java ├── MaxSumOfNumbersWithSameDigitSum.java ├── MaximumLengthOfAConcatenatedStringWithUniqueCharacters.java ├── MinAdjSwapsToGroupRedBalls.java ├── MinAdjSwapsToMakePalindrome.java ├── MinDeletionsToObtainStringInRightFormat.java ├── MinMovesToObtainStringWithout3IdenticalConsecutiveLetters.java ├── MinStepsToMakePilesEqualHeight.java ├── MinimumDeletionsRequiredToMakeFrequencyOfEachLetterUnique.java ├── ParticleVelocity.java ├── SmallestPositiveInteger.java ├── StopWatchImplementation.java ├── StreamPairCounterImpl.java ├── SwapForLongestRepeatedCharacterSubstring.java └── WebCrawler.java └── topUberQuestions ├── CountNumberWithCondition.java ├── FindCountOfXInSortedArray.java ├── FrequencyOfIntervals.java ├── IncreasingSequence.java ├── LongestPrefixPalindromeRemoval.java ├── MinTimeToCompleteAllTasks.java ├── MinimumPeak.java ├── ReverseChars.java ├── RoomTravel.java ├── RotateMatrix.java ├── SolveExpression.java ├── StreamData.java ├── UnionAndIntersectionOfTwoSortedIntervalLists.java └── ValidDirection.java /AlgoExpert/AllKindsOfNodeDepths.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 18, 2020 3 | * Questions: https://www.algoexpert.io/questions/All%20Kinds%20Of%20Node%20Depths 4 | */ 5 | public class AllKindsOfNodeDepths { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int allKindsOfNodeDepths(BinaryTree root) { 11 | if (root == null) return 0; 12 | return getDepth(root, 0) + allKindsOfNodeDepths(root.left) + allKindsOfNodeDepths(root.right); 13 | } 14 | 15 | private static int getDepth(BinaryTree root, int depth) { 16 | if (root == null) return 0; 17 | return depth + getDepth(root.left, depth + 1) + getDepth(root.right, depth + 1); 18 | } 19 | 20 | static class BinaryTree { 21 | int value; 22 | BinaryTree left; 23 | BinaryTree right; 24 | 25 | public BinaryTree(int value) { 26 | this.value = value; 27 | left = null; 28 | right = null; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /AlgoExpert/ContinuousMedianHandlerImpl.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Sep 06, 2020 5 | * Questions: https://www.algoexpert.io/questions/Continuous%20Median 6 | */ 7 | public class ContinuousMedianHandlerImpl { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | static class ContinuousMedianHandler { 13 | double median = 0; 14 | PriorityQueue left = new PriorityQueue<>((v1, v2) -> v2 - v1), right = new PriorityQueue<>(); 15 | 16 | public void insert(int number) { 17 | right.add(number); 18 | if (!left.isEmpty()) right.add(left.poll()); 19 | while (left.size() < right.size()) left.add(right.poll()); 20 | int size = left.size() + right.size(); 21 | if (size == 0) median = 0; 22 | if (size % 2 == 0) { 23 | median = ((double) left.peek() + (double) right.peek()) / 2; 24 | } else { 25 | median = left.peek(); 26 | } 27 | } 28 | 29 | public double getMedian() { 30 | return median; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /AlgoExpert/FindLoop.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 17, 2020 3 | * Questions: https://www.algoexpert.io/questions/Find%20Loop 4 | */ 5 | public class FindLoop { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static LinkedList findLoop(LinkedList head) { 11 | LinkedList slow = head.next; 12 | LinkedList fast = head.next.next; 13 | while (slow != fast) { 14 | slow = slow.next; 15 | fast = fast.next.next; 16 | } 17 | slow = head; 18 | while (slow != fast) { 19 | slow = slow.next; 20 | fast = fast.next; 21 | } 22 | return slow; 23 | } 24 | 25 | static class LinkedList { 26 | int value; 27 | LinkedList next = null; 28 | 29 | public LinkedList(int value) { 30 | this.value = value; 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /AlgoExpert/InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 14, 2020 3 | * Questions: https://www.algoexpert.io/questions/Invert%20Binary%20Tree 4 | */ 5 | public class InvertBinaryTree { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static void invertBinaryTree(BinaryTree tree) { 11 | if (tree == null) return; 12 | invertBinaryTree(tree.left); 13 | invertBinaryTree(tree.right); 14 | BinaryTree temp = tree.right; 15 | tree.right = tree.left; 16 | tree.left = temp; 17 | } 18 | 19 | static class BinaryTree { 20 | public int value; 21 | public BinaryTree left; 22 | public BinaryTree right; 23 | 24 | public BinaryTree(int value) { 25 | this.value = value; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /AlgoExpert/MaxSubSetSumNoAdjacent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 18, 2020 3 | * Questions: 4 | */ 5 | public class MaxSubSetSumNoAdjacent { 6 | public static void main(String[] args) { 7 | System.out.println(maxSubsetSumNoAdjacent(new int[]{75, 105, 120, 75, 90, 135})); 8 | System.out.println(maxSubsetSumNoAdjacent(new int[]{30, 25, 50, 55, 100, 120})); 9 | } 10 | 11 | public static int maxSubsetSumNoAdjacent(int[] array) { 12 | if (array == null || array.length == 0) return 0; 13 | int len = array.length; 14 | if (len == 1) return array[0]; 15 | int pre2 = 0, pre1 = array[0]; 16 | for (int i = 1; i < len; i++) { 17 | int cur = Math.max(pre1, pre2 + array[i]); 18 | pre2 = pre1; 19 | pre1 = cur; 20 | } 21 | return Math.max(pre1, pre2); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /AlgoExpert/MinNumberOfCoinsForChange.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 10, 2020 3 | * Questions: 4 | */ 5 | public class MinNumberOfCoinsForChange { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int minNumberOfCoinsForChange(int n, int[] denoms) { 11 | if (n == 0) return 0; 12 | // dp[x] = minum number of coins to make x amount 13 | Integer[] dp = new Integer[n + 1]; 14 | helper(n, denoms, dp); 15 | return dp[n] == Integer.MAX_VALUE ? -1 : dp[n]; 16 | } 17 | 18 | private static int helper(int target, int[] coins, Integer[] dp) { 19 | if (target < 0) return Integer.MAX_VALUE; 20 | if (target == 0) return 0; 21 | if (dp[target] != null) return dp[target]; 22 | int cur = Integer.MAX_VALUE; 23 | for (int coin : coins) { 24 | int next = helper(target - coin, coins, dp); 25 | if (next != Integer.MAX_VALUE) { 26 | cur = Math.min(cur, next + 1); 27 | } 28 | } 29 | return dp[target] = cur; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /AlgoExpert/QuickSelect.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Sep 06, 2020 5 | * Questions: https://www.algoexpert.io/questions/Quickselect 6 | */ 7 | public class QuickSelect { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int quickselect(int[] array, int k) { 13 | PriorityQueue pq = new PriorityQueue<>((v1, v2) -> v2 - v1); 14 | for (int val : array) { 15 | pq.add(val); 16 | if (pq.size() > k) pq.poll(); 17 | } 18 | return pq.peek(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /AlgoExpert/RunLengthEncoding.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Feb 22, 2021 3 | * Questions: 4 | */ 5 | 6 | public class RunLengthEncoding { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static String runLengthEncoding(String string) { 13 | char pre = ' '; 14 | int count = 0; 15 | StringBuilder sb = new StringBuilder(); 16 | for (char cur : string.toCharArray()) { 17 | if (cur != pre) { 18 | while (count > 9) { 19 | sb.append(9).append(pre); 20 | count -= 9; 21 | } 22 | if (count >= 1) sb.append(count).append(pre); 23 | count = 0; 24 | } 25 | pre = cur; 26 | count++; 27 | } 28 | while (count > 9) { 29 | sb.append(9).append(pre); 30 | count -= 9; 31 | } 32 | if (count >= 1) sb.append(count).append(pre); 33 | return sb.toString(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /AlgoExpert/SmallestDifference.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Aug 18, 2020 5 | * Questions: https://www.algoexpert.io/questions/Smallest%20Difference 6 | */ 7 | public class SmallestDifference { 8 | public static void main(String[] args) { 9 | System.out.println(Arrays.toString(smallestDifference(new int[]{-1, 5, 10, 20, 28, 3}, new int[]{26, 134, 135, 15, 17}))); 10 | } 11 | 12 | public static int[] smallestDifference(int[] arrayOne, int[] arrayTwo) { 13 | int[] best = {0, 0}; 14 | Arrays.sort(arrayOne); 15 | Arrays.sort(arrayTwo); 16 | int p1 = 0, p2 = 0, l1 = arrayOne.length, l2 = arrayTwo.length, closest = Integer.MAX_VALUE; 17 | while (p1 < l1 && p2 < l2) { 18 | int curDiff = Math.abs(arrayOne[p1] - arrayTwo[p2]); 19 | if (curDiff < closest) { 20 | best = new int[]{arrayOne[p1], arrayTwo[p2]}; 21 | closest = curDiff; 22 | if (curDiff == 0) return best; 23 | } 24 | if (arrayOne[p1] < arrayTwo[p2]) p1++; 25 | else p2++; 26 | } 27 | return best; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /AlgoExpert/StaircaseTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Feb 24, 2021 3 | * Questions: 4 | */ 5 | 6 | public class StaircaseTraversal { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | // Time: O(n*k), Space: O(n) 13 | public static int staircaseTraversal(int height, int maxSteps) { 14 | int[] dp = new int[height + 1]; 15 | dp[0] = 1; 16 | for (int i = 0; i <= height; i++) { 17 | for (int j = 1; j <= maxSteps && i + j <= height; j++) { 18 | dp[i + j] += dp[i]; 19 | } 20 | } 21 | return dp[height]; 22 | } 23 | 24 | // TIme: O(n), Space: O(n) 25 | public static int staircaseTraversal_op2(int height, int maxSteps) { 26 | int[] dp = new int[height + 1]; 27 | dp[0] = 1; 28 | int sum = 0; 29 | for (int i = 1; i <= height; i++) { 30 | int start = i - maxSteps - 1; 31 | int end = i - 1; 32 | sum -= start >= 0 ? dp[start] : 0; 33 | sum += end >= 0 ? dp[end] : 0; 34 | dp[i] = sum; 35 | } 36 | return dp[height]; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /AlgoExpert/ValidateSubsequence.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | /** 4 | * Created on: Sep 06, 2020 5 | * Questions: https://www.algoexpert.io/questions/Validate%20Subsequence 6 | */ 7 | public class ValidateSubsequence { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static boolean isValidSubsequence(List array, List sequence) { 13 | for (int i = 0; i < array.size(); i++) { 14 | if (array.get(i) == sequence.get(0) && valid(array, i, sequence)) { 15 | return true; 16 | } 17 | } 18 | return false; 19 | } 20 | 21 | private static boolean valid(List array, int idx, List sequence) { 22 | int p1 = 0; 23 | while (idx < array.size() && p1 < sequence.size()) { 24 | if (array.get(idx++) == sequence.get(p1)) p1++; 25 | } 26 | return p1 == sequence.size(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/binarysearch/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/explore/learn/card/binary-search/138/background/1038/ 3 | */ 4 | public class BinarySearch { 5 | public static void main(String[] args) { 6 | System.out.println("Answer is:" + search(new int[]{-1, 0, 3, 5, 9, 12}, 9) + " should be [4]."); 7 | System.out.println("Answer is:" + search(new int[]{-1, 0, 3, 5, 9, 12}, 2) + " should be [-1]."); 8 | } 9 | 10 | public static int search(int[] nums, int target) { 11 | return binarySearchHelper(nums, target, 0, nums.length - 1); 12 | } 13 | 14 | private static int binarySearchHelper(int[] nums, int target, int start, int end) { 15 | if (start > end || start < 0 || end >= nums.length) return -1; 16 | int mid = start + ((end - start) / 2); 17 | if (nums[mid] > target) { 18 | return binarySearchHelper(nums, target, start, mid - 1); 19 | } else if (nums[mid] < target) { 20 | return binarySearchHelper(nums, target, mid + 1, end); 21 | } else { 22 | return mid; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/binarysearch/FindMinimumInRotatedSortedArrayII.java: -------------------------------------------------------------------------------- 1 | public class FindMinimumInRotatedSortedArrayII { 2 | 3 | public static void main(String[] args) { 4 | System.out.println("Answer is:" + findMin(new int[]{3, 4, 5, 1, 2}) + " should be [1]."); 5 | System.out.println("Answer is:" + findMin(new int[]{1, 3, 5}) + " should be [1]."); 6 | System.out.println("Answer is:" + findMin(new int[]{2, 2, 2, 0, 1}) + " should be [0]."); 7 | System.out.println("Answer is:" + findMin(new int[]{1, 3, 3}) + " should be [1]."); 8 | System.out.println("Answer is:" + findMin(new int[]{10, 1, 10, 10, 10}) + " should be [1]."); 9 | System.out.println("Answer is:" + findMin(new int[]{3, 3, 1, 3}) + " should be [1]."); 10 | } 11 | 12 | public static int findMin(int[] nums) { 13 | for (int i = 1; i < nums.length; i++) { 14 | if (nums[i - 1] > nums[i]) return nums[i]; 15 | } 16 | return nums[0]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/binarysearch/GuessNumberHigherOrLower.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/explore/learn/card/binary-search/125/template-i/951/ 3 | */ 4 | public class GuessNumberHigherOrLower { 5 | public static void main(String[] args) { 6 | System.out.println("Answer is :" + guessNumber(10) + " should be []."); 7 | } 8 | 9 | private static int guess(int i) { 10 | return 0; 11 | } 12 | 13 | public static int guessNumber(int n) { 14 | int start = 1, end = n; 15 | while (start < end) { 16 | int mid = start + (end - start) / 2; 17 | int comp = guess(mid); 18 | if (comp == 0) return mid; 19 | if (comp > 0) start = mid + 1; 20 | else end = mid - 1; 21 | } 22 | return guess(start) == 0 ? start : -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/binarysearch/Sqrt.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/explore/learn/card/binary-search/125/template-i/950/ 3 | */ 4 | public class Sqrt { 5 | public static void main(String[] args) { 6 | System.out.println("Answer is:" + mySqrt(4) + " should be [2]."); 7 | System.out.println("Answer is:" + mySqrt(8) + " should be [2]."); 8 | System.out.println("Answer is:" + mySqrt(10) + " should be [3]."); 9 | System.out.println("Answer is:" + mySqrt(2147395600) + " should be [46340]."); 10 | } 11 | 12 | public static int mySqrt(int x) { 13 | if (x < 2) return x; 14 | int left = (int) Math.sqrt(x); 15 | int right = left + 1; 16 | long rightSquare = (long) right * (long) right; 17 | return rightSquare > x ? left : right; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/coursera/Rough_Explanation.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neerazz/FAANG/7fe3057fdf8a604bac479974378d5eda83178e62/Algorithms/coursera/Rough_Explanation.xlsx -------------------------------------------------------------------------------- /Algorithms/coursera/Week1Assign1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /* 4 | In this very first programming challenge, your goal is to implement a program that reads two digits from the standard input and 5 | prints their sum to the standard output. 6 | */ 7 | public class Week1Assign1 { 8 | 9 | public static void main(String[] args) { 10 | Scanner s = new Scanner(System.in); 11 | int a = s.nextInt(); 12 | int b = s.nextInt(); 13 | System.out.println(a + b); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/cycle-sort/AllMissingNumbers.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * Created on: Jul 13, 2021 6 | * Ref: https://www.educative.io/courses/grokking-the-coding-interview/Y52qNM0ljWK 7 | */ 8 | 9 | public class AllMissingNumbers { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static List findNumbers(int[] nums) { 16 | List missingNumbers = new ArrayList<>(); 17 | int len = nums.length; 18 | for (int i = 0; i < len; i++) { 19 | int cur = Math.abs(nums[i]) - 1; 20 | if (nums[cur] < 0) continue; 21 | nums[cur] *= -1; 22 | } 23 | for (int i = 0; i < len; i++) { 24 | if (nums[i] > 0) { 25 | missingNumbers.add(i + 1); 26 | } 27 | } 28 | return missingNumbers; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/cycle-sort/CycleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Jul 13, 2021 5 | * Ref: https://www.educative.io/courses/grokking-the-coding-interview/B8qXVqVwDKY 6 | */ 7 | 8 | public class CycleSort { 9 | 10 | public static void main(String[] args) { 11 | sort(new int[]{3, 1, 5, 4, 2}); 12 | } 13 | 14 | public static void sort(int[] nums) { 15 | System.out.println("Before: " + Arrays.toString(nums)); 16 | int len = nums.length; 17 | for (int i = 0; i < len; i++) { 18 | while (nums[i] != i + 1) { 19 | int next = nums[i]; 20 | nums[i] = nums[next - 1]; 21 | nums[next - 1] = next; 22 | } 23 | } 24 | System.out.println("After : " + Arrays.toString(nums)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/cycle-sort/FirstSmallestMissingPositive.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 13, 2021 3 | * Ref: https://www.educative.io/courses/grokking-the-coding-interview/3jEXWgB5ZmM 4 | */ 5 | 6 | public class FirstSmallestMissingPositive { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int findNumber(int[] nums) { 13 | int min = Integer.MAX_VALUE, len = nums.length; 14 | for (int i = 0; i < len; i++) { 15 | if (nums[i] <= 0) nums[i] = len + 1; 16 | if (nums[i] > len) nums[i] = len + 1; 17 | min = Math.min(min, nums[i]); 18 | } 19 | if (min > 1) return 1; 20 | for (int i = 0; i < len; i++) { 21 | while (nums[i] != i + 1 && nums[i] != len + 1) { 22 | int temp = nums[i]; 23 | nums[i] = nums[temp - 1]; 24 | nums[temp - 1] = temp; 25 | } 26 | } 27 | for (int i = 0; i < len; i++) { 28 | if (nums[i] != i + 1) return i + 1; 29 | } 30 | return len + 1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/dfs-bfs/ArrayNesting.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 01, 2021 3 | * Ref: https://leetcode.com/problems/array-nesting/ 4 | */ 5 | public class ArrayNesting { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int arrayNesting(int[] nums) { 11 | int len = nums.length; 12 | boolean[] visited = new boolean[len]; 13 | int max = 0; 14 | for (int i = 0; i < len; i++) { 15 | if (visited[i]) continue; 16 | int cur = dfs(i, nums, visited); 17 | max = Math.max(max, cur); 18 | } 19 | return max; 20 | } 21 | 22 | static int dfs(int cur, int[] nums, boolean[] visited) { 23 | if (visited[cur]) return 0; 24 | visited[cur] = true; 25 | return 1 + dfs(nums[cur], nums, visited); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/dfs-bfs/CountGoodNodesInBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 18, 2021 3 | * Ref: https://leetcode.com/problems/count-good-nodes-in-binary-tree/ 4 | */ 5 | 6 | public class CountGoodNodesInBinaryTree { 7 | 8 | static int count; 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public int goodNodes(TreeNode root) { 15 | if (root == null) return 0; 16 | count = 0; 17 | helper(root, root.val); 18 | return count; 19 | } 20 | 21 | private void helper(TreeNode root, int max) { 22 | if (root == null) return; 23 | if (max <= root.val) count++; 24 | int curMax = Math.max(max, root.val); 25 | helper(root.left, curMax); 26 | helper(root.right, curMax); 27 | } 28 | 29 | static class TreeNode { 30 | int val; 31 | TreeNode left; 32 | TreeNode right; 33 | 34 | TreeNode(int x) { 35 | val = x; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/dfs-bfs/JumpGameIII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Nov 29, 2020 3 | * Questions: https://leetcode.com/problems/jump-game-iii/ 4 | */ 5 | 6 | public class JumpGameIII { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static boolean canReach(int[] arr, int start) { 13 | boolean[] visited = new boolean[arr.length]; 14 | return helper(arr, start, visited); 15 | } 16 | 17 | private static boolean helper(int[] arr, int start, boolean[] visited) { 18 | if (visited[start]) return false; 19 | if (arr[start] == 0) return true; 20 | visited[start] = true; 21 | int back = start - arr[start], front = start + arr[start]; 22 | // System.out.println("Back = " + back + " cur = " + start + " front = " + front); 23 | boolean result = false; 24 | if (back >= 0 && back < arr.length && helper(arr, back, visited)) { 25 | return true; 26 | } 27 | if (front >= 0 && front < arr.length && helper(arr, front, visited)) { 28 | return true; 29 | } 30 | return false; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/dfs-bfs/MostStonesRemovedWithSameRowOrColumn.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * Created on: Sep 23, 2021 6 | * Ref: https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ 7 | */ 8 | public class MostStonesRemovedWithSameRowOrColumn { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static int removeStones(int[][] stones) { 14 | Set visited = new HashSet<>(); 15 | int count = 0, len = stones.length; 16 | for (int[] stone : stones) { 17 | if (visited.contains(stone)) continue; 18 | count++; 19 | dfs(stone, stones, visited); 20 | } 21 | return len - count; 22 | } 23 | 24 | static void dfs(int[] stone, int[][] stones, Set visited) { 25 | visited.add(stone); 26 | for (int[] cur : stones) { 27 | if (!visited.contains(cur) && (cur[0] == stone[0] || cur[1] == stone[1])) { 28 | dfs(cur, stones, visited); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/BestTimeToBuyAndSellStockIV.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 18, 2020 3 | * Questions: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 4 | */ 5 | 6 | public class BestTimeToBuyAndSellStockIV { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(maxProfit(2, new int[]{2, 5, 7, 1, 4, 3, 1, 3}) + " should be [8]."); 10 | System.out.println(maxProfit(2, new int[]{3, 3, 5, 0, 0, 3, 1, 4}) + " should be [6]."); 11 | System.out.println(maxProfit(2, new int[]{1, 2, 3, 4, 5}) + " should be [4]."); 12 | } 13 | 14 | public static int maxProfit(int k, int[] prices) { 15 | return 0; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/BinomialCoefficient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Questions: 3 | * Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). 4 | * A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects; 5 | * more formally, the number of k-element subsets (or k-combinations) of an n-element set. 6 | * Example: function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2. 7 | */ 8 | public class BinomialCoefficient { 9 | public static void main(String[] args) { 10 | System.out.println(binomialCoeff(4, 2) + " should be [6]."); 11 | System.out.println(binomialCoeff(5, 2) + " should be [10]."); 12 | } 13 | 14 | private static int binomialCoeff(int n, int k) { 15 | return 0; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/DistinctSubsequences.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 19, 2021 3 | * Ref: https://leetcode.com/problems/distinct-subsequences 4 | */ 5 | public class DistinctSubsequences { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public int numDistinct(String s, String t) { 11 | int l1 = s.length(), l2 = t.length(); 12 | Integer[][] dp = new Integer[l1][l2]; 13 | return helper(s, 0, l1, t, 0, l2, dp); 14 | } 15 | 16 | int helper(String s, int i1, int l1, String t, int i2, int l2, Integer[][] dp) { 17 | if (i2 == l2) return i1 <= l1 ? 1 : 0; 18 | if (i1 == l1) return 0; 19 | if (dp[i1][i2] != null) return dp[i1][i2]; 20 | int cur = 0; 21 | if (s.charAt(i1) == t.charAt(i2)) cur += helper(s, i1 + 1, l1, t, i2 + 1, l2, dp); 22 | cur += helper(s, i1 + 1, l1, t, i2, l2, dp); 23 | return dp[i1][i2] = cur; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/FlipStringToMonotoneIncreasing.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 10, 2021 3 | * Ref : https://leetcode.com/problems/flip-string-to-monotone-increasing/ 4 | */ 5 | public class FlipStringToMonotoneIncreasing { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int minFlipsMonoIncr(String s) { 11 | int len = s.length(); 12 | int[] dp = new int[len + 1]; 13 | // Calculate Pre Sum 14 | for (int i = 0; i < len; i++) { 15 | dp[i + 1] = dp[i] + (s.charAt(i) - '0'); 16 | } 17 | int min = Integer.MAX_VALUE; 18 | for (int i = 0; i <= len; i++) { 19 | // Ones before the point. 20 | int onesBefore = dp[i]; 21 | // Zeros after this point= total chars after this point - total number of ones after the point. 22 | int zerosAfter = (len - i) - (dp[len] - dp[i]); 23 | min = Math.min(min, onesBefore + zerosAfter); 24 | } 25 | return min; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/GreatestSumDivisibleByThree.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Mar 09, 2021 5 | * Questions: https://leetcode.com/problems/greatest-sum-divisible-by-three/ 6 | */ 7 | 8 | public class GreatestSumDivisibleByThree { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static int maxSumDivThree(int[] nums) { 15 | int[] dp = new int[3]; 16 | for (int num : nums) { 17 | for (int val : Arrays.copyOf(dp, dp.length)) { 18 | dp[(num + val) % 3] = Math.max(dp[(num + val) % 3], num + val); 19 | } 20 | } 21 | return dp[0]; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/HouseRobberII.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Sep 25, 2020 5 | * Questions: https://leetcode.com/problems/house-robber-ii/ 6 | */ 7 | public class HouseRobberII { 8 | public static void main(String[] args) { 9 | System.out.println(rob(new int[]{2, 3, 2})); 10 | System.out.println(rob(new int[]{1, 2, 3, 1})); 11 | System.out.println(rob(new int[]{1, 2, 1, 0})); 12 | } 13 | 14 | public static int rob(int[] nums) { 15 | int len = nums.length; 16 | if (len == 0) return 0; 17 | if (len == 1) return nums[0]; 18 | return Math.max(helper(Arrays.copyOfRange(nums, 0, len - 1)), helper(Arrays.copyOfRange(nums, 1, len))); 19 | } 20 | 21 | private static int helper(int[] nums) { 22 | int len = nums.length; 23 | int[] dp = new int[len]; 24 | dp[0] = nums[0]; 25 | for (int i = 1; i < len; i++) { 26 | dp[i] = Math.max(dp[i - 1], (i >= 2 ? dp[i - 2] : 0) + nums[i]); 27 | } 28 | return dp[len - 1]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/IntegerBreak.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Mar 02, 2021 3 | * Questions: https://leetcode.com/problems/integer-break/ 4 | */ 5 | 6 | public class IntegerBreak { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int integerBreak(int n) { 13 | Integer[] dp = new Integer[n + 1]; 14 | return helper(n, 0, dp); 15 | } 16 | 17 | private static int helper(int val, int div, Integer[] dp) { 18 | if (val <= 1) return 1; 19 | if (dp[val] != null) return dp[val]; 20 | int max = (div == 0) ? 0 : val; 21 | for (int i = 1; i < val; i++) { 22 | int next = helper(val - i, div + 1, dp); 23 | if (i * next > max) { 24 | max = i * next; 25 | } 26 | } 27 | return dp[val] = max; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/LongestIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Crated on: Apr 08, 2020 3 | */ 4 | public class LongestIncreasingSubsequence { 5 | public static void main(String[] args) { 6 | System.out.println(lengthOfLIS(new int[]{10, 9, 2, 5, 3, 7, 101, 18}) + " should be [4]."); 7 | System.out.println(lengthOfLIS(new int[]{1}) + " should be [1]."); 8 | System.out.println(lengthOfLIS(new int[]{2, 2}) + " should be [1]."); 9 | } 10 | 11 | public static int lengthOfLIS(int[] nums) { 12 | int len = nums.length, max = 1; 13 | if (len <= 1) return len; 14 | int[] dp = new int[len + 1]; 15 | for (int i = len - 1; i >= 0; i--) { 16 | dp[i] = 1; 17 | for (int j = i + 1; j < len; j++) { 18 | if (nums[j] > nums[i]) { 19 | dp[i] = Math.max(dp[i], dp[j] + 1); 20 | max = Math.max(max, dp[i]); 21 | } 22 | } 23 | } 24 | return max; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/LongestRepeatingSubsequence.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 11, 2021 3 | * Ref: https://www.codingninjas.com/codestudio/problems/longest-repeating-subsequence_1118110?topList=top-google-coding-interview-questions&leftPanelTab=1 4 | */ 5 | public class LongestRepeatingSubsequence { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int longestRepeatingSubsequence(String st, int n) { 11 | if (n < 2) return 0; 12 | Integer[][] dp = new Integer[n][n]; 13 | return helper(st, 0, 1, n, dp); 14 | } 15 | 16 | static int helper(String s, int p1, int p2, int len, Integer[][] dp) { 17 | if (p2 >= len || p1 == p2) return 0; 18 | if (dp[p1][p2] != null) return dp[p1][p2]; 19 | int best = 0; 20 | if (s.charAt(p1) == s.charAt(p2)) { 21 | best = 1 + helper(s, p1 + 1, p2 + 1, len, dp); 22 | } else { 23 | best = Math.max(helper(s, p1 + 1, p2, len, dp), helper(s, p1, p2 + 1, len, dp)); 24 | } 25 | return dp[p1][p2] = best; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | class MaximumSubarray { 2 | public static void main(String[] args) { 3 | 4 | } 5 | 6 | public int maxSubArray(int[] nums) { 7 | int max = nums[0], sumSoFar = nums[0]; 8 | int[] dp = new int[nums.length]; 9 | for (int i = 1; i < nums.length; i++) { 10 | int pre = dp[i - 1]; 11 | int cur = nums[i]; 12 | dp[i] = Math.max(pre + cur, cur); 13 | } 14 | return dp[nums.length - 1]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/MinimumPathSum.java: -------------------------------------------------------------------------------- 1 | public class MinimumPathSum { 2 | public static void main(String[] args) { 3 | 4 | } 5 | 6 | public static int minPathSum(int[][] grid) { 7 | int rows = grid.length, cols = rows > 0 ? grid[0].length : 0; 8 | if (cols == 0) return 0; 9 | int[][] dp = new int[rows + 1][cols + 1]; 10 | for (int row = 1; row <= rows; row++) { 11 | for (int col = 1; col <= cols; col++) { 12 | int curgrid = grid[row - 1][col - 1]; 13 | int dpmin = 0; 14 | if (row == 1) dpmin = dp[row][col - 1]; 15 | else if (col == 1) dpmin = dp[row - 1][col]; 16 | else dpmin = Math.min(dp[row - 1][col], dp[row][col - 1]); 17 | dp[row][col] = curgrid + dpmin; 18 | } 19 | } 20 | return dp[rows][cols]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/NthCatalanNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Crated on: Apr 11, 2020 3 | */ 4 | 5 | /** 6 | * The first few Catalan numbers for n = 0, 1, 2, 3, … are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862 7 | * Solution: https://www.youtube.com/watch?v=CMaZ69P1bAc 8 | */ 9 | public class NthCatalanNumber { 10 | public static void main(String[] args) { 11 | System.out.println(nthCatalanNumber(3) + " should be [5]."); 12 | System.out.println(nthCatalanNumber(5) + " should be [42]."); 13 | System.out.println(nthCatalanNumber(9) + " should be [4862]."); 14 | } 15 | 16 | private static int nthCatalanNumber(int n) { 17 | int[] dp = new int[n + 1]; 18 | if (n >= 1) dp[0] = 1; 19 | if (n >= 2) dp[1] = 1; 20 | for (int i = 2; i <= n; i++) { 21 | for (int j = 0; j < i; j++) { 22 | dp[i] += dp[j] * dp[i - j - 1]; 23 | } 24 | } 25 | return dp[n]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/PartitionArrayForMaximumSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Mar 09, 2021 3 | * Questions: https://leetcode.com/problems/partition-array-for-maximum-sum/ 4 | */ 5 | 6 | public class PartitionArrayForMaximumSum { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public int maxSumAfterPartitioning(int[] arr, int k) { 13 | int len = arr.length; 14 | Integer[] dp = new Integer[len]; 15 | return helper(arr, 0, k, dp); 16 | } 17 | 18 | private int helper(int[] nums, int start, int k, Integer[] dp) { 19 | if (start == nums.length) return 0; 20 | if (dp[start] != null) return dp[start]; 21 | int max = 0, best = 0, count = 0; 22 | for (int i = start; i < start + k && i < nums.length; i++) { 23 | max = Math.max(max, nums[i]); 24 | count++; 25 | int cur = max * count + helper(nums, i + 1, k, dp); 26 | best = Math.max(best, cur); 27 | } 28 | // System.out.println("Start =" + start + " best = " + best); 29 | return dp[start] = best; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/dynamic-problem/RangeSumQuery2DImmutable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 01, 2020 3 | * Questions: https://leetcode.com/problems/range-sum-query-2d-immutable/ 4 | */ 5 | public class RangeSumQuery2DImmutable { 6 | public static void main(String[] args) { 7 | 8 | } 9 | } 10 | 11 | class NumMatrix { 12 | int[][] dp; 13 | 14 | public NumMatrix(int[][] matrix) { 15 | int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0; 16 | dp = new int[rows + 1][cols + 1]; 17 | for (int row = 1; row <= rows; row++) { 18 | for (int col = 1; col <= cols; col++) { 19 | dp[row][col] = matrix[row - 1][col - 1] + dp[row - 1][col] + dp[row][col - 1] - dp[row - 1][col - 1]; 20 | } 21 | } 22 | } 23 | 24 | public int sumRegion(int row1, int col1, int row2, int col2) { 25 | row1++; 26 | row2++; 27 | col1++; 28 | col2++; 29 | return dp[row2][col2] - dp[row2][col1 - 1] - dp[row1 - 1][col2] + dp[row1 - 1][col1 - 1]; 30 | } 31 | } -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/BestTimeToBuyAndSellStockII.java: -------------------------------------------------------------------------------- 1 | public class BestTimeToBuyAndSellStockII { 2 | public static void main(String[] args) { 3 | System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4}) + " should be [7]"); 4 | System.out.println(maxProfit(new int[]{1, 2, 3, 4, 5}) + " should be [4]"); 5 | System.out.println(maxProfit(new int[]{7, 6, 4, 3, 1}) + " should be [0]"); 6 | } 7 | 8 | public static int maxProfit(int[] prices) { 9 | int maxValue = 0; 10 | for (int i = 0; i < prices.length - 1; i++) { 11 | if (prices[i] < prices[i + 1]) { 12 | maxValue += prices[i + 1] - prices[i]; 13 | } 14 | } 15 | return maxValue; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/JumpGame.java: -------------------------------------------------------------------------------- 1 | public class JumpGame { 2 | public static void main(String[] args) { 3 | System.out.println(canJump(new int[]{2, 3, 1, 1, 4}) + " should be [true]"); 4 | System.out.println(canJump(new int[]{3, 2, 1, 0, 4}) + " should be [false]"); 5 | } 6 | 7 | public static boolean canJump(int[] nums) { 8 | if (nums.length < 1) return true; 9 | boolean[] possible = new boolean[nums.length]; 10 | possible[0] = true; 11 | for (int i = 0; i < nums.length; i++) { 12 | int jumps = nums[i]; 13 | for (int j = 1; j <= jumps && i + j < nums.length; j++) { 14 | possible[i + j] = true; 15 | } 16 | } 17 | for (int i = 0; i < possible.length; i++) { 18 | if (!possible[i]) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/MaxMin.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class MaxMin { 4 | public static void main(String[] args) { 5 | System.out.println(maxMin(2, new int[]{1, 2, 1, 2, 1}) + " should be [0]"); 6 | System.out.println(maxMin(4, new int[]{1, 2, 3, 4, 10, 20, 30, 40, 100, 200}) + " should be [3]"); 7 | } 8 | 9 | static int maxMin(int k, int[] arr) { 10 | Arrays.sort(arr); 11 | int pointer1 = 0, pointer2 = k - 1, minValue = Integer.MAX_VALUE; 12 | while (pointer2 < arr.length) { 13 | minValue = Math.min(minValue, arr[pointer2++] - arr[pointer1++]); 14 | } 15 | return minValue; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/MaximumUnitsOnATruck.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Jan 12, 2021 5 | * Questions: https://leetcode.com/problems/maximum-units-on-a-truck/ 6 | */ 7 | 8 | public class MaximumUnitsOnATruck { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static int maximumUnits(int[][] boxes, int truckSize) { 15 | Arrays.sort(boxes, (b1, b2) -> Integer.compare(b2[1], b1[1])); 16 | int total = 0; 17 | for (int[] box : boxes) { 18 | if (box[0] <= truckSize) { 19 | truckSize -= box[0]; 20 | total += box[0] * box[1]; 21 | } else { 22 | total += truckSize * box[1]; 23 | truckSize = 0; 24 | } 25 | } 26 | return total; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/MinimumAbsoluteDifferenceInAnArray.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms 5 | */ 6 | public class MinimumAbsoluteDifferenceInAnArray { 7 | public static void main(String[] args) { 8 | System.out.println(minimumAbsoluteDifference(new int[]{3, -7, 0}) + " should be [3]"); 9 | System.out.println(minimumAbsoluteDifference(new int[]{-59, -36, -13, 1, -53, -92, -2, -96, -54, 75}) + " should be [1]"); 10 | System.out.println(minimumAbsoluteDifference(new int[]{1, -3, 71, 68, 17}) + " should be [3]"); 11 | } 12 | 13 | static int minimumAbsoluteDifference(int[] arr) { 14 | Arrays.sort(arr); 15 | int minValue = Integer.MAX_VALUE; 16 | for (int i = 0; i < arr.length - 1; i++) { 17 | minValue = Math.min(minValue, Math.abs(arr[i] - arr[i + 1])); 18 | } 19 | return minValue; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/MinimumCostToMoveChipsToTheSamePosition.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Nov 05, 2020 3 | * Questions: https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/ 4 | */ 5 | 6 | public class MinimumCostToMoveChipsToTheSamePosition { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int minCostToMoveChips(int[] position) { 13 | int[] count = {0, 0}; 14 | for (int pos : position) { 15 | count[pos % 2]++; 16 | } 17 | return Math.min(count[0], count[1]); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/MinimumDeletionsToMakeCharacterFrequenciesUnique.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * Created on: Jun 21, 2021 6 | * Ref: https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique 7 | */ 8 | 9 | public class MinimumDeletionsToMakeCharacterFrequenciesUnique { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static int minDeletions(String s) { 16 | int[] counts = new int[26]; 17 | for (char cur : s.toCharArray()) { 18 | counts[cur - 'a']++; 19 | } 20 | Set set = new HashSet<>(); 21 | int del = 0; 22 | for (int count : counts) { 23 | if (count == 0) continue; 24 | while (set.contains(count) && count > 0) { 25 | count--; 26 | del++; 27 | } 28 | set.add(count); 29 | } 30 | return del; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/MinimumDifferenceBetweenLargestAndSmallestValueInThreeMoves.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Jul 23, 2021 5 | * Ref : https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/ 6 | */ 7 | public class MinimumDifferenceBetweenLargestAndSmallestValueInThreeMoves { 8 | public static void main(String[] args) { 9 | System.out.println(minDifference(new int[]{5, 3, 2, 4}) + " = 0"); 10 | } 11 | 12 | public static int minDifference(int[] nums) { 13 | Arrays.sort(nums); 14 | int min = Math.abs(nums[0] - nums[nums.length - 1]), len = nums.length; 15 | if (len <= 3) return 0; 16 | for (int i = 1; i <= 3; i++) { 17 | int cur = Integer.MAX_VALUE; 18 | for (int j = 0; j <= i; j++) { 19 | cur = Math.min(cur, nums[len - 1 - i + j] - nums[j]); 20 | } 21 | min = Math.min(min, cur); 22 | } 23 | return min; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/greedy-algorithum/WaterBetweenPillars.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 24, 2021 3 | * Ref: https://leetcode.com/discuss/interview-question/1471501/FacebookorVirtual-Onsiteor-Water-between-pillarsor-Java 4 | */ 5 | public class WaterBetweenPillars { 6 | public static void main(String[] args) { 7 | System.out.println(getWater(new int[]{1, 2, 3, 4, 5}) + " = 10"); 8 | System.out.println(getWater(new int[]{5, 2, 1, 2, 5}) + " = 30"); 9 | System.out.println(getWater(new int[]{6, 1, 5, 1, 3}) + " = 22"); 10 | System.out.println(getWater(new int[]{5, 1, 0, 2, 6}) + " = 32"); 11 | } 12 | 13 | private static int getWater(int[] nums) { 14 | int sum = 0, len = 0; 15 | if (len < 2) return sum; 16 | int[] left = new int[len], right = new int[len]; 17 | left[0] = nums[0]; 18 | right[len - 1] = nums[len - 1]; 19 | for (int i = 1; i < len; i++) { 20 | left[i] = Math.max(nums[i - 1], nums[i - 1]); 21 | } 22 | for (int i = len - 2; i >= 0; i--) { 23 | right[i] = Math.max(right[i + 1], nums[i + 1]); 24 | } 25 | return sum; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/interval/MyCalendarI.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * Created on: Aug 11, 2021 6 | * Ref : https://leetcode.com/problems/my-calendar-i/ 7 | */ 8 | public class MyCalendarI { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | static class MyCalendar { 14 | List list = new ArrayList<>(); 15 | 16 | public boolean book(int start, int end) { 17 | int i = 0, len = list.size(); 18 | while (i < len && list.get(i)[1] < start) i++; 19 | // Check for overlap 20 | while (i < len && list.get(i)[0] < end) { 21 | int[] cur = list.get(i); 22 | int v1 = Math.max(cur[0], start), v2 = Math.min(cur[1], end); 23 | if (v1 < v2) return false; 24 | i++; 25 | } 26 | // Add at the index. 27 | list.add(i, new int[]{start, end}); 28 | return true; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/interval/RemoveCoveredIntervals.java: -------------------------------------------------------------------------------- 1 | import java.util.Collections; 2 | import java.util.PriorityQueue; 3 | 4 | public class RemoveCoveredIntervals { 5 | public static void main(String[] args) { 6 | System.out.println(removeCoveredIntervals(new int[][]{{1, 4}, {3, 6}, {2, 8}})); 7 | } 8 | 9 | public static int removeCoveredIntervals(int[][] intervals) { 10 | PriorityQueue pq = new PriorityQueue<>( 11 | (i1, i2) -> i1[0] == i2[0] ? i2[1] - i1[1] : i1[0] - i2[0] 12 | ); 13 | Collections.addAll(pq, intervals); 14 | int[] pre = pq.poll(); 15 | int overlap = 0, len = intervals.length; 16 | while (!pq.isEmpty()) { 17 | int[] cur = pq.poll(); 18 | if (hasOverLap(pre, cur)) { 19 | overlap++; 20 | } else { 21 | pre = cur; 22 | } 23 | } 24 | return len - overlap; 25 | } 26 | 27 | private static boolean hasOverLap(int[] pre, int[] cur) { 28 | return pre[0] <= cur[0] && pre[1] >= cur[1]; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/others/AVeryBigSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.hackerrank.com/challenges/a-very-big-sum/problem?h_r=next-challenge&h_v=zen 3 | */ 4 | public class AVeryBigSum { 5 | public static void main(String[] args) { 6 | System.out.println(aVeryBigSum(new long[]{1000000001, 1000000002, 1000000003, 1000000004, 1000000005})); 7 | } 8 | 9 | static long aVeryBigSum(long[] ar) { 10 | long output = 0; 11 | for (int i = 0; i < ar.length; i++) { 12 | output += ar[i]; 13 | } 14 | return output; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Algorithms/others/BirthdayCakeCandles.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.hackerrank.com/challenges/birthday-cake-candles/problem 3 | */ 4 | public class BirthdayCakeCandles { 5 | public static void main(String[] args) { 6 | System.out.println(birthdayCakeCandles(new int[]{3, 2, 1, 3}) + " should be 2"); 7 | } 8 | 9 | static int birthdayCakeCandles(int[] ar) { 10 | int output = 0; 11 | int max = Integer.MIN_VALUE; 12 | for (int i = 0; i < ar.length; i++) { 13 | max = Math.max(max, ar[i]); 14 | } 15 | for (int i = 0; i < ar.length; i++) { 16 | if (ar[i] == max) 17 | output++; 18 | } 19 | return output; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/others/CamelCase.java: -------------------------------------------------------------------------------- 1 | public class CamelCase { 2 | public static void main(String[] args) { 3 | System.out.println(camelcase("saveChangesInTheEditor")); 4 | } 5 | 6 | static int camelcase(String s) { 7 | if (s == null || s.isEmpty()) { 8 | return 0; 9 | } 10 | int result = 1; 11 | for (int i = 1; i < s.length(); i++) { 12 | if (Character.isUpperCase(s.charAt(i))) { 13 | result++; 14 | } 15 | } 16 | return result; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/others/CompareTheTriplets.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | /* 5 | https://www.hackerrank.com/challenges/compare-the-triplets/problem 6 | */ 7 | public class CompareTheTriplets { 8 | public static void main(String[] args) { 9 | System.out.println(compareTriplets(Arrays.asList(17, 28, 30), Arrays.asList(99, 16, 8)) + " should be [2,1]."); 10 | } 11 | 12 | static List compareTriplets(List a, List b) { 13 | int BobPoint = 0, AlicePoint = 0; 14 | for (int i = 0; i < a.size(); i++) { 15 | if (a.get(i) > b.get(i)) { 16 | AlicePoint++; 17 | } else if (a.get(i) < b.get(i)) { 18 | BobPoint++; 19 | } 20 | } 21 | return Arrays.asList(AlicePoint, BobPoint); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/others/DiagonalDifference.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | /* 5 | https://www.hackerrank.com/challenges/diagonal-difference/problem 6 | */ 7 | public class DiagonalDifference { 8 | public static void main(String[] args) { 9 | System.out.println(diagonalDifference(Arrays.asList( 10 | Arrays.asList(11, 2, 4), 11 | Arrays.asList(4, 5, 6), 12 | Arrays.asList(10, 8, -12) 13 | ))); 14 | } 15 | 16 | public static int diagonalDifference(List> arr) { 17 | int size = arr.size(); 18 | int leftValue = 0, rightValue = 0; 19 | int leftI = 0, leftJ = 0, rightI = 0, rightJ = size - 1; 20 | if (size > 0) { 21 | for (int i = 0; i < size; i++) { 22 | leftValue += arr.get(leftI++).get(leftJ++); 23 | rightValue += arr.get(rightI++).get(rightJ--); 24 | } 25 | } 26 | return Math.abs(leftValue - rightValue); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/others/HackerRankInAString.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.hackerrank.com/challenges/hackerrank-in-a-string/problem 3 | */ 4 | public class HackerRankInAString { 5 | public static void main(String[] args) { 6 | System.out.println(hackerrankInString("hereiamstackerrank") + " should be [YES]"); 7 | System.out.println(hackerrankInString("hackerworld") + " should be [NO]"); 8 | } 9 | 10 | static String hackerrankInString(String s) { 11 | if (s == null || s.length() == 0) { 12 | return "NO"; 13 | } 14 | char[] chars = "hackerrank".toCharArray(); 15 | int index = 0; 16 | for (int i = 0; i < s.length(); i++) { 17 | char cur = s.charAt(i); 18 | if (cur == chars[index]) { 19 | index++; 20 | } 21 | } 22 | return index < 10 ? "NO" : "YES"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/others/MarsExploration.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.hackerrank.com/challenges/mars-exploration/problem 3 | */ 4 | public class MarsExploration { 5 | public static void main(String[] args) { 6 | System.out.println(marsExploration("SOSSOT") + " should be [1]"); 7 | System.out.println(marsExploration("SOSSOS") + " should be [0]"); 8 | } 9 | 10 | static int marsExploration(String s) { 11 | if (s == null || s.isEmpty()) { 12 | return 0; 13 | } 14 | int count = 0; 15 | for (int i = 0; i < s.length(); i++) { 16 | if (s.charAt(i++) != 'S') { 17 | count++; 18 | } 19 | if (s.charAt(i++) != 'O') { 20 | count++; 21 | } 22 | if (s.charAt(i) != 'S') { 23 | count++; 24 | } 25 | } 26 | return count; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/others/MiniMaxSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.hackerrank.com/challenges/mini-max-sum/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen 3 | */ 4 | public class MiniMaxSum { 5 | public static void main(String[] args) { 6 | // miniMaxSum(new int[]{1, 3, 5, 7, 9}); 7 | // miniMaxSum(new int[]{1, 2, 3, 4, 5}); 8 | miniMaxSum(new int[]{942381765, 627450398, 954173620, 583762094, 236817490}); 9 | } 10 | 11 | static void miniMaxSum(int[] arr) { 12 | if (arr.length == 0) { 13 | System.out.println("0 0"); 14 | } 15 | long max = Long.MIN_VALUE, min = Long.MAX_VALUE; 16 | long sum = 0; 17 | for (int j = 0; j < arr.length; j++) { 18 | sum += arr[j]; 19 | } 20 | 21 | for (int i = 0; i < arr.length; i++) { 22 | min = Math.min(min, sum - arr[i]); 23 | max = Math.max(max, sum - arr[i]); 24 | } 25 | System.out.println(min + " " + max); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/others/PlusMinus.java: -------------------------------------------------------------------------------- 1 | import java.text.DecimalFormat; 2 | 3 | /* 4 | https://www.hackerrank.com/challenges/plus-minus/problem?h_r=next-challenge&h_v=zen 5 | */ 6 | public class PlusMinus { 7 | public static void main(String[] args) { 8 | plusMinus(new int[]{1, 1, 0, -1, -1}); 9 | } 10 | 11 | static void plusMinus(int[] arr) { 12 | int length = arr.length; 13 | double positive = 0, negative = 0, zeros = 0; 14 | for (int i = 0; i < length; i++) { 15 | int current = arr[i]; 16 | if (current > 0) positive++; 17 | if (current < 0) negative++; 18 | if (current == 0) zeros++; 19 | } 20 | DecimalFormat df = new DecimalFormat("0.0000##"); 21 | System.out.println(df.format(positive / length)); 22 | System.out.println(df.format(negative / length)); 23 | System.out.println(df.format(zeros / length)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/others/SolveMeFirst.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | public class SolveMeFirst { 5 | static int solveMeFirst(int a, int b) { 6 | return a + b; 7 | } 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int a; 12 | a = in.nextInt(); 13 | int b; 14 | b = in.nextInt(); 15 | int sum; 16 | sum = solveMeFirst(a, b); 17 | System.out.println(sum); 18 | } 19 | 20 | static int simpleArraySum(int[] ar) { 21 | return Arrays.stream(ar).sum(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/others/Staircase.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | https://www.hackerrank.com/challenges/staircase/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen 5 | */ 6 | public class Staircase { 7 | public static void main(String[] args) { 8 | staircase(4); 9 | System.out.println("**********************************************"); 10 | staircase(6); 11 | } 12 | 13 | static void staircase(int n) { 14 | for (int i = 1; i <= n; i++) { 15 | char[] chars = new char[n]; 16 | Arrays.fill(chars, ' '); 17 | Arrays.fill(chars, n - i, n, '#'); 18 | System.out.println(String.valueOf(chars)); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/others/SuperReducedString.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://www.hackerrank.com/challenges/reduced-string/problem 3 | */ 4 | public class SuperReducedString { 5 | public static void main(String[] args) { 6 | System.out.println(superReducedString("aaabccddd") + " should be [abd]"); 7 | System.out.println(superReducedString("aa") + " should be []"); 8 | System.out.println(superReducedString("baab") + " should be []"); 9 | } 10 | 11 | static String superReducedString(String str) { 12 | for (int i = 1; i < str.length(); i++) { 13 | if (str.charAt(i) == str.charAt(i - 1)) { 14 | str = str.substring(0, i - 1) + str.substring(i + 1); 15 | i = 0; 16 | } 17 | } 18 | return str.length() == 0 ? "Empty String" : str; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/others/TimeConversion.java: -------------------------------------------------------------------------------- 1 | public class TimeConversion { 2 | public static void main(String[] args) { 3 | System.out.println(timeConversion("07:05:45PM")); 4 | System.out.println(timeConversion("12:45:54PM")); 5 | } 6 | 7 | static String timeConversion(String s) { 8 | if (s.length() == 10) { 9 | String hour = s.substring(0, 2); 10 | if (s.charAt(8) == 'P') { 11 | if (hour.equals("12")) { 12 | return s.substring(0, 8); 13 | } 14 | String converted = String.format("%2d", Integer.parseInt(hour) + 12); 15 | return converted + s.substring(2, 8); 16 | } else { 17 | if (hour.equals("12")) { 18 | return "00" + s.substring(2, 8); 19 | } 20 | return s.substring(0, 8); 21 | } 22 | } 23 | throw new IllegalArgumentException("Kindly provide input in hh:mm:ssAM/PM format"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/path/RectangleOverLap.java: -------------------------------------------------------------------------------- 1 | public class RectangleOverLap { 2 | public static void main(String[] args) { 3 | System.out.println(isRectangleOverlap(new int[]{0, 0, 2, 2}, new int[]{1, 1, 3, 3})); 4 | System.out.println(isRectangleOverlap(new int[]{0, 0, 1, 1}, new int[]{1, 0, 2, 1})); 5 | } 6 | 7 | public static boolean isRectangleOverlap(int[] rec1, int[] rec2) { 8 | // Calculate the area and and make sure that rec1 is smaller. 9 | if (rec2[0] > rec1[0] && rec2[0] < rec1[2]) { 10 | return true; 11 | } 12 | return false; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/path/SquirrelSimulation.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Feb 01, 2021 3 | * Questions: https://leetcode.com/problems/squirrel-simulation/ 4 | */ 5 | 6 | public class SquirrelSimulation { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int minDistance(int height, int width, int[] tree, int[] cur, int[][] nuts) { 13 | int total = 0, min = Integer.MAX_VALUE; 14 | for (int[] nut : nuts) { 15 | int d1 = getDistance(cur, nut); 16 | int d2 = getDistance(nut, tree); 17 | min = Math.min(min, d1 - d2); 18 | total += d2 * 2; 19 | } 20 | return total + min; 21 | } 22 | 23 | private static int getDistance(int[] a, int[] b) { 24 | return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/recursion-backtracking/BeautifulArrangement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 05, 2021 3 | * Questions: https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3591/ 4 | */ 5 | 6 | public class BeautifulArrangement { 7 | 8 | int count = 0; 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public int countArrangement(int n) { 15 | boolean[] visited = new boolean[n + 1]; 16 | helper(visited, 1, n, n); 17 | return count; 18 | } 19 | 20 | private void helper(boolean[] visited, int cur, int end, int n) { 21 | if (cur == end + 1) { 22 | count++; 23 | } else { 24 | for (int i = 1; i <= n; i++) { 25 | if (!visited[i] && (i % cur == 0 || cur % i == 0)) { 26 | visited[i] = true; 27 | helper(visited, cur + 1, n, n); 28 | visited[i] = false; 29 | } 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/recursion-backtracking/CountSortedVowelStrings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 17, 2021 3 | * Questions: https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3607/ 4 | */ 5 | 6 | public class CountSortedVowelStrings { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int countVowelStrings(int n) { 13 | Integer[][] dp = new Integer[6][n + 1]; 14 | return helper(0, 0, n, dp); 15 | } 16 | 17 | private static int helper(int pre, int soFar, int n, Integer[][] dp) { 18 | if (pre >= 5) return 0; 19 | if (n == soFar) return 1; 20 | // System.out.println("pre = " + pre + " soFar=" + soFar); 21 | if (dp[pre][soFar] != null) return dp[pre][soFar]; 22 | int count = 0; 23 | for (int i = pre; i < 5; i++) { 24 | count += helper(i, soFar + 1, n, dp); 25 | } 26 | return dp[pre][soFar] = count; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/recursion-backtracking/FallingSquares.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /* 5 | Problem: https://leetcode.com/problems/falling-squares/ 6 | 7 | Solution: https://leetcode.com/articles/falling-squares/ 8 | */ 9 | public class FallingSquares { 10 | public static void main(String[] args) { 11 | int[][] value = { 12 | {1, 2}, 13 | {2, 3}, 14 | {6, 1} 15 | }; 16 | List output = getOutput(value); 17 | System.out.println(output); 18 | } 19 | 20 | private static List getOutput(int[][] value) { 21 | System.out.println(value.length); 22 | int noOfCubes = value.length; 23 | 24 | List output = new ArrayList<>(); 25 | 26 | long maxValue = Long.MIN_VALUE; 27 | 28 | for (int i = 0; i < noOfCubes; i++) { 29 | int x = value[i][0]; 30 | int y = value[i][0]; 31 | maxValue = Math.max(maxValue, y); 32 | } 33 | 34 | return output; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/recursion-backtracking/PermutationSequence.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | /** 5 | * Created on: Jun 20, 2020 6 | * Questions:https://leetcode.com/problems/permutation-sequence 7 | */ 8 | public class PermutationSequence { 9 | static List list; 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static String getPermutation(int n, int k) { 16 | list = new ArrayList<>(); 17 | boolean[] taken = new boolean[n + 1]; 18 | helper(n, k, taken, ""); 19 | return list.get(k - 1); 20 | } 21 | 22 | private static void helper(int n, int k, boolean[] taken, String sofar) { 23 | if (list.size() >= k) return; 24 | if (sofar.length() == n) { 25 | list.add(sofar); 26 | } else { 27 | for (int i = 1; i <= n; i++) { 28 | if (!taken[i]) { 29 | taken[i] = true; 30 | helper(n, k, taken, sofar + i); 31 | taken[i] = false; 32 | } 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/recursion-backtracking/ProductSum.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | /** 4 | * Created on: Sep 28, 2020 5 | * Questions: https://www.algoexpert.io/questions/Product%20Sum 6 | */ 7 | public class ProductSum { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int productSum(List array) { 13 | return productSum(array, 1); 14 | } 15 | 16 | private static int productSum(List array, int level) { 17 | int sum = 0; 18 | for (Object obj : array) { 19 | if (obj instanceof List) { 20 | sum += productSum((List) obj, level + 1); 21 | } else { 22 | sum += (int) obj; 23 | } 24 | } 25 | return sum * level; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/segmentTrees/SumsInTheMatrix.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neerazz/FAANG/7fe3057fdf8a604bac479974378d5eda83178e62/Algorithms/segmentTrees/SumsInTheMatrix.jpg -------------------------------------------------------------------------------- /Algorithms/sliding-door/AverageOfSubarrayOfSizeK.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | /** 6 | * Created on: Jun 28, 2021 7 | * Ref: https://www.educative.io/courses/grokking-the-coding-interview/7D5NNZWQ8Wr 8 | */ 9 | 10 | public class AverageOfSubarrayOfSizeK { 11 | 12 | public static void main(String[] args) { 13 | System.out.println(Arrays.toString(findAverages(5, new int[]{1, 3, 2, 6, -1, 4, 1, 8, 2}))); 14 | } 15 | 16 | public static double[] findAverages(int k, int[] arr) { 17 | List result = new ArrayList<>(); 18 | double windowSum = 0; 19 | int start = 0; 20 | for (int i = 0; i < arr.length; i++) { 21 | windowSum += arr[i]; 22 | if (i - start + 1 == k) { 23 | result.add(windowSum / k); 24 | windowSum -= arr[start++]; 25 | } 26 | } 27 | return result.stream().mapToDouble(val -> val).toArray(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/CharacterReplacement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 30, 2021 3 | * Ref: https://www.educative.io/courses/grokking-the-coding-interview/R8DVgjq78yR#problem-statement 4 | */ 5 | 6 | public class CharacterReplacement { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(findLength("aabccbb", 2) + "=5"); 10 | } 11 | 12 | public static int findLength(String str, int k) { 13 | int[] counts = new int[26]; 14 | int len = str.length(), p1 = 0, p2 = 0, max = 0, maxCharCount = 0; 15 | while (p2 < len) { 16 | int curChar = str.charAt(p2) - 'a'; 17 | counts[curChar]++; 18 | maxCharCount = Math.max(maxCharCount, counts[curChar]); 19 | while (p2 - p1 + 1 - maxCharCount > k) { 20 | counts[str.charAt(p1++) - 'a']--; 21 | } 22 | max = Math.max(max, p2 - p1 + 1); 23 | p2++; 24 | } 25 | return max; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/FruitsIntoBaskets.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: Oct 05, 2020 6 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/Bn2KLlOR0lQ 7 | */ 8 | 9 | public class FruitsIntoBaskets { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static int findLength(char[] arr) { 16 | int count = 0, len = arr.length, p1 = 0, max = 0; 17 | Map bucket = new HashMap<>(); 18 | for (int p2 = 0; p2 < len; p2++) { 19 | char cur = arr[p2]; 20 | bucket.put(cur, bucket.getOrDefault(cur, 0) + 1); 21 | count++; 22 | while (bucket.size() > 2) { 23 | cur = arr[p1++]; 24 | int val = bucket.remove(cur); 25 | if (val > 1) bucket.put(cur, val - 1); 26 | count--; 27 | } 28 | max = Math.max(max, count); 29 | } 30 | return max; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/LongestSubarray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 04, 2020 3 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/B6VypRxPolJ 4 | */ 5 | 6 | public class LongestSubarray { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(findLength(new int[]{0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1}, 2)); 10 | } 11 | 12 | public static int findLength(int[] arr, int k) { 13 | int max = Integer.MIN_VALUE; 14 | int start = 0, len = arr.length; 15 | for (int end = 0; end < len; end++) { 16 | if (arr[end] != 1) { 17 | while (start < end && k == 0) { 18 | k += arr[start++] == 1 ? 0 : 1; 19 | } 20 | k--; 21 | } 22 | max = Math.max(max, end - start + 1); 23 | } 24 | return max; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/LongestSubarrayWithOnesAfterReplacement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 05, 2020 3 | * Questions:https://www.educative.io/courses/grokking-the-coding-interview/B6VypRxPolJ 4 | */ 5 | 6 | public class LongestSubarrayWithOnesAfterReplacement { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(findLength(new int[]{0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1}, 2)); 10 | System.out.println(findLength(new int[]{0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1}, 3)); 11 | } 12 | 13 | public static int findLength(int[] arr, int k) { 14 | int p1 = 0, max = 0, len = arr.length; 15 | for (int i = 0; i < len; i++) { 16 | if (arr[i] != 1) { 17 | while (p1 < i && k == 0) { 18 | k += arr[p1++] == 1 ? 0 : 1; 19 | } 20 | k--; 21 | } 22 | max = Math.max(max, i - p1 + 1); 23 | } 24 | return max; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/LongestSubstringWithKDistinctCharacters.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: Oct 05, 2020 6 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/YQQwQMWLx80 7 | */ 8 | 9 | public class LongestSubstringWithKDistinctCharacters { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static int findLength(String str, int k) { 16 | Map window = new HashMap<>(); 17 | int max = 0, p1 = 0, len = str.length(); 18 | for (int p2 = 0; p2 < len; p2++) { 19 | char cur = str.charAt(p2); 20 | window.put(cur, window.getOrDefault(cur, 0) + 1); 21 | while (window.size() > k) { 22 | cur = str.charAt(p1); 23 | int count = window.remove(cur); 24 | if (count > 1) window.put(cur, count - 1); 25 | p1++; 26 | } 27 | max = Math.max(max, p2 - p1 + 1); 28 | } 29 | return max; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/LongestSubstringWithSameLettersAfterReplacement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 05, 2020 3 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/R8DVgjq78yR 4 | */ 5 | 6 | public class LongestSubstringWithSameLettersAfterReplacement { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int findLength(String str, int k) { 13 | int max = Integer.MIN_VALUE, len = str.length(); 14 | for (int i = 0; i < len; i++) { 15 | int temp = k, count = 0, j = i; 16 | while (j < len && (str.charAt(i) == str.charAt(j) || temp > 0)) { 17 | count++; 18 | temp -= str.charAt(i) == str.charAt(j) ? 0 : 1; 19 | j++; 20 | } 21 | max = Math.max(max, count); 22 | } 23 | return max; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/MaximumPointsYouCanObtainFromCards.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 23, 2021 3 | * Ref : https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ 4 | */ 5 | public class MaximumPointsYouCanObtainFromCards { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int maxScore(int[] nums, int k) { 11 | int sum = 0, max = 0, len = nums.length; 12 | for (int i = 0; i < len && i < k; i++) { 13 | sum += nums[i]; 14 | } 15 | if (len == k) return sum; 16 | max = sum; 17 | for (int i = 0; i < len && i < k; i++) { 18 | sum -= nums[k - i - 1]; 19 | sum += nums[len - i - 1]; 20 | max = Math.max(max, sum); 21 | } 22 | return max; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/MaximumSumSubarrayOfSizeK.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 05, 2020 3 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/JPKr0kqLGNP 4 | */ 5 | 6 | public class MaximumSumSubarrayOfSizeK { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int findMaxSumSubArray(int k, int[] arr) { 13 | int sum = 0, max = Integer.MIN_VALUE; 14 | for (int i = 0; i < k - 1; i++) sum += arr[i]; 15 | for (int i = k - 1; i < arr.length; i++) { 16 | sum += arr[i]; 17 | max = Math.max(max, sum); 18 | sum -= arr[i - k + 1]; 19 | } 20 | return max; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/NoRepeatSubstring.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * Created on: Oct 05, 2020 6 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/YMzBx1gE5EO 7 | */ 8 | 9 | public class NoRepeatSubstring { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static int findLength(String str) { 16 | Set set = new HashSet<>(); 17 | int max = 0, len = str.length(), p1 = 0; 18 | for (int p2 = 0; p2 < len; p2++) { 19 | char cur = str.charAt(p2); 20 | if (!set.add(cur)) { 21 | while (p1 <= p2 && str.charAt(p1) != cur) { 22 | set.remove(str.charAt(p1++)); 23 | } 24 | p1++; 25 | } 26 | max = Math.max(max, p2 - p1 + 1); 27 | } 28 | return max; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/PartitionArrayIntoDisjointIntervals.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 21, 2021 3 | * Ref: https://leetcode.com/problems/partition-array-into-disjoint-intervals/ 4 | */ 5 | 6 | public class PartitionArrayIntoDisjointIntervals { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int partitionDisjoint(int[] nums) { 13 | int len = nums.length; 14 | int[] maxLeft = new int[len], minRight = new int[len]; 15 | int max = Integer.MIN_VALUE, min = nums[len - 1]; 16 | for (int i = 0; i < len; i++) { 17 | maxLeft[i] = max = Math.max(max, nums[i]); 18 | } 19 | int leftSize = -1; 20 | for (int i = len - 2; i >= 0; i--) { 21 | int left = maxLeft[i]; 22 | // left = max item on left. 23 | // min = min item on right. 24 | if (left <= min) leftSize = i + 1; 25 | min = Math.min(min, nums[i]); 26 | } 27 | return leftSize; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/ReplacingOnes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 30, 2021 3 | * Ref: https://www.educative.io/courses/grokking-the-coding-interview/B6VypRxPolJ#problem-statement 4 | */ 5 | 6 | public class ReplacingOnes { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int findLength(int[] arr, int k) { 13 | int[] counts = {0, 0}; 14 | int len = arr.length, i = 0, j = 0, max = 0; 15 | while (j < len) { 16 | counts[arr[j]]++; 17 | while (i <= j && counts[0] > k) { 18 | counts[arr[i++]]--; 19 | } 20 | max = Math.max(max, j - i + 1); 21 | j++; 22 | } 23 | return max; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/SmallestSubarrayWithAGivenSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 05, 2020 3 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/7XMlMEQPnnQ 4 | */ 5 | 6 | public class SmallestSubarrayWithAGivenSum { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int findMinSubArray(int S, int[] arr) { 13 | int sum = 0, len = arr.length, min = len + 1, p1 = 0, p2 = 0; 14 | while (p2 < len) { 15 | sum += arr[p2]; 16 | while (p1 <= p2 && sum >= S) { 17 | min = Math.min(min, p2 - p1 + 1); 18 | sum -= arr[p1++]; 19 | } 20 | p2++; 21 | } 22 | return min == len + 1 ? -1 : min; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/sliding-door/StringPermutation.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Jun 30, 2021 5 | * Ref: https://www.educative.io/courses/grokking-the-coding-interview/N8vB7OVYo2D#permutation-in-a-string-hard 6 | */ 7 | 8 | public class StringPermutation { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static boolean findPermutation(String str, String pattern) { 15 | int[] required = new int[26]; 16 | for (char c : pattern.toCharArray()) required[c - 'a']++; 17 | int[] window = new int[26]; 18 | int p1 = 0, p2 = 0, len = str.length(), reqLen = pattern.length(); 19 | while (p2 < len) { 20 | window[str.charAt(p2) - 'a']++; 21 | if (p2 - p1 + 1 == reqLen) { 22 | if (Arrays.equals(required, window)) return true; 23 | window[str.charAt(p1++) - 'a']--; 24 | } 25 | p2++; 26 | } 27 | return false; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/BackspaceCompare.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Created on: Oct 06, 2020 5 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/g7pBzR12YPl 6 | */ 7 | 8 | public class BackspaceCompare { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static boolean compare(String str1, String str2) { 15 | str1 = BackspaceCompare.resolveString(str1); 16 | str2 = BackspaceCompare.resolveString(str2); 17 | return str1.equals(str2); 18 | } 19 | 20 | private static String resolveString(String str) { 21 | Stack stack = new Stack<>(); 22 | for (char c : str.toCharArray()) { 23 | if (c == '#') { 24 | if (stack.isEmpty()) continue; 25 | stack.pop(); 26 | } else { 27 | stack.add(c); 28 | } 29 | } 30 | StringBuilder sb = new StringBuilder(); 31 | while (!stack.isEmpty()) { 32 | sb.append(stack.pop()); 33 | } 34 | return sb.reverse().toString(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/BuddyStrings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 12, 2020 3 | * Questions: 4 | */ 5 | 6 | public class BuddyStrings { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public boolean buddyStrings(String A, String B) { 13 | if (A.length() != B.length()) return false; 14 | int len = A.length(), mismatch = 0, diff = 0; 15 | int[] count = new int[26]; 16 | for (int i = 0; i < len; i++) { 17 | count[A.charAt(i) - 'a']++; 18 | if (A.charAt(i) != B.charAt(i)) { 19 | if (diff == 1) { 20 | if (mismatch != B.charAt(i) - A.charAt(i)) return false; 21 | } else { 22 | mismatch = A.charAt(i) - B.charAt(i); 23 | } 24 | diff++; 25 | } 26 | if (diff > 2) return false; 27 | } 28 | if (diff == 0) { 29 | for (int i = 0; i < 26; i++) { 30 | if (count[i] > 1) return true; 31 | } 32 | } 33 | return diff == 2; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/DetectCapital.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 04, 2020 3 | * Questions: https://leetcode.com/problems/detect-capital/ 4 | */ 5 | public class DetectCapital { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static boolean detectCapitalUse(String word) { 11 | boolean isLower = false; 12 | int i = 0; 13 | for (char cur : word.toCharArray()) { 14 | if (Character.isUpperCase(cur)) { 15 | if (isLower) return false; 16 | } else { 17 | if (!isLower && i > 1) return false; 18 | } 19 | isLower = Character.isLowerCase(cur); 20 | i++; 21 | } 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/KthMissingPositiveNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 06, 2021 3 | * Questions: https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3594/ 4 | */ 5 | 6 | public class KthMissingPositiveNumber { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int findKthPositive(int[] arr, int k) { 13 | int pre = 0, count = 0; 14 | for (int num : arr) { 15 | int cur = num - pre - 1; 16 | if (cur + count >= k) break; 17 | count += cur; 18 | pre = num; 19 | } 20 | while (count < k) { 21 | pre++; 22 | count++; 23 | } 24 | return pre; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/MaxNumberOfKSumPairs.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Jan 18, 2021 5 | * Questions: https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3608/ 6 | */ 7 | 8 | public class MaxNumberOfKSumPairs { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static int maxOperations(int[] nums, int k) { 15 | Arrays.sort(nums); 16 | int start = 0, end = nums.length - 1; 17 | int count = 0; 18 | while (start < end) { 19 | int sum = nums[start] + nums[end]; 20 | if (sum == k) { 21 | start++; 22 | end--; 23 | count++; 24 | } else if (sum < k) { 25 | start++; 26 | } else { 27 | end--; 28 | } 29 | } 30 | return count; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 19, 2020 3 | * Questions: https://leetcode.com/problems/merge-sorted-array/ 4 | */ 5 | public class MergeSortedArray { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public void merge(int[] nums1, int m, int[] nums2, int n) { 11 | int p1 = m - 1, p2 = n - 1, last = m + n - 1; 12 | while (p1 >= 0 && p2 >= 0) { 13 | if (nums1[p1] >= nums2[p2]) { 14 | nums1[last--] = nums1[p1--]; 15 | } else { 16 | nums1[last--] = nums2[p2--]; 17 | } 18 | } 19 | while (p1 >= 0) nums1[last--] = nums1[p1--]; 20 | while (p2 >= 0) nums1[last--] = nums2[p2--]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/NumberOfSubArraysOfSizeKAndAverageGreaterThanOrEqualToThreshold.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 30, 2020 3 | * Questions: https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/ 4 | */ 5 | public class NumberOfSubArraysOfSizeKAndAverageGreaterThanOrEqualToThreshold { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int numOfSubarrays(int[] arr, int k, int threshold) { 11 | double sum = 0; 12 | int idx = 0, count = 0, p1 = 0; 13 | while (idx < k - 1) { 14 | sum += arr[idx++]; 15 | } 16 | for (int i = idx; i < arr.length; i++) { 17 | sum += arr[i]; 18 | if (sum / k >= threshold) count++; 19 | sum -= arr[p1++]; 20 | } 21 | return count; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Oct 06, 2020 5 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/mEEA22L5mNA 6 | */ 7 | 8 | public class RemoveDuplicates { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static int remove(int[] arr) { 15 | int nonDublicateIdx = 0; 16 | for (int i = 0; i < arr.length - 1; i++) { 17 | if (arr[i] == arr[i + 1]) continue; 18 | arr[nonDublicateIdx++] = arr[i]; 19 | } 20 | arr[nonDublicateIdx++] = arr[arr.length - 1]; 21 | System.out.println(Arrays.toString(arr)); 22 | return nonDublicateIdx; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/RemoveDuplicatesFromSortedArrayII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Dec 11, 2020 3 | * Questions: https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/570/week-2-december-8th-december-14th/3562/ 4 | */ 5 | 6 | public class RemoveDuplicatesFromSortedArrayII { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int removeDuplicates(int[] nums) { 13 | int pre = Integer.MIN_VALUE, count = 0, preIdx = 0; 14 | for (int cur : nums) { 15 | if (pre == cur) { 16 | if (count++ < 2) { 17 | nums[preIdx++] = cur; 18 | } 19 | } else { 20 | nums[preIdx++] = cur; 21 | count = 1; 22 | pre = cur; 23 | } 24 | } 25 | return preIdx; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/SentenceScreenFitting.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 26, 2021 3 | * Ref : https://leetcode.com/problems/sentence-screen-fitting/ 4 | */ 5 | public class SentenceScreenFitting { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int wordsTyping(String[] sentence, int rows, int cols) { 11 | int row = 0, col = 0, count = 0, len = sentence.length, i = 0; 12 | while (row < rows && col < cols && i < len) { 13 | while (sentence[i].length() <= cols - col && i < len) { 14 | col += sentence[i++].length() + 1; 15 | if (i == len) { 16 | count++; 17 | i = 0; 18 | } 19 | } 20 | row++; 21 | col = 0; 22 | } 23 | return count; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/TripletSumToZero.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | /** 6 | * Created on: Oct 06, 2020 7 | * Questions: https://www.educative.io/courses/grokking-the-coding-interview/gxk639mrr5r 8 | */ 9 | 10 | public class TripletSumToZero { 11 | 12 | public static void main(String[] args) { 13 | 14 | } 15 | 16 | public static List> searchTriplets(int[] arr) { 17 | List> triplets = new ArrayList<>(); 18 | Arrays.sort(arr); 19 | for (int i = 0; i < arr.length - 2; i++) { 20 | int target = arr[i] * -1; 21 | int start = i + 1, end = arr.length - 1; 22 | while (start < end) { 23 | int sum = arr[start] + arr[end]; 24 | if (sum == target) { 25 | triplets.add(Arrays.asList(arr[i], arr[start++], arr[end--])); 26 | } else if (sum < target) { 27 | start++; 28 | } else { 29 | end--; 30 | } 31 | } 32 | } 33 | return triplets; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/two-pointer/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 01, 2020 3 | * Questions: https://leetcode.com/problems/valid-palindrome/ 4 | */ 5 | public class ValidPalindrome { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public boolean isPalindrome(String str) { 11 | int s = 0, e = str.length() - 1; 12 | while (s < e) { 13 | while (s < str.length() && !Character.isLetterOrDigit(str.charAt(s))) s++; 14 | while (e >= 0 && !Character.isLetterOrDigit(str.charAt(e))) e--; 15 | if (s < e && Character.toLowerCase(str.charAt(s++)) != Character.toLowerCase(str.charAt(e--))) return false; 16 | } 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | v1.0 | :white_check_mark: | 11 | 12 | ## Reporting a Vulnerability 13 | 14 | Use this section to tell people how to report a vulnerability. 15 | 16 | Tell them where to go, how often they can expect to get an update on a 17 | reported vulnerability, what to expect if the vulnerability is accepted or 18 | declined, etc. 19 | -------------------------------------------------------------------------------- /blind75/arrays/FindMinimumInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class FindMinimumInRotatedSortedArray { 4 | 5 | public static void main(String[] args) { 6 | int[] input = new int[]{3, 4, 5, 1, 2}; 7 | System.out.println(findMin(input)); 8 | //TODO:Implement this 9 | } 10 | 11 | public static int findMin(int[] nums) { 12 | int left = 0, right = nums.length - 1, mid = 0; 13 | if (nums[left] < nums[right]) return nums[left]; 14 | while (left < right) { 15 | mid = left + (right - left) / 2; 16 | if (nums[left] > nums[mid]) { 17 | right = mid; 18 | } else if (nums[right] < nums[mid]) { 19 | left = mid; 20 | } 21 | } 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /blind75/arrays/MaximumSumSubArray.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | /* 4 | https://leetcode.com/problems/maximum-subarray/ 5 | P 6 | 7 | Given an integer array nums, find the contiguous subarray (containing at least one number) 8 | which has the largest sum and return its sum. A subarray is a contiguous part of an array. 9 | 10 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 11 | Output: 6 12 | Explanation: [4,-1,2,1] has the largest sum = 6. 13 | 14 | Input: nums = [5,4,-1,7,8] 15 | Output: 23 16 | */ 17 | public class MaximumSumSubArray { 18 | 19 | public static void main(String[] args) { 20 | int[] input = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}; 21 | System.out.println(maxSubArray(input)); 22 | } 23 | 24 | 25 | //Insight - Reset when the value is negative 26 | public static int maxSubArray(int[] nums) { 27 | int sol = Integer.MIN_VALUE, sum = 0; 28 | for (int num : nums) { 29 | sum += num; 30 | sum = Math.max(sum, num); 31 | sol = Math.max(sol, sum); 32 | } 33 | return sol; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /blind75/linkedlist/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | package linkedlist; 2 | 3 | import util.ListNode; 4 | 5 | /* 6 | https://leetcode.com/problems/reverse-linked-list 7 | F 8 | Given the head of a singly linked list, reverse the list, and return the reversed list. 9 | Input: head = [1,2,3,4,5] 10 | Output: [5,4,3,2,1] 11 | 12 | */ 13 | public class ReverseLinkedList { 14 | 15 | public static void main(String[] args) { 16 | 17 | } 18 | 19 | //Insight - use three things 20 | //prev , curr, next 21 | //Reversed will be in prev 22 | //We reverse a section and assign to curr 23 | //Next will be in curr 24 | public ListNode reverseList(ListNode head) { 25 | ListNode prev = null; 26 | ListNode curr = head; 27 | while (curr != null) { 28 | ListNode next = curr.next; 29 | curr.next = prev; 30 | prev = curr; 31 | curr = next; 32 | } 33 | return prev; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /blind75/matrix/SetMatrixZeroes.java: -------------------------------------------------------------------------------- 1 | package matrix; 2 | 3 | public class SetMatrixZeroes { 4 | //TODO: Implement this 5 | } 6 | -------------------------------------------------------------------------------- /blind75/strings/MinimumWindowSubstring.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class MinimumWindowSubstring { 4 | //TODO: Implement this 5 | } 6 | -------------------------------------------------------------------------------- /blind75/strings/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | /* 4 | https://leetcode.com/problems/valid-anagram/ 5 | P 6 | Given two strings s and t, return true if t is an anagram of s, and false otherwise. 7 | 8 | Example 1: 9 | Input: s = "anagram", t = "nagaram" 10 | Output: true 11 | 12 | Example 2: 13 | Input: s = "rat", t = "car" 14 | Output: false 15 | 16 | */ 17 | public class ValidAnagram { 18 | 19 | public static void main(String[] args) { 20 | 21 | } 22 | 23 | //Insight - Count and Compare 24 | //Sorting is another technique that can be used. 25 | public static boolean isAnagram(String s, String t) { 26 | if (s.length() != t.length()) return false; 27 | int[] arr = new int[26]; 28 | 29 | for (int i = 0; i < s.length(); i++) { 30 | arr[s.charAt(i) - 'a']++; 31 | arr[t.charAt(i) - 'a']--; 32 | } 33 | 34 | for (int j : arr) { 35 | if (j != 0) return false; 36 | } 37 | return true; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /blind75/trees/BinaryTreeMaximumPathSum.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | public class BinaryTreeMaximumPathSum { 4 | //TODO: Implement this 5 | } 6 | -------------------------------------------------------------------------------- /blind75/trees/InvertTree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import util.TreeNode; 4 | import util.Util; 5 | 6 | /* 7 | https://leetcode.com/problems/invert-binary-tree/ 8 | F 9 | 10 | Given the root of a binary tree, invert the tree, and return its root. 11 | 12 | Input: root = [4,2,7,1,3,6,9] 13 | Output: [4,7,2,9,6,3,1] 14 | 15 | Input: root = [2,1,3] 16 | Output: [2,3,1] 17 | */ 18 | 19 | public class InvertTree { 20 | 21 | public static TreeNode invertTree(TreeNode root) { 22 | if (root == null) 23 | return null; 24 | TreeNode left = invertTree(root.left); 25 | TreeNode right = invertTree(root.right); 26 | root.left = right; 27 | root.right = left; 28 | return root; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Integer[] input = new Integer[]{4, 2, 7, 1, 3, 6, 9}; 33 | TreeNode root = Util.createTree(input); 34 | TreeNode sol = invertTree(root); 35 | Util.print(sol); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /blind75/trees/SameTree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | /* 4 | https://leetcode.com/problems/same-tree/ 5 | F 6 | 7 | Given the roots of two binary trees p and q, write a function to check if they are the same or not. 8 | Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. 9 | 10 | Input: p = [1,2,3], q = [1,2,3] 11 | Output: true 12 | 13 | Input: p = [1,2], q = [1,null,2] 14 | Output: false 15 | 16 | Input: p = [1,2,1], q = [1,1,2] 17 | Output: false 18 | */ 19 | 20 | import util.TreeNode; 21 | 22 | public class SameTree { 23 | 24 | public static boolean isSameTree(TreeNode p, TreeNode q) { 25 | if (p == null && q == null) return true; 26 | if (p == null || q == null) return false; 27 | boolean leftMatch = isSameTree(p.left, q.left); 28 | boolean valMatch = p.val == q.val; 29 | boolean rightMatch = isSameTree(p.right, q.right); 30 | return leftMatch && valMatch && rightMatch; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /blind75/trees/SerializeAndDeserializeBinaryTree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | public class SerializeAndDeserializeBinaryTree { 4 | //TODO: Implement this 5 | } 6 | -------------------------------------------------------------------------------- /blind75/util/ListNode.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | public class ListNode { 4 | public int val; 5 | public ListNode next; 6 | 7 | public ListNode(int x) { 8 | val = x; 9 | next = null; 10 | } 11 | } -------------------------------------------------------------------------------- /blind75/util/Node.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | public class Node { 4 | 5 | public int val; 6 | public Node next; 7 | 8 | public Node() { 9 | } 10 | 11 | public Node(int _val, Node _next) { 12 | val = _val; 13 | next = _next; 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /blind75/util/TreeNode.java: -------------------------------------------------------------------------------- 1 | package util; 2 | 3 | public class TreeNode { 4 | public int val; 5 | public TreeNode left; 6 | public TreeNode right; 7 | 8 | public TreeNode(int x) { 9 | val = x; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return String.valueOf(val); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /dataStructures/LinkedList/ConvertSortedListToBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 31, 2020 3 | * Questions: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ 4 | */ 5 | public class ConvertSortedListToBinarySearchTree { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static TreeNode sortedListToBST(ListNode head) { 11 | if (head == null) return null; 12 | ListNode left = new ListNode(-1), leftRef = left, slow = head, fast = head; 13 | while (fast != null && fast.next != null) { 14 | leftRef.next = new ListNode(slow.val); 15 | leftRef = leftRef.next; 16 | slow = slow.next; 17 | fast = fast.next.next; 18 | } 19 | TreeNode cur = new TreeNode(slow.val); 20 | cur.left = sortedListToBST(left.next); 21 | cur.right = sortedListToBST(slow.next); 22 | return cur; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /dataStructures/LinkedList/LinkedListCycleII.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 28, 2020 3 | * Questions: https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/562/week-4-october-22nd-october-28th/3509/ 4 | */ 5 | 6 | public class LinkedListCycleII { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static ListNode detectCycle(ListNode head) { 13 | if (head == null || head.next == null) return null; 14 | ListNode slow = head.next, fast = head.next.next; 15 | while (fast != null && fast.next != null && slow != fast) { 16 | slow = slow.next; 17 | fast = fast.next.next; 18 | } 19 | if (slow != fast) return null; 20 | fast = head; 21 | while (slow != fast) { 22 | slow = slow.next; 23 | fast = fast.next; 24 | } 25 | return slow; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/LinkedList/LinkedListRandomNode.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Random; 4 | 5 | /** 6 | * Created on: Jul 26, 2020 7 | * Questions: https://leetcode.com/problems/linked-list-random-node/ 8 | */ 9 | public class LinkedListRandomNode { 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | static class Solution { 15 | 16 | Random random; 17 | Map map; 18 | 19 | public Solution(ListNode head) { 20 | map = new HashMap<>(); 21 | random = new Random(); 22 | int i = 0; 23 | while (head != null) { 24 | map.put(i++, head.val); 25 | head = head.next; 26 | } 27 | } 28 | 29 | public int getRandom() { 30 | return map.get(random.nextInt(map.size())); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dataStructures/LinkedList/RemoveLinkedListElements.java: -------------------------------------------------------------------------------- 1 | /* 2 | Remove all elements from a linked list of integers that have value val. 3 | Example: 4 | Input: 1->2->6->3->4->5->6, val = 6 5 | Output: 1->2->3->4->5 6 | */ 7 | public class RemoveLinkedListElements { 8 | public static void main(String[] args) { 9 | System.out.println(removeElements(RemoveNthNodeFromEndOfList.createListNode(new int[]{1, 2, 6, 3, 4, 5, 6}), 6)); 10 | } 11 | 12 | public static ListNode removeElements(ListNode head, int val) { 13 | if (head == null) return null; 14 | ListNode current = head, outputRef = new ListNode(head.val), output = outputRef; 15 | while (current != null) { 16 | current = current.next; 17 | if (current != null && current.val != val) { 18 | output.next = new ListNode(current.val); 19 | output = output.next; 20 | } 21 | } 22 | return head.val == val ? outputRef.next : outputRef; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /dataStructures/arrays/CheckFirstUnique.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | /** 5 | * Created on: Jan 24, 2024 6 | * Ref: 7 | * In this problem, you have to implement the int findFirstUnique(int[] arr) method that will look for a first unique integer, which appears only once in the whole array. The function returns -1 if no unique number is found. 8 | * 9 | * Method Prototype 10 | * int findFirstUnique(int[] arr) 11 | * Output 12 | * The first unique element in the array. 13 | * 14 | * Sample Input 15 | * arr = {9, 2, 3, 2, 6, 6} 16 | * Sample Output 17 | * 9 18 | */ 19 | 20 | public class CheckFirstUnique { 21 | 22 | public static void main(String[] args) { 23 | 24 | } 25 | 26 | public static int findFirstUnique(int[] arr){ 27 | LinkedHashMap map = new LinkedHashMap<>(); 28 | for(int num: arr){ 29 | map.put(num, map.getOrDefault(num, 0)+1); 30 | } 31 | return map.entrySet().stream() 32 | .filter(e -> e.getValue() == 1) 33 | .map(e -> e.getKey()) 34 | .findFirst().orElse(-1); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /dataStructures/arrays/CheckMinimum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | /** 5 | * Created on: Jan 23, 2024 6 | * Ref: In this problem, you have to implement the int findMinimum(int[] arr) method, which will traverse the whole array and find the smallest number in the array. 7 | */ 8 | 9 | public class CheckMinimum { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static int findMinimum(int[] arr) { 16 | if(arr == null || arr.length == 0) return -1; 17 | return Arrays.stream(arr).min().getAsInt(); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/Anagram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Anagram { 4 | public static void main(String[] args) { 5 | System.out.println(stringAnagram(Arrays.asList("heater", "cold", "clod", "reheat", "docl"), Arrays.asList("codl", "heater", "abcd"))); 6 | } 7 | 8 | public static List stringAnagram(List dictionary, List query) { 9 | // Collect all the words with its sorted values and the unsorted array. 10 | Map map = new HashMap<>(); 11 | for (String word : dictionary) { 12 | String sorted = sortByChars(word); 13 | map.put(sorted, map.getOrDefault(sorted, 0) + 1); 14 | } 15 | List op = new ArrayList<>(); 16 | for (String q : query) { 17 | String sorted = sortByChars(q); 18 | op.add(map.getOrDefault(sorted, 0)); 19 | } 20 | return op; 21 | } 22 | 23 | static String sortByChars(String input) { 24 | char[] wordChars = input.toCharArray(); 25 | Arrays.sort(wordChars); 26 | return new StringBuilder().append(wordChars).toString(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/AppleAndOrange.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: Apr 19, 2020 3 | */ 4 | 5 | /** 6 | * Questions: https://www.hackerrank.com/challenges/apple-and-orange/problem 7 | */ 8 | public class AppleAndOrange { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | static void countApplesAndOranges(int s, int t, int a, int b, int[] apples, int[] oranges) { 14 | int apl = 0, org = 0; 15 | for (int i : apples) { 16 | if (fellInHouse(s, t, a + i)) apl++; 17 | } 18 | for (int i : oranges) { 19 | if (fellInHouse(s, t, b + i)) org++; 20 | } 21 | System.out.println(apl); 22 | System.out.println(org); 23 | } 24 | 25 | static boolean fellInHouse(int s, int t, int point) { 26 | return s <= point && t >= point; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/ArrayPartitionI.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1154/ 5 | */ 6 | public class ArrayPartitionI { 7 | public static void main(String[] args) { 8 | System.out.println("Answer is: " + arrayPairSum(new int[]{1, 4, 3, 2}) + " should be 4"); 9 | } 10 | 11 | public static int arrayPairSum(int[] nums) { 12 | Arrays.sort(nums); 13 | int index = 0; 14 | int size = nums.length; 15 | if (size == 0) return 0; 16 | int result = 0; 17 | while (index < size) { 18 | result += Math.min(nums[index], nums[index + 1]); 19 | index += 2; 20 | } 21 | return result; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/CaesarCipherEncryptor.java: -------------------------------------------------------------------------------- 1 | class CaesarCipherEncryptor { 2 | public static void main(String[] args) { 3 | System.out.println(caesarCypherEncryptor("xyz", 2)); 4 | } 5 | 6 | public static String caesarCypherEncryptor(String str, int key) { 7 | char[] chars = new char[] 8 | {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 9 | StringBuilder sb = new StringBuilder(); 10 | for (char c : str.toCharArray()) { 11 | int index = c - 'a' + key; 12 | if (index > 25) { 13 | index %= 26; 14 | } 15 | sb.append(chars[index]); 16 | } 17 | return sb.toString(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/CityTravel.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: Apr 25, 2020 3 | */ 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * Questions: https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/city-travel-59bad87f/ 10 | */ 11 | public class CityTravel { 12 | public static void main(String[] args) { 13 | FastReader sr = new FastReader(); 14 | int s = sr.nextInt(), x = sr.nextInt(), n = sr.nextInt(); 15 | Map exceptions = new HashMap<>(); 16 | for (int i = 0; i < n; i++) { 17 | exceptions.put(sr.nextInt(), sr.nextInt()); 18 | } 19 | int distance = 0, day = 0; 20 | while (distance <= s) { 21 | distance += exceptions.getOrDefault(++day, x); 22 | if (distance >= s) { 23 | System.out.println(day); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/CompareVersionNumbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 09, 2020 3 | * Questions: https://leetcode.com/problems/compare-version-numbers/ 4 | */ 5 | public class CompareVersionNumbers { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public int compareVersion(String version1, String version2) { 11 | String[] v1 = version1.split("\\."), v2 = version2.split("\\."); 12 | // System.out.println(Arrays.toString(v1)); 13 | // System.out.println(Arrays.toString(v2)); 14 | int p1 = 0, p2 = 0, l1 = v1.length, l2 = v2.length; 15 | while (p1 < l1 && p2 < l2) { 16 | int cur1 = Integer.parseInt(v1[p1++]), cur2 = Integer.parseInt(v2[p2++]); 17 | if (cur1 == cur2) continue; 18 | if (cur1 < cur2) return -1; 19 | else return 1; 20 | } 21 | while (p1 < l1) { 22 | if (Integer.parseInt(v1[p1++]) > 0) return 1; 23 | } 24 | while (p2 < l2) { 25 | if (Integer.parseInt(v2[p2++]) > 0) return -1; 26 | } 27 | return 0; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/CountAndSay.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 19, 2020 3 | * Questions: https://leetcode.com/problems/count-and-say/ 4 | */ 5 | public class CountAndSay { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static String countAndSay(int n) { 11 | String str = "1"; 12 | while (n > 1) { 13 | StringBuilder sb = new StringBuilder(); 14 | char pre = str.charAt(0); 15 | int count = 0; 16 | for (char cur : str.toCharArray()) { 17 | if (pre == cur) count++; 18 | else { 19 | sb.append(count).append(pre); 20 | pre = cur; 21 | count = 1; 22 | } 23 | } 24 | sb.append(count).append(pre); 25 | str = sb.toString(); 26 | n--; 27 | } 28 | return str; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/CountingValleys.java: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen 3 | Sample Input 4 | 8 5 | UDDDUDUU 6 | Sample Output 7 | 1 8 | */ 9 | public class CountingValleys { 10 | 11 | public static void main(String[] args) { 12 | System.out.println(countingValleys(8, "UDDDUDUU")); 13 | System.out.println(countingValleys(12, "DDUUDDUDUUUD")); 14 | } 15 | 16 | static int countingValleys(int n, String s) { 17 | int level = 0; 18 | int previous; 19 | int valleys = 0; 20 | for (int i = 0; i < n; i++) { 21 | previous = level; 22 | if (s.charAt(i) == 'U') level++; 23 | else level--; 24 | if (level == 0 && previous < 0) valleys++; 25 | } 26 | return valleys; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/DesignerPDFViewer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 19, 2020 3 | * Questions: https://www.hackerrank.com/challenges/designer-pdf-viewer/problem 4 | */ 5 | public class DesignerPDFViewer { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | static int designerPdfViewer(int[] h, String word) { 11 | int tallest = 0; 12 | for (char cur : word.toCharArray()) { 13 | tallest = Math.max(tallest, h[cur - 'a']); 14 | } 15 | return tallest * word.length(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/GoatLatin.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 19, 2020 3 | * Questions: https://leetcode.com/problems/goat-latin/ 4 | */ 5 | public class GoatLatin { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static String toGoatLatin(String S) { 11 | StringBuilder sb = new StringBuilder(); 12 | String[] split = S.split(" "); 13 | int i = 0; 14 | 15 | while (i < split.length) { 16 | String cur = split[i++]; 17 | if (isVowel(cur)) { 18 | sb.append(cur).append("ma"); 19 | } else { 20 | sb.append(cur.substring(1)).append(cur.charAt(0)).append("ma"); 21 | } 22 | int temp = i; 23 | while (temp > 0) { 24 | sb.append("a"); 25 | } 26 | sb.append(" "); 27 | } 28 | 29 | return sb.toString().trim(); 30 | } 31 | 32 | private static boolean isVowel(String str) { 33 | char first = Character.toLowerCase(str.charAt(0)); 34 | return first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u'; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/GradingStudents.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: Apr 19, 2020 3 | */ 4 | 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | /** 9 | * Questions: 10 | */ 11 | public class GradingStudents { 12 | public static void main(String[] args) { 13 | 14 | } 15 | 16 | public static List gradingStudents(List grades) { 17 | return grades.stream().map(val -> { 18 | int diff = val % 5; 19 | if (diff > 2 && val >= 38) { 20 | return ((val / 5) + 1) * 5; 21 | } else { 22 | return val; 23 | } 24 | }).collect(Collectors.toList()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class GroupAnagrams { 4 | public static void main(String[] args) { 5 | 6 | } 7 | 8 | public static List> groupAnagrams(List words) { 9 | Map> map = new HashMap<>(); 10 | for (String word : words) { 11 | char[] chars = word.toCharArray(); 12 | Arrays.sort(chars); 13 | String sorted = String.valueOf(chars); 14 | List values = map.getOrDefault(sorted, new ArrayList<>()); 15 | values.add(word); 16 | map.put(sorted, values); 17 | } 18 | return new ArrayList<>(map.values()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/Kangaroo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: Apr 19, 2020 3 | */ 4 | 5 | /** 6 | * Questions: 7 | */ 8 | public class Kangaroo { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | /** 14 | * @param x1 Kangaroo1 start point 15 | * @param v1 Kangaroo1 steps at each jump 16 | * @param x2 Kangaroo2 start point 17 | * @param v2 Kangaroo2 steps at each jump 18 | * @return If both the kangaroos can meet at a point. 19 | * @implNote Imagine that both of them meets after x steps. Then the equations would look like 20 | * x1 + x * v1 = x2 + x * v2; 21 | * x (v1-v2) = x2-x1 22 | * x = (x2 - x1) / (v1 - v2) 23 | * By using the above formula, if both the kangaroors to meet then x >= 0 && x would be a whole number. 24 | */ 25 | static String kangaroo(int x1, int v1, int x2, int v2) { 26 | int jumpDif = v1 - v2; 27 | int startDif = x2 - x1; 28 | if (jumpDif != 0 && startDif / jumpDif >= 0 && startDif % jumpDif == 0) return "YES"; 29 | return "NO"; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/LeftRotation.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | https://www.hackerrank.com/challenges/ctci-array-left-rotation/ 5 | 6 | */ 7 | public class LeftRotation { 8 | public static void main(String[] args) { 9 | System.out.println(Arrays.toString(rotLeft(new int[]{1, 2, 3, 4, 5}, 4))); 10 | System.out.println(Arrays.toString(rotLeft(new int[]{41, 73, 89, 7, 10, 1, 59, 58, 84, 77, 77, 97, 58, 1, 86, 58, 26, 10, 86, 51}, 10))); 11 | } 12 | 13 | static int[] rotLeft(int[] a, int d) { 14 | int[] output = new int[a.length]; 15 | int start = 0, second = d; 16 | for (int i = d; i < a.length; i++) { 17 | output[start++] = a[second++]; 18 | } 19 | for (int i = 0; i < d; i++) { 20 | output[start++] = a[i]; 21 | } 22 | return output; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/MaxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1301/ 3 | */ 4 | public class MaxConsecutiveOnes { 5 | public static void main(String[] args) { 6 | System.out.println("Answer is: " + findMaxConsecutiveOnes(new int[]{1, 1, 0, 1, 1, 1}) + " should be 3."); 7 | } 8 | 9 | public static int findMaxConsecutiveOnes(int[] nums) { 10 | int max = -1, counter = 0; 11 | for (int i = 0; i < nums.length; i++) { 12 | int current = nums[i]; 13 | if (current == 1) { 14 | counter++; 15 | } else { 16 | max = Math.max(counter, max); 17 | counter = 0; 18 | } 19 | } 20 | return Math.max(counter, max); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/MaximumSubArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/problems/maximum-subarray/submissions/ 3 | */ 4 | public class MaximumSubArray { 5 | public static void main(String[] args) { 6 | System.out.println(maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4})); 7 | System.out.println(maxSubArray(new int[]{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10})); 8 | } 9 | 10 | // Loop through the current array. 11 | // If the sum of max and the current value is greater then max then set the sum to max. 12 | // Else set the max value to the current value. 13 | // And get the max value of the max and the previous result. 14 | public static int maxSubArray(int[] nums) { 15 | int result = nums[0], max = nums[0]; 16 | for (int i = 1; i <= nums.length - 1; i++) { 17 | int cur = nums[i]; 18 | max = Math.max(max + cur, cur); 19 | result = Math.max(max, result); 20 | } 21 | return result; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/MaximumSubsetSumWithNoAdjesentElement.java: -------------------------------------------------------------------------------- 1 | class MaximumSubsetSumWithNoAdjesentElement { 2 | public static void main(String[] args) { 3 | 4 | } 5 | 6 | public static int maxSubsetSumNoAdjacent(int[] array) { 7 | if (array.length == 0) return 0; 8 | int len = array.length; 9 | int[] op = new int[len]; 10 | int[] sum = new int[len]; 11 | for (int i = 0; i < len; i++) { 12 | int cur = array[i]; 13 | if (i >= 2) { 14 | // Take the value present at the left side sum. 15 | cur += sum[i - 2]; 16 | } 17 | sum[i] = Math.max(cur, sum[i - 1]); 18 | } 19 | return op[array.length - 1]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/MoveZeroes.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 5 | Example: 6 | Input: [0,1,0,3,12] 7 | Output: [1,3,12,0,0] 8 | Note: 9 | 10 | You must do this in-place without making a copy of the array. 11 | Minimize the total number of operations. 12 | */ 13 | public class MoveZeroes { 14 | public static void main(String[] args) { 15 | int[] nums = new int[]{0, 1, 0, 3, 12}; 16 | moveZeroes(nums); 17 | System.out.println("Answer is: \t[" + Arrays.toString(nums) + "] \nShould be: \t[1,3,12,0,0]"); 18 | } 19 | 20 | public static void moveZeroes(int[] nums) { 21 | int position = 0; 22 | for (int i = 0; i < nums.length; i++) { 23 | if (nums[i] != 0) { 24 | nums[position] = nums[i]; 25 | position++; 26 | } 27 | } 28 | for (int i = position; i < nums.length; i++) { 29 | nums[i] = 0; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/PatternSyntaxChecker.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.regex.Pattern; 3 | import java.util.regex.PatternSyntaxException; 4 | 5 | /* 6 | https://www.hackerrank.com/challenges/pattern-syntax-checker/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen 7 | */ 8 | public class PatternSyntaxChecker { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int testCases = Integer.parseInt(in.nextLine()); 12 | String[] patterns = new String[testCases]; 13 | for (int i = 0; i < testCases; i++) { 14 | patterns[i] = in.next(); 15 | } 16 | for (int i = 0; i < testCases; i++) { 17 | try { 18 | Pattern.compile(patterns[i]); 19 | System.out.println("Valid"); 20 | } catch (PatternSyntaxException e) { 21 | System.out.println("Invalid"); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/PlusOne.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | https://leetcode.com/explore/learn/card/array-and-string/201/introduction-to-array/1148/ 5 | 6 | Understand Question. 7 | */ 8 | public class PlusOne { 9 | public static void main(String[] args) { 10 | System.out.println("Answer is: " + Arrays.toString(plusOne(new int[]{3, 6, 1, 0})) + " should be 1."); 11 | } 12 | 13 | public static int[] plusOne(int[] digits) { 14 | int carry = 1, len = digits.length; 15 | for (int i = len - 1; i >= 0; i--) { 16 | int sum = digits[i] + carry; 17 | digits[i] = sum % 10; 18 | carry = sum / 10; 19 | if (carry == 0) break; 20 | } 21 | if (carry == 0) return digits; 22 | int[] temp = new int[len + 1]; 23 | temp[0] = carry; 24 | System.arraycopy(digits, 0, temp, 1, len); 25 | return temp; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/RainSound.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: Apr 25, 2020 3 | */ 4 | 5 | /** 6 | * Questions: https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/rain-41f57695/ 7 | */ 8 | public class RainSound { 9 | public static void main(String[] args) { 10 | FastReader reader = new FastReader("C:\\Users\\bnira\\Downloads\\633dd04c5ede11ea.txt.clean.txt"); 11 | int tests = reader.nextInt(); 12 | for (int i = 0; i < tests; i++) { 13 | int a = reader.nextInt(); 14 | int b = reader.nextInt(); 15 | int c = reader.nextInt(); 16 | int min = -1; 17 | if (a % c == 0) min = a / c; 18 | else if (((a / c) + 1) * c <= b) min = (a / c) + 1; 19 | int max = -1; 20 | if (min != -1) { 21 | if (b % c == 0) max = b / c; 22 | else if ((b / c) > 0) max = b / c; 23 | } 24 | System.out.println(min + " " + max); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/RansomNote.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: May 03, 2020 3 | */ 4 | 5 | /** 6 | * Questions: https://leetcode.com/problems/ransom-note/ 7 | */ 8 | public class RansomNote { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static boolean canConstruct(String ransomNote, String magazine) { 14 | int[] chars = new int[26]; 15 | for (char c : magazine.toCharArray()) { 16 | chars[c - 'a']++; 17 | } 18 | for (char c : ransomNote.toCharArray()) { 19 | if (chars[c - 'a'] > 0) { 20 | chars[c - 'a']--; 21 | } else { 22 | return false; 23 | } 24 | } 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/ShiftingLetters.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 09, 2021 3 | * Ref: https://leetcode.com/problems/shifting-letters/ 4 | */ 5 | public class ShiftingLetters { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public String shiftingLetters(String s, int[] shifts) { 11 | int len = shifts.length; 12 | int[] postsum = new int[len]; 13 | long sum = 0; 14 | for (int i = len - 1; i >= 0; i--) { 15 | sum += shifts[i]; 16 | sum %= 26; 17 | postsum[i] = (int) sum; 18 | } 19 | StringBuilder sb = new StringBuilder(); 20 | for (int i = 0; i < len; i++) { 21 | sb.append(shift(s.charAt(i), postsum[i])); 22 | } 23 | return sb.toString(); 24 | } 25 | 26 | char shift(char c, int shift) { 27 | int idx = (c - 'a') + shift; 28 | idx %= 26; 29 | return (char) ('a' + idx); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/SockMerchant.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /* 5 | Problem: https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup 6 | Sample Input 7 | 9 8 | 10 20 20 10 10 30 50 10 20 9 | Sample Output 10 | 3 11 | */ 12 | public class SockMerchant { 13 | public static void main(String[] args) { 14 | int stocks = 9; 15 | int[] colours = {10, 20, 20, 10, 10, 30, 50, 10, 20}; 16 | System.out.println(sockMerchant(stocks, colours)); 17 | } 18 | 19 | static int sockMerchant(int n, int[] ar) { 20 | int pairs = 0; 21 | Map map = new HashMap<>(); 22 | for (int i = 0; i < n; i++) { 23 | int current = ar[i]; 24 | if (map.containsKey(current)) { 25 | pairs++; 26 | map.remove(current); 27 | } else { 28 | map.put(current, 1); 29 | } 30 | } 31 | return pairs; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/SparseArrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: Apr 19, 2020 3 | */ 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * Questions: https://www.hackerrank.com/challenges/sparse-arrays/problem 10 | */ 11 | public class SparseArrays { 12 | public static void main(String[] args) { 13 | 14 | } 15 | 16 | static int[] matchingStrings(String[] strings, String[] queries) { 17 | Map map = new HashMap<>(); 18 | for (String str : strings) { 19 | map.put(str, map.getOrDefault(str, 0) + 1); 20 | } 21 | int[] op = new int[queries.length]; 22 | int idx = 0; 23 | for (String query : queries) { 24 | op[idx++] = map.getOrDefault(query, 0); 25 | } 26 | return op; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /dataStructures/arraysAndString/StudentAttendanceRecordI.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 17, 2020 3 | * Questions: https://leetcode.com/problems/student-attendance-record-i/ 4 | */ 5 | public class StudentAttendanceRecordI { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static boolean checkRecord(String s) { 11 | int a = 0, l = 0; 12 | for (char c : s.toCharArray()) { 13 | if (c == 'A') a++; 14 | l = c == 'L' ? l + 1 : 0; 15 | if (a > 1 || l > 2) return false; 16 | } 17 | return true; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/AddDigits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 26, 2020 3 | * Questions: https://leetcode.com/problems/add-digits/ 4 | */ 5 | public class AddDigits { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | // https://leetcode.com/articles/add-digits/ 11 | public static int addDigits_optimal(int num) { 12 | if (num == 0) return 0; 13 | if (num % 9 == 0) return 9; 14 | return num % 9; 15 | } 16 | 17 | public static int addDigits(int num) { 18 | while (num > 9) { 19 | int cur = 0; 20 | while (num > 0) { 21 | cur += num % 10; 22 | num /= 10; 23 | } 24 | num = cur; 25 | } 26 | return num; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/AngleBetweenHandsOfAClock.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 14, 2020 3 | * Questions: https://leetcode.com/problems/angle-between-hands-of-a-clock 4 | */ 5 | public class AngleBetweenHandsOfAClock { 6 | public static void main(String[] args) { 7 | System.out.println(angleClock(12, 30) + " should be [165]"); 8 | System.out.println(angleClock(4, 50) + " should be [155]"); 9 | System.out.println(angleClock(12, 0) + " should be [0]"); 10 | System.out.println(angleClock(3, 15) + " should be [7.5]"); 11 | } 12 | 13 | public static double angleClock(int hour, int minutes) { 14 | double h = (hour == 12 ? 0 : hour) * 30 + minutes * 0.5; 15 | double m = minutes * 6; 16 | double dif = Math.abs(h - m); 17 | return Math.min(360 - dif, dif); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/BirthdayParty.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: May 02, 2020 3 | */ 4 | 5 | /** 6 | * Questions: 7 | */ 8 | public class BirthdayParty { 9 | public static void main(String[] args) { 10 | FastReader fr = new FastReader(); 11 | int t = fr.nextInt(); 12 | for (int i = 0; i < t; i++) { 13 | int n = fr.nextInt(), m = fr.nextInt(); 14 | if (m % n == 0) { 15 | System.out.println("Yes"); 16 | } else { 17 | System.out.println("No"); 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/ChampagneTower.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 28, 2020 3 | * Questions: https://leetcode.com/problems/champagne-tower/ 4 | */ 5 | 6 | public class ChampagneTower { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static double champagneTower(int poured, int query_row, int query_glass) { 13 | double[][] A = new double[102][102]; 14 | A[0][0] = poured; 15 | for (int r = 0; r <= query_row; ++r) { 16 | for (int c = 0; c <= r; ++c) { 17 | double q = (A[r][c] - 1.0) / 2.0; 18 | if (q > 0) { 19 | A[r + 1][c] += q; 20 | A[r + 1][c + 1] += q; 21 | } 22 | } 23 | } 24 | 25 | return Math.min(1, A[query_row][query_glass]); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/CountingRhombi.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStreamReader; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Created on: Mar 03, 2021 7 | * Questions: https://codeforces.com/gym/318788/problem/B 8 | */ 9 | 10 | public class CountingRhombi { 11 | 12 | public static void main(String[] args) { 13 | Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); 14 | int w = sc.nextInt(), h = sc.nextInt(); 15 | System.out.println(getCount(0, 0, w, h)); 16 | } 17 | 18 | private static long getCount(int startRow, int startCol, int endRow, int endCol) { 19 | if (startRow + 1 == endRow || startCol + 1 == endCol) return 0; 20 | int midRow = (startRow + endRow) / 2, midCol = (startCol + endCol) / 2; 21 | long subCount = getCount(startRow, startCol, midRow, midCol); 22 | return (subCount * 4) + 1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/DayOfTheWeek.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 30, 2020 3 | * Questions: https://leetcode.com/problems/day-of-the-week/ 4 | */ 5 | public class DayOfTheWeek { 6 | public static void main(String[] args) { 7 | System.out.println(dayOfTheWeek(31, 8, 2019)); 8 | } 9 | 10 | public static String dayOfTheWeek(int day, int month, int year) { 11 | return java.time.LocalDate.of(year, month, day).getDayOfWeek().getDisplayName(java.time.format.TextStyle.FULL, java.util.Locale.ENGLISH); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/DistributeCandiesToPeople.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Aug 17, 2020 5 | * Questions: https://leetcode.com/problems/distribute-candies-to-people/ 6 | */ 7 | public class DistributeCandiesToPeople { 8 | public static void main(String[] args) { 9 | System.out.println(Arrays.toString(distributeCandies(10, 3)) + " = [5,2,3]"); 10 | System.out.println(Arrays.toString(distributeCandies(60, 4)) + " = [15,18,15,12]"); 11 | } 12 | 13 | public static int[] distributeCandies(int candies, int n) { 14 | int[] op = new int[n]; 15 | int round = 0; 16 | while (candies > 0) { 17 | for (int i = 0; i < n; i++) { 18 | int expected = (round * n) + (i + 1); 19 | op[i] += Math.min(candies, expected); 20 | candies -= expected; 21 | if (candies < 0) return op; 22 | } 23 | round++; 24 | } 25 | return op; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/ExcelSheetColumnNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 10, 2020 3 | * Questions: https://leetcode.com/problems/excel-sheet-column-number/ 4 | */ 5 | public class ExcelSheetColumnNumber { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int titleToNumber(String s) { 11 | int result = 0, len = s.length(); 12 | for (char c : s.toCharArray()) { 13 | result += (int) (Math.pow(26, --len) * getNum(c)); 14 | } 15 | return result; 16 | } 17 | 18 | private static int getNum(char c) { 19 | return c - 'A' + 1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/JavaBigDecimal.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | 5 | /* 6 | https://www.hackerrank.com/challenges/java-bigdecimal/problem 7 | Sample Input 8 | 9 9 | -100 10 | 50 11 | 0 12 | 56.6 13 | 90 14 | 0.12 15 | .12 16 | 02.34 17 | 000.000 18 | Sample Output 19 | 90 20 | 56.6 21 | 50 22 | 02.34 23 | 0.12 24 | .12 25 | 0 26 | 000.000 27 | -100 28 | */ 29 | public class JavaBigDecimal { 30 | public static void main(String[] args) { 31 | //Input 32 | Scanner sc = new Scanner(System.in); 33 | int n = sc.nextInt(); 34 | String[] s = new String[n]; 35 | for (int i = 0; i < n; i++) { 36 | s[i] = sc.next(); 37 | } 38 | sc.close(); 39 | 40 | //Write your code here 41 | Arrays.sort(s, (s1, s2) -> { 42 | if (s1 == null || s2 == null) return 0; 43 | return new BigDecimal(s2).compareTo(new BigDecimal(s1)); 44 | }); 45 | 46 | //Output 47 | for (int i = 0; i < n; i++) { 48 | System.out.println(s[i]); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/JavaPrimalityTest.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | /* 5 | https://www.hackerrank.com/challenges/java-primality-test/problem 6 | */ 7 | public class JavaPrimalityTest { 8 | private static Scanner scanner = new Scanner(System.in); 9 | 10 | public static void main(String[] args) { 11 | String n = scanner.nextLine(); 12 | System.out.println(new BigInteger(n).isProbablePrime(1) ? "prime" : "not prime"); 13 | scanner.close(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/JavaStringPalindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /* 4 | https://www.hackerrank.com/challenges/java-string-reverse/problem?h_r=next-challenge&h_v=zen 5 | */ 6 | public class JavaStringPalindrome { 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | String input = sc.next(); 10 | System.out.println(isPalindrome(input) ? "Yes" : "No"); 11 | } 12 | 13 | private static boolean isPalindrome(String input) { 14 | if (input.isEmpty()) return false; 15 | if (input.length() == 1) return true; 16 | int start = 0, end = input.length() - 1; 17 | while (start <= end) { 18 | if (input.charAt(start) != input.charAt(end)) { 19 | return false; 20 | } 21 | start++; 22 | end--; 23 | } 24 | return true; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/PoorPigs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Nov 14, 2020 3 | * Questions: https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3530/ 4 | */ 5 | 6 | public class PoorPigs { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | /* 13 | https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/565/week-2-november-8th-november-14th/3530/discuss/94266/Another-explanation-and-solution 14 | */ 15 | public static int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 16 | int tests = minutesToTest / minutesToDie; 17 | for (int i = 0; i < buckets; i++) { 18 | double val = Math.pow(tests + 1, i); 19 | if (val >= buckets) return i; 20 | } 21 | return buckets; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /dataStructures/basicsAndMath/SignOfTheProductOfAnArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 18, 2021 3 | * Ref: https://leetcode.com/problems/sign-of-the-product-of-an-array/ 4 | */ 5 | 6 | public class SignOfTheProductOfAnArray { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public int arraySign(int[] nums) { 13 | int neg = 0, zero = 0; 14 | for (int num : nums) { 15 | if (num < 0) neg++; 16 | else if (num == 0) zero++; 17 | } 18 | if (zero > 0) return 0; 19 | return neg % 2 == 0 ? 1 : -1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /dataStructures/binarytree/FindLargestValueInEachTreeRow.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | import java.util.List; 4 | import java.util.Queue; 5 | 6 | /** 7 | * Created on: Sep 03, 2020 8 | * Questions: https://leetcode.com/problems/find-largest-value-in-each-tree-row/ 9 | */ 10 | public class FindLargestValueInEachTreeRow { 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static List largestValues(TreeNode root) { 16 | List op = new ArrayList<>(); 17 | if (root == null) return op; 18 | Queue queue = new LinkedList<>(); 19 | queue.add(root); 20 | while (!queue.isEmpty()) { 21 | int size = queue.size(), max = Integer.MIN_VALUE; 22 | for (int i = 0; i < size; i++) { 23 | TreeNode poll = queue.poll(); 24 | max = Math.max(max, poll.val); 25 | if (poll.left != null) queue.add(poll.left); 26 | if (poll.right != null) queue.add(poll.right); 27 | } 28 | op.add(max); 29 | } 30 | return op; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dataStructures/binarytree/FlipEquivalentBinaryTrees.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 11, 2021 3 | * Ref : https://leetcode.com/problems/flip-equivalent-binary-trees/ 4 | */ 5 | public class FlipEquivalentBinaryTrees { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static boolean flipEquiv(TreeNode root1, TreeNode root2) { 11 | if (root1 == null && root2 == null) return true; 12 | if (root1 == null || root2 == null) return false; 13 | if (root1.val != root2.val) return false; 14 | // Same without flip. 15 | if (flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right)) return true; 16 | // With flip 17 | return flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dataStructures/binarytree/IncreasingOrderSearchTree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode: 3 | def __init__(self, val=0, left=None, right=None): 4 | self.val = val 5 | self.left = left 6 | self.right = right 7 | 8 | 9 | class IncreasingOrderSearchTree: 10 | 11 | def increasingBST(self, root: TreeNode) -> TreeNode: 12 | def helper(node): 13 | if node: 14 | yield from helper(node.left) 15 | yield node.val 16 | yield from helper(node.right) 17 | 18 | res = ref = TreeNode(-1) 19 | if root: 20 | for rec in helper(root): 21 | ref.next = TreeNode(rec.val) 22 | ref = ref.right 23 | return res.right 24 | 25 | increasingBST(TreeNode(0, TreeNode(1), TreeNode(2))) -------------------------------------------------------------------------------- /dataStructures/binarytree/MaximumAverageSubtree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 12, 2021 3 | * Questions: https://leetcode.com/problems/maximum-average-subtree/ 4 | */ 5 | 6 | public class MaximumAverageSubtree { 7 | 8 | static double max; 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static double maximumAverageSubtree(TreeNode root) { 15 | max = 0; 16 | helper(root); 17 | return max; 18 | } 19 | 20 | private static int[] helper(TreeNode root) { 21 | if (root == null) return new int[2]; 22 | // 0: sum, 1 : count 23 | int[] left = helper(root.left), right = helper(root.right); 24 | int sum = root.val + left[0] + right[0], count = 1 + left[1] + right[1]; 25 | double cur = (double) (sum) / (count); 26 | max = Math.max(max, cur); 27 | return new int[]{sum, count}; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /dataStructures/binarytree/MaximumProductOfSplittedBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 19, 2021 3 | * Ref : https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/615/week-3-august-15th-august-21st/3903/ 4 | */ 5 | public class MaximumProductOfSplittedBinaryTree { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | static long result; 11 | static int mod = 1_000_000_007; 12 | 13 | public static int maxProduct(TreeNode root) { 14 | result = 0; 15 | long sum = getSum(root); 16 | helper(root, sum); 17 | return (int) (result % mod); 18 | } 19 | 20 | static long helper(TreeNode root, long sum) { 21 | if (root == null) return 0; 22 | long left = helper(root.left, sum); 23 | long right = helper(root.right, sum); 24 | long curSum = left + right + root.val; 25 | result = Math.max(result, (sum - curSum) * curSum); 26 | return curSum; 27 | } 28 | 29 | static long getSum(TreeNode root) { 30 | if (root == null) return 0; 31 | return getSum(root.left) + root.val + getSum(root.right); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dataStructures/binarytree/RangeSumOfBST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 30, 2020 3 | * Questions: https://leetcode.com/problems/range-sum-of-bst/ 4 | */ 5 | public class RangeSumOfBST { 6 | static int sum; 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int rangeSumBST(TreeNode root, int L, int R) { 13 | sum = 0; 14 | helper(root, L, R); 15 | return sum; 16 | } 17 | 18 | private static void helper(TreeNode root, int min, int max) { 19 | if (root == null) return; 20 | if (root.val < min) { 21 | helper(root.right, min, max); 22 | } else if (root.val > max) { 23 | helper(root.left, min, max); 24 | } else { 25 | sum += root.val; 26 | helper(root.right, min, max); 27 | helper(root.left, min, max); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /dataStructures/binarytree/SubtreeOfAnotherTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 13, 2021 3 | * Questions: https://leetcode.com/problems/subtree-of-another-tree/ 4 | */ 5 | 6 | public class SubtreeOfAnotherTree { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static boolean isSubtree(TreeNode s, TreeNode t) { 13 | if (s == null || t == null) return false; 14 | return isSame(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t); 15 | } 16 | 17 | public static boolean isSame(TreeNode a, TreeNode b) { 18 | if (a == null && b == null) return true; 19 | if (a == null || b == null) return false; 20 | if (a.val != b.val) return false; 21 | return isSame(a.left, b.left) && isSame(a.right, b.right); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /dataStructures/binarytree/SumOfLeftLeaves.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 24, 2020 3 | * Questions: https://leetcode.com/problems/sum-of-left-leaves/ 4 | */ 5 | public class SumOfLeftLeaves { 6 | static int op; 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int sumOfLeftLeaves(TreeNode root) { 13 | op = 0; 14 | helper(root, 'M'); 15 | return op; 16 | } 17 | 18 | private static void helper(TreeNode root, char dir) { 19 | if (root == null) return; 20 | if (root.left == null && root.right == null) { 21 | if (dir == 'L') op += root.val; 22 | } else { 23 | helper(root.left, 'L'); 24 | helper(root.right, 'R'); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/binarytree/SumOfRootToLeafBinaryNumbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 08, 2020 3 | * Questions: https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 4 | */ 5 | public class SumOfRootToLeafBinaryNumbers { 6 | static int result = 0; 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int sumRootToLeaf(TreeNode root) { 13 | result = 0; 14 | helper(root, 0); 15 | return result; 16 | } 17 | 18 | private static void helper(TreeNode root, int soFar) { 19 | if (root == null) return; 20 | int cur = (soFar << 1) + root.val; 21 | if (root.left == null && root.right == null) { 22 | result += cur; 23 | } else { 24 | helper(root.left, cur); 25 | helper(root.right, cur); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /dataStructures/binarytree/VerifyPreorderSerializationOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 26, 2021 3 | * Ref: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ 4 | */ 5 | public class VerifyPreorderSerializationOfABinaryTree { 6 | static int p, len; 7 | static boolean outOfIndex; 8 | 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static boolean isValidSerialization(String preorder) { 14 | String[] split = preorder.split(","); 15 | len = split.length; 16 | p = 0; 17 | outOfIndex = false; 18 | boolean exploredAll = dfs(split); 19 | if (outOfIndex) return false; 20 | if (exploredAll && p == len) return true; 21 | return false; 22 | } 23 | 24 | static boolean dfs(String[] split) { 25 | // When the pointer runs out of index, return false. 26 | if (p >= len || outOfIndex) { 27 | outOfIndex = true; 28 | return false; 29 | } 30 | String cur = split[p++]; 31 | if (cur.equals("#")) return true; 32 | return dfs(split) && dfs(split); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /dataStructures/bitwise/ConvertANumberToHexadecimal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 06, 2020 3 | * Questions: https://leetcode.com/problems/convert-a-number-to-hexadecimal/ 4 | */ 5 | 6 | public class ConvertANumberToHexadecimal { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public String toHex(int num) { 13 | if (num == 0) return "0"; 14 | long cur = num; 15 | if (num < 0) cur = this.complement(cur); 16 | String op = ""; 17 | char[] map = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 18 | while (cur > 0) { 19 | int rem = (int) (cur % 16); 20 | cur /= 16; 21 | op = map[rem] + op; 22 | } 23 | return op; 24 | } 25 | 26 | long complement(long n) { 27 | long num = n < 0 ? -n : n; 28 | long nn = (long) Math.pow(16, 8) - 1; 29 | return nn ^ num - 1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /dataStructures/bitwise/FindOdd.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: May 04, 2020 3 | */ 4 | 5 | /** 6 | * Questions: 7 | */ 8 | public class FindOdd { 9 | public static void main(String[] args) { 10 | System.out.println(findOdd(new int[]{12, 12, 14, 90, 14, 14, 14})); 11 | } 12 | 13 | private static int findOdd(int[] nums) { 14 | int op = 0; 15 | for (int num : nums) { 16 | op ^= num; 17 | } 18 | return op; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dataStructures/bitwise/FindTheMissingNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: May 04, 2020 3 | */ 4 | 5 | /** 6 | * Questions: https://www.geeksforgeeks.org/find-the-missing-number/ 7 | */ 8 | public class FindTheMissingNumber { 9 | public static void main(String[] args) { 10 | System.out.println(getMissingNo(new int[]{1, 2, 3, 5})); 11 | System.out.println(getMissingNo(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 10})); 12 | } 13 | 14 | static int getMissingNo(int[] nums) { 15 | int a = 1, b = nums[0], len = nums.length; 16 | for (int i = 1; i < len; i++) { 17 | a ^= i + 1; 18 | b ^= nums[i]; 19 | } 20 | return (a ^ len + 1) ^ b; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /dataStructures/bitwise/MissingNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Aug 15, 2020 3 | * Questions: https://leetcode.com/problems/missing-number/ 4 | */ 5 | public class MissingNumber { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int missingNumber(int[] nums) { 11 | int len = nums.length, xor = 0; 12 | for (int i = 0; i < len; i++) { 13 | xor = xor ^ i ^ nums[i]; 14 | } 15 | return xor ^ len; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /dataStructures/bitwise/Mystery.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: May 05, 2020 3 | */ 4 | 5 | import java.io.BufferedReader; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | 9 | /** 10 | * Questions: https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/mystery-30/ 11 | */ 12 | public class Mystery { 13 | public static void main(String[] args) throws IOException { 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | StringBuffer sb = new StringBuffer(""); 16 | String str; 17 | long i; 18 | while (true) { 19 | str = br.readLine(); 20 | if (str != null) { 21 | if (str.equals("99999999999999999")) { 22 | sb.append("36 \n"); 23 | } else { 24 | i = Long.parseLong(str); 25 | sb.append(Long.bitCount(i)).append("\n"); 26 | } 27 | } else { 28 | System.out.println(sb); 29 | System.exit(0); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dataStructures/bitwise/ReverseBits.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 12, 2020 3 | * Questions: https://leetcode.com/problems/reverse-bits/ 4 | */ 5 | public class ReverseBits { 6 | public static void main(String[] args) { 7 | System.out.println(reverseBits(0b10000000000000000000000000000000)); 8 | } 9 | 10 | public static int reverseBits(int n) { 11 | return Integer.reverse(n); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /dataStructures/bitwise/SingleNumberIII.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * Created on: Jul 23, 2020 6 | * Questions: https://leetcode.com/problems/single-number-iii/ 7 | */ 8 | public class SingleNumberIII { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public int[] singleNumber(int[] nums) { 14 | Set set = new HashSet<>(); 15 | for (int num : nums) { 16 | if (!set.add(num)) { 17 | set.remove(num); 18 | } 19 | } 20 | int[] op = new int[2]; 21 | int i = 0; 22 | for (int num : set) { 23 | op[i++] = num; 24 | } 25 | return op; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/bitwise/SwapTwoNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: May 04, 2020 3 | */ 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Questions: https://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/ 9 | */ 10 | public class SwapTwoNumber { 11 | public static void main(String[] args) { 12 | System.out.println(Arrays.toString(swap(5, 3))); 13 | } 14 | 15 | private static int[] swap(int a, int b) { 16 | return new int[]{(a ^ b) ^ a, (a ^ b) ^ b}; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /dataStructures/coursera/README.md: -------------------------------------------------------------------------------- 1 | # Data Structures 2 | 3 | ## Course assignments 4 | 5 | ### Basic Data Structures (Week 1) 6 | 7 | |No. |Problem |Status| 8 | | --- | --- |--- | 9 | |1 |Check brackets in the code |`` Solved `` 10 | |2 |Compute tree height |`` UnderStand Question `` 11 | |3 |Network packet processing simulation |`` UnSolved `` 12 | |4 |Extending stack interface |`` Implemented `` 13 | |5 |Maximum in Sliding Window |`` UnderStand Question `` 14 | 15 | ### Priority Queues & Disjoint Sets (Week 3) 16 | 17 | |No. |Problem |Status| 18 | | --- | --- |--- | 19 | |1 |Make Heap |`` Attempted `` 20 | |2 |Parallel Processing |`` Attempted `` 21 | |3 |Merging Tables |`` UnSolved `` 22 | -------------------------------------------------------------------------------- /dataStructures/graph/MaximalNetworkRank.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 23, 2021 3 | * Ref: https://leetcode.com/problems/maximal-network-rank/ 4 | */ 5 | 6 | public class MaximalNetworkRank { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int maximalNetworkRank(int n, int[][] roads) { 13 | boolean[][] hasRoad = new boolean[n][n]; 14 | int[] counts = new int[n]; 15 | int max = 0; 16 | for (int[] road : roads) { 17 | hasRoad[road[0]][road[1]] = hasRoad[road[1]][road[0]] = true; 18 | counts[road[0]]++; 19 | counts[road[1]]++; 20 | } 21 | for (int r1 = 0; r1 < n; r1++) { 22 | for (int r2 = 0; r2 < n; r2++) { 23 | if (r1 == r2) continue; 24 | // Lop though each pair of roads and find the counts, and then reduce if any by one if any roard connects to both r1, and r2. 25 | int cur = counts[r1] + counts[r2]; 26 | if (hasRoad[r1][r2]) cur--; 27 | max = Math.max(max, cur); 28 | } 29 | } 30 | return max; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dataStructures/hashtable/CheckArrayFormationThroughConcatenation.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 01, 2021 3 | * Questions: https://leetcode.com/problems/check-array-formation-through-concatenation/ 4 | */ 5 | 6 | public class CheckArrayFormationThroughConcatenation { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public boolean canFormArray(int[] arr, int[][] pieces) { 13 | int p1 = 0, len = arr.length; 14 | while (p1 < len) { 15 | boolean found = false; 16 | for (int[] p : pieces) { 17 | if (p1 >= len || arr[p1] != p[0]) continue; 18 | for (int num : p) { 19 | if (arr[p1++] != num) return false; 20 | found = true; 21 | } 22 | } 23 | if (!found) return false; 24 | } 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/hashtable/KdiffPairsInAnArray.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: Oct 03, 2020 6 | * Questions: https://leetcode.com/problems/k-diff-pairs-in-an-array/submissions/ 7 | */ 8 | public class KdiffPairsInAnArray { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static int findPairs(int[] nums, int k) { 14 | Map map = new HashMap<>(); 15 | for (int num : nums) { 16 | map.put(num, map.getOrDefault(num, 0) + 1); 17 | } 18 | int count = 0; 19 | for (int key : map.keySet()) { 20 | count += k != 0 && map.containsKey(key + k) ? 1 : 0; 21 | if (k == 0 && map.get(key) > 1) count++; 22 | } 23 | return count; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dataStructures/hashtable/MajorityElement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 10, 2021 3 | * Ref: https://leetcode.com/problems/majority-element/ 4 | */ 5 | public class MajorityElement { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public int majorityElement(int[] nums) { 11 | int can = 0, count = 0, len = nums.length; 12 | for (int num : nums) { 13 | if (count == 0) can = num; 14 | count += (num == can) ? 1 : -1; 15 | } 16 | return can; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /dataStructures/hashtable/MaximumNumberOfBalloons.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 13, 2021 3 | * Ref: https://leetcode.com/problems/maximum-number-of-balloons 4 | */ 5 | public class MaximumNumberOfBalloons { 6 | char[] chars = {'b', 'a', 'l', 'o', 'n'}; 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public int maxNumberOfBalloons(String text) { 13 | int[] counts = new int[26]; 14 | for (char c : text.toCharArray()) { 15 | counts[c - 'a']++; 16 | } 17 | int min = Integer.MAX_VALUE; 18 | for (char c : chars) { 19 | int count = counts[c - 'a']; 20 | if (c == 'l' || c == 'o') { 21 | count /= 2; 22 | } 23 | min = Math.min(min, count); 24 | } 25 | return min; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/hashtable/NumberOfBoomerangs.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: May 24, 2021 6 | * Questions: https://leetcode.com/problems/number-of-boomerangs/ 7 | */ 8 | 9 | public class NumberOfBoomerangs { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | public static int numberOfBoomerangs(int[][] points) { 16 | int count = 0, len = points.length; 17 | for (int i = 0; i < len; i++) { 18 | Map map = new HashMap<>(); 19 | for (int j = 0; j < len; j++) { 20 | if (i == j) continue; 21 | double dist = dist(points[i], points[j]); 22 | map.put(dist, map.getOrDefault(dist, 0) + 1); 23 | } 24 | for (int pair : map.values()) { 25 | count += pair * (pair - 1); 26 | } 27 | } 28 | return count; 29 | } 30 | 31 | static double dist(int[] p1, int[] p2) { 32 | double x = p1[0] - p2[0], y = p1[1] - p2[1]; 33 | // return Math.sqrt(x * x + y * y); 34 | return x * x + y * y; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /dataStructures/hashtable/RepeatedDNASequences.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.List; 3 | import java.util.Map; 4 | import java.util.stream.Collectors; 5 | 6 | /** 7 | * Created on: Oct 17, 2020 8 | * Questions: https://leetcode.com/problems/repeated-dna-sequences/ 9 | */ 10 | 11 | public class RepeatedDNASequences { 12 | 13 | public static void main(String[] args) { 14 | 15 | } 16 | 17 | public static List findRepeatedDnaSequences(String s) { 18 | Map map = new HashMap<>(); 19 | for (int i = 0; i < s.length() - 9; i++) { 20 | String cur = s.substring(i, i + 10); 21 | map.put(cur, map.getOrDefault(cur, 0) + 1); 22 | } 23 | return map.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()).collect(Collectors.toList()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dataStructures/hashtable/Roman2Integer.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | class Roman2Integer { 5 | public static void main(String[] args) { 6 | 7 | } 8 | 9 | public int romanToInt(String s) { 10 | Map map = new HashMap<>(); 11 | map.put("I", 1); 12 | map.put("IV", 4); 13 | map.put("V", 5); 14 | map.put("IX", 9); 15 | map.put("X", 10); 16 | map.put("XL", 40); 17 | map.put("L", 50); 18 | map.put("XC", 90); 19 | map.put("C", 100); 20 | map.put("CD", 400); 21 | map.put("D", 500); 22 | map.put("CM", 900); 23 | map.put("M", 1000); 24 | int sum = 0; 25 | while (s.length() > 0) { 26 | if (s.length() > 1 && map.containsKey(s.substring(0, 2))) { 27 | sum += map.get(s.substring(0, 2)); 28 | s = s.substring(2); 29 | } else { 30 | sum += map.get(s.substring(0, 1)); 31 | s = s.substring(1); 32 | } 33 | } 34 | return sum; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /dataStructures/hashtable/SingleNumberII.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: Jun 22, 2020 6 | * Questions: 7 | */ 8 | public class SingleNumberII { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static int singleNumber(int[] nums) { 14 | Map map = new HashMap<>(); 15 | for (int num : nums) { 16 | map.put(num, map.getOrDefault(num, 0) + 1); 17 | } 18 | return map.entrySet().stream().filter(entry -> entry.getValue() == 1).map(entry -> entry.getKey()).findFirst().get(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dataStructures/hashtable/SnapshotArrayImpl.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created on: Oct 11, 2021 5 | * Ref: https://leetcode.com/problems/snapshot-array/ 6 | */ 7 | public class SnapshotArrayImpl { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | static class SnapshotArray { 13 | Map values; 14 | int snapId = 0; 15 | Map> map; 16 | 17 | public SnapshotArray(int length) { 18 | map = new HashMap<>(); 19 | values = new HashMap<>(); 20 | } 21 | 22 | public void set(int index, int val) { 23 | values.put(index, val); 24 | } 25 | 26 | public int snap() { 27 | map.put(snapId, new HashMap<>(values)); 28 | return snapId++; 29 | } 30 | 31 | public int get(int index, int snap_id) { 32 | Map array = map.get(snap_id); 33 | if (array == null) return -1; 34 | return array.getOrDefault(index, 0); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /dataStructures/hashtable/TwoStrings.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | public class TwoStrings { 4 | public static void main(String[] args) { 5 | System.out.println(twoStrings("hello", "world")); 6 | System.out.println(twoStrings("hi", "world")); 7 | } 8 | 9 | static String twoStrings(String s1, String s2) { 10 | if (s1.length() < s2.length()) { 11 | return twoStrings(s2, s1); 12 | } else { 13 | char[] chars = s1.toCharArray(); 14 | HashSet characters = new HashSet<>(); 15 | for (int i = 0; i < s1.length(); i++) { 16 | characters.add(s1.charAt(i)); 17 | } 18 | for (int i = 0; i < s2.length(); i++) { 19 | if (characters.contains(s2.charAt(i))) { 20 | return "YES"; 21 | } 22 | } 23 | return "NO"; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /dataStructures/hashtable/WordPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: Sep 07, 2020 6 | * Questions: https://leetcode.com/problems/word-pattern/ 7 | */ 8 | public class WordPattern { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static boolean wordPattern(String pattern, String str) { 14 | Map map1 = new HashMap<>(); 15 | Map map2 = new HashMap<>(); 16 | String[] split = str.split(" "); 17 | if (pattern.length() != split.length) return false; 18 | for (int i = 0; i < split.length; i++) { 19 | char pat = pattern.charAt(i); 20 | String word = split[i]; 21 | map1.putIfAbsent(pat, i); 22 | map2.putIfAbsent(word, i); 23 | if (!map1.get(pat).equals(map2.get(word))) return false; 24 | } 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/heapAndSort/HIndex.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Aug 11, 2020 5 | * Questions: https://leetcode.com/problems/h-index/ 6 | */ 7 | public class HIndex { 8 | public static void main(String[] args) { 9 | System.out.println(hIndex(new int[]{0}) + " = 0"); 10 | System.out.println(hIndex(new int[]{3, 0, 6, 1, 5}) + " = 3"); 11 | System.out.println(hIndex(new int[]{100}) + " = 1"); 12 | } 13 | 14 | public static int hIndex(int[] citations) { 15 | int result = 0, equalAndGreater = 0; 16 | Arrays.sort(citations); 17 | // Start from end, and keep the count of citations. 18 | // if number of citations soFar is greater than then current value. That could be the answer. 19 | // Keep the max of all possible answers. 20 | for (int i = citations.length - 1; i >= 0; i--) { 21 | equalAndGreater++; 22 | if (citations[i] >= equalAndGreater) result = Math.max(result, equalAndGreater); 23 | } 24 | return result; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /dataStructures/heapAndSort/LargestNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.stream.Collectors; 4 | 5 | /** 6 | * Created on: Sep 25, 2020 7 | * Questions: https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/557/week-4-september-22nd-september-28th/3472/ 8 | */ 9 | public class LargestNumber { 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static String largestNumber(int[] nums) { 15 | List list = Arrays.stream(nums).boxed() 16 | .map(Object::toString) 17 | .sorted((v1, v2) -> compare(v1, v2)) 18 | .collect(Collectors.toList()); 19 | return list.isEmpty() || list.get(0).equals("0") ? "0" : String.join("", list); 20 | } 21 | 22 | private static int compare(String a, String b) { 23 | // System.out.println(a + " and " + b); 24 | String str1 = a + b, str2 = b + a; 25 | return str2.compareTo(str1); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /dataStructures/queue/MinStackImpl.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Created on: Aug 08, 2020 5 | * Questions: https://leetcode.com/problems/min-stack/ 6 | */ 7 | public class MinStackImpl { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | static class MinStack { 13 | int min = Integer.MAX_VALUE; 14 | Stack stack; 15 | 16 | public MinStack() { 17 | stack = new Stack(); 18 | } 19 | 20 | public void push(int x) { 21 | if (stack.isEmpty()) { 22 | min = x; 23 | } else { 24 | min = Math.min(getMin(), x); 25 | } 26 | stack.push(new int[]{x, min}); 27 | } 28 | 29 | public void pop() { 30 | stack.pop(); 31 | } 32 | 33 | public int top() { 34 | return stack.peek()[0]; 35 | } 36 | 37 | public int getMin() { 38 | return stack.peek()[1]; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /dataStructures/queue/TeemoAttacking.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 26, 2020 3 | * Questions: https://leetcode.com/problems/teemo-attacking/ 4 | */ 5 | public class TeemoAttacking { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int findPoisonedDuration(int[] timeSeries, int duration) { 11 | int free = 0, total = 0; 12 | for (int time : timeSeries) { 13 | free = Math.max(free, time); 14 | int cur = time + duration; 15 | total += (time + duration) - free; 16 | free = cur; 17 | } 18 | return total; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dataStructures/stack/BalancedBrackets.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | class BalancedBrackets { 4 | public static void main(String[] args) { 5 | 6 | } 7 | 8 | public static boolean balancedBrackets(String str) { 9 | if (str == null || str.length() == 0) return true; 10 | Stack stack = new Stack<>(); 11 | for (char c : str.toCharArray()) { 12 | if (c == '{' || c == '[' || c == '(') { 13 | stack.add(c); 14 | } else if (stack.isEmpty()) { 15 | return false; 16 | } else { 17 | if (c == '}' && stack.peek() == '{') { 18 | stack.pop(); 19 | } else if (c == ']' && stack.peek() == '[') { 20 | stack.pop(); 21 | } else if (c == ')' && stack.peek() == '(') { 22 | stack.pop(); 23 | } else { 24 | return false; 25 | } 26 | } 27 | } 28 | return stack.isEmpty(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /dataStructures/stack/NumberOfVisiblePeopleInAQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Created on: Oct 01, 2021 5 | * Ref: https://leetcode.com/problems/number-of-visible-people-in-a-queue/ 6 | */ 7 | public class NumberOfVisiblePeopleInAQueue { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int[] canSeePersonsCount(int[] heights) { 13 | int len = heights.length; 14 | int[] count = new int[len]; 15 | Stack stack = new Stack<>(); 16 | for (int i = len - 1; i >= 0; i--) { 17 | int height = heights[i]; 18 | int see = 0; 19 | while (!stack.isEmpty() && stack.peek() < height) { 20 | see++; 21 | stack.pop(); 22 | } 23 | count[i] = see + (stack.isEmpty() ? 0 : 1); 24 | stack.add(height); 25 | } 26 | return count; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /database/TeamScoresInFootballTournament.sql: -------------------------------------------------------------------------------- 1 | select t.team_id, t.team_name, ifnull(sum(num_points), 0) as num_points 2 | from 3 | (select host_team as team_id , 4 | case when host_goals > guest_goals 5 | then 3 6 | when host_goals = guest_goals 7 | then 1 8 | else 0 end as num_points 9 | from matches 10 | union all 11 | select guest_team as team_id , 12 | case when guest_goals > host_goals 13 | then 3 14 | when host_goals = guest_goals 15 | then 1 16 | else 0 end as num_points 17 | from matches) a 18 | right join teams t on a.team_id = t.team_id 19 | group by t.team_id, t.team_name 20 | order by num_points desc, t.team_id -------------------------------------------------------------------------------- /pramp/AbsoluteValueSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | Created on: May 09, 2020 3 | */ 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Questions: https://www.pramp.com/challenge/4E4NW7NjbnHQEx1AxoXE 9 | * Given an array of integers arr, write a function absSort(arr), that sorts the array according to the absolute values of the numbers in arr. 10 | * If two numbers have the same absolute value, sort them according to sign, where the negative numbers come before the positive numbers. 11 | * Examples: 12 | * input: arr = [2, -7, -2, -2, 0] 13 | * output: [0, -2, -2, 2, -7] 14 | */ 15 | public class AbsoluteValueSort { 16 | public static void main(String[] args) { 17 | System.out.println(Arrays.toString(absSort(new int[]{-1, 0, 1, 2}))); 18 | System.out.println(Arrays.toString(absSort(new int[]{1, 0, -1, 2}))); 19 | } 20 | 21 | static int[] absSort(int[] arr) { 22 | return Arrays.stream(arr) 23 | .boxed() 24 | .sorted((v1, v2) -> Math.abs(v1) == Math.abs(v2) ? v1 - v2 : Math.abs(v1) - Math.abs(v2)) 25 | .mapToInt(i -> i) 26 | .toArray(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /pramp/ArrayIndexAndElementEquality.java: -------------------------------------------------------------------------------- 1 | class ArrayIndexAndElementEquality { 2 | static int indexEqualsValueSearch(int[] arr) { 3 | int start = 0, end = arr.length - 1; 4 | int res = -1; 5 | while (start < end) { 6 | int mid = start + (end - start) / 2; 7 | if (arr[mid] < mid) { 8 | // Go right 9 | start = mid + 1; 10 | } else { 11 | // Go left 12 | if (arr[mid] == mid) 13 | res = mid; 14 | end = mid - 1; 15 | } 16 | } 17 | if (start == end && arr[start] == start) return start; 18 | return -1; 19 | } 20 | 21 | public static void main(String[] args) { 22 | System.out.println(indexEqualsValueSearch(new int[]{-8, 0, 2, 5})); 23 | System.out.println(indexEqualsValueSearch(new int[]{-5, 0, 2, 3, 4, 5})); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /pramp/BracketMatch.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | class BracketMatch { 4 | public static void main(String[] args) { 5 | System.out.println(bracketMatch("(()")); 6 | } 7 | 8 | static int bracketMatch(String text) { 9 | int count = 0; 10 | Stack stack = new Stack<>(); 11 | for (char c : text.toCharArray()) { 12 | if (c == '(') { 13 | stack.add(c); 14 | } else if (c == ')') { 15 | if (stack.isEmpty() || stack.peek() != '(') { 16 | count++; 17 | } else { 18 | stack.pop(); 19 | } 20 | } 21 | } 22 | count += stack.size(); 23 | return count; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /pramp/BusiestTimeInTheMall.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 05, 2020 3 | * Questions: 4 | */ 5 | public class BusiestTimeInTheMall { 6 | static int findBusiestPeriod(int[][] data) { 7 | int count = 0, maxVal = 0, maxTime = 0, preTime = 0; 8 | for (int[] val : data) { 9 | int curTime = val[0], curVal = val[1], act = val[2]; 10 | if (curTime != preTime) { 11 | // It is different 12 | // [[1487799425,21,0],[1487799427,22,1],[1487901318,7,0]] 13 | if (count > maxVal) { 14 | maxVal = count; 15 | maxTime = preTime; 16 | } 17 | preTime = curTime; 18 | } 19 | count += act == 1 ? curVal : -1 * curVal; 20 | } 21 | if (count > maxVal) { 22 | maxTime = preTime; 23 | } 24 | return maxTime; 25 | } 26 | 27 | public static void main(String[] args) { 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /pramp/KMessedArraySort.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | class KMessedArraySort { 4 | public static void main(String[] args) { 5 | 6 | } 7 | 8 | static int[] sortKMessedArray(int[] arr, int k) { 9 | int len = arr.length; 10 | // min heap 11 | PriorityQueue priorityQueue = new PriorityQueue<>(); 12 | 13 | // add first k items to the min heap 14 | for (int i = 0; i < k + 1; i++) { 15 | priorityQueue.add(arr[i]); 16 | } 17 | 18 | int index = 0; 19 | for (int i = k + 1; i < len; i++) { 20 | // extract the top element from the min-heap and assign it to the next available array index 21 | arr[index++] = priorityQueue.poll(); 22 | // push the next array element into the min-heap 23 | priorityQueue.add(arr[i]); 24 | } 25 | 26 | // extract all remaining elements from the min-heap and assign them to the next available array index 27 | while (!priorityQueue.isEmpty()) { 28 | arr[index++] = priorityQueue.poll(); 29 | } 30 | return arr; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /pramp/PairsWithGivenDifference.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class PairWithGivenDifference { 4 | 5 | static int[][] findPairsWithGivenDifference(int[] arr, int k) { 6 | Set set = new HashSet<>(); 7 | List output = new ArrayList<>(); 8 | for (int i = 0; i < arr.length; i++) { 9 | set.add(arr[i]); 10 | } 11 | for (int i = 0; i < arr.length; i++) { 12 | int dif = k + arr[i]; 13 | if (set.contains(dif)) { 14 | output.add(new int[]{dif, arr[i]}); 15 | } 16 | } 17 | int[][] conv = new int[output.size()][2]; 18 | for (int i = 0; i < output.size(); i++) { 19 | conv[i][0] = output.get(i)[0]; 20 | conv[i][1] = output.get(i)[1]; 21 | } 22 | return conv; 23 | } 24 | 25 | public static void main(String[] args) { 26 | System.out.println(Arrays.deepToString(findPairsWithGivenDifference(new int[]{0, -1, -2, 2, 1}, 1))); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /pramp/ValidateIPAddress.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jun 28, 2020 3 | * Questions: Validate IP Address 4 | * https://www.pramp.com/challenge/Q5G1jZ1OWdtZ3GbAGpNE 5 | */ 6 | public class ValidateIPAddress { 7 | static boolean validateIP(String ip) { 8 | String[] strs = ip.split("\\.", -1); 9 | if (strs.length != 4) return false; 10 | for (String str : strs) { 11 | if (!isValid(str)) { 12 | return false; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | private static boolean isValid(String str) { 19 | try { 20 | int n = Integer.parseInt(str); 21 | if (n == 0) return str.length() == 1; 22 | return n > 0 && n < 256; 23 | } catch (Exception e) { 24 | return false; 25 | } 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(validateIP("192.168.0.1")); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /topAmazonQuestions/AmazonFulfillmentBuilder.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Jan 21, 2021 5 | * Questions: 6 | * It's similar to https://leetcode.com/problems/minimum-cost-to-connect-sticks/ 7 | */ 8 | 9 | public class AmazonFulfillmentBuilder { 10 | 11 | public static void main(String[] args) { 12 | System.out.println(getTotalTime(new int[]{})); 13 | } 14 | 15 | private static int getTotalTime(int[] nums) { 16 | PriorityQueue pq = new PriorityQueue<>(); 17 | for (int num : nums) { 18 | pq.add(num); 19 | } 20 | int sum = 0; 21 | while (pq.size() >= 2) { 22 | int v1 = pq.poll(), v2 = pq.poll(); 23 | sum += v1 + v2; 24 | pq.add(v1 + v2); 25 | } 26 | return sum; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /topAmazonQuestions/ConnectRopes.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Jan 19, 2021 5 | * Questions: https://aonecode.com/amazon-online-assessment-oa2-connect-ropes 6 | */ 7 | 8 | public class ConnectRopes { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static int connectRopes(int[] ropes) { 15 | PriorityQueue pq = new PriorityQueue<>(); 16 | for (int rope : ropes) pq.add(rope); 17 | int cost = 0; 18 | while (pq.size() >= 2) { 19 | int a = pq.poll(), b = pq.poll(); 20 | cost += a + b; 21 | pq.add(a + b); 22 | } 23 | return cost; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /topAmazonQuestions/KeyPressedTimes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 15, 2021 3 | * Questions: https://aonecode.com/aplusplus/interviewctrl/getInterview/8960002076 4 | */ 5 | 6 | public class KeyPressedTimes { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(keyPressedTimes(new int[][]{{0, 1}, {3, 4}, {0, 8}, {2, 11}})); 10 | } 11 | 12 | private static char keyPressedTimes(int[][] times) { 13 | int key = -1, max = 0, pre = 0; 14 | for (int[] time : times) { 15 | int cur = time[1]; 16 | if (cur - pre > max || (cur - pre == max && time[0] < key)) { 17 | key = time[0]; 18 | max = cur - pre; 19 | } 20 | pre = cur; 21 | } 22 | return (char) ('a' + key); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /topAmazonQuestions/MaximizeProfit.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 15, 2021 3 | * Questions: https://aonecode.com/aplusplus/interviewctrl/getInterview/87934981990 4 | */ 5 | 6 | public class MaximizeProfit { 7 | 8 | public static void main(String[] args) { 9 | // System.out.println(maxProfit(2, new int[]{3, 4}, 6) + " = 15"); 10 | System.out.println(maxProfit(5, new int[]{3, 5, 7, 10, 6}, 20) + " = 107"); 11 | } 12 | 13 | private static int maxProfit(int n, int[] arr, int k) { 14 | int[] counts = new int[100001]; 15 | int max = 0; 16 | for (int num : arr) { 17 | counts[num]++; 18 | max = Math.max(num, max); 19 | } 20 | int item = 0, profit = 0; 21 | for (int i = max; i >= 0 && item < k; i--) { 22 | int curCount = counts[i]; 23 | if (curCount == 0) continue; 24 | int taken = Math.min(k - item, curCount); 25 | profit += i * taken; 26 | item += taken; 27 | counts[i] -= taken; 28 | if (i > 0) counts[i - 1] += taken; 29 | } 30 | return profit; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /topAmazonQuestions/MultiprocessorSystem.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Jan 15, 2021 5 | * Questions: https://algo.monster/problems/multiprocessor_system 6 | */ 7 | 8 | public class MultiprocessorSystem { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static int multiprocessorSystem(int[] ability, int num, int processes) { 15 | PriorityQueue pq = new PriorityQueue<>((p1, p2) -> Integer.compare(p2, p1)); 16 | for (int cap : ability) { 17 | pq.add(cap); 18 | } 19 | int time = 0, processed = 0; 20 | while (!pq.isEmpty() && processed < processes) { 21 | int poll = pq.poll(); 22 | processed += poll; 23 | time++; 24 | if (poll / 2 > 0) pq.add(poll / 2); 25 | } 26 | return time; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /topAmazonQuestions/RoverControl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 12, 2021 3 | * Questions: https://leetcode.com/discuss/interview-question/985703/Amazon-or-OA-or-Rover-Control 4 | */ 5 | 6 | public class RoverControl { 7 | 8 | static int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 9 | 10 | public static void main(String[] args) { 11 | System.out.println(roverMove(4, new String[]{"RIGHT", "UP", "DOWN", "LEFT", "DOWN", "DOWN"})); 12 | } 13 | 14 | private static int roverMove(int n, String[] directions) { 15 | int row = 0, col = 0; 16 | for (String dir : directions) { 17 | int idx = getDirIdx(dir); 18 | int nr = row + dirs[idx][0], nc = col + dirs[idx][1]; 19 | if (nr >= 0 && nr < n && nc >= 0 && nc < n) { 20 | row = nr; 21 | col = nc; 22 | } 23 | } 24 | return (row * n) + col; 25 | } 26 | 27 | private static int getDirIdx(String dir) { 28 | if (dir.equals("UP")) return 0; 29 | if (dir.equals("DOWN")) return 1; 30 | if (dir.equals("LEFT")) return 2; 31 | return 3; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /topAmazonQuestions/ScheduleTasks.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Jan 14, 2021 5 | * Questions: https://aonecode.com/aplusplus/interviewctrl/getInterview/896000198 6 | */ 7 | 8 | public class ScheduleTasks { 9 | 10 | public static void main(String[] args) { 11 | System.out.println(getTaskResolveTime(5, new int[]{4, 2, 8, 3, 5}, 19)); 12 | System.out.println(getTaskResolveTime(4, new int[]{4, 8, 3, 5}, 25)); 13 | } 14 | 15 | private static int getTaskResolveTime(int n, int[] powers, int tasks) { 16 | PriorityQueue pq = new PriorityQueue<>((p1, p2) -> Integer.compare(p2, p1)); 17 | for (int power : powers) if (power > 0) pq.add(power); 18 | int time = 0; 19 | while (tasks > 0 && !pq.isEmpty()) { 20 | int power = pq.poll(); 21 | time++; 22 | tasks -= power; 23 | if (power / 2 > 0) pq.add(power / 2); 24 | } 25 | return tasks <= 0 ? time : -1; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /topAmazonQuestions/SlowestKey.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jan 13, 2021 3 | * Questions: https://leetcode.com/problems/slowest-key/ 4 | */ 5 | 6 | public class SlowestKey { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static char slowestKey(int[] times, String keys) { 13 | int pre = times[0], max = pre; 14 | char maxChar = keys.charAt(0); 15 | for (int i = 1; i < times.length; i++) { 16 | int cur = times[i]; 17 | if (cur - pre > max || (cur - pre == max && keys.charAt(i) > maxChar)) { 18 | maxChar = keys.charAt(i); 19 | max = cur - pre; 20 | } 21 | pre = cur; 22 | } 23 | return maxChar; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /topAmazonQuestions/TwoSumUniquePairs.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * Created on: Jan 13, 2021 6 | * Questions: https://leetcode.com/discuss/interview-question/372434 7 | */ 8 | 9 | public class TwoSumUniquePairs { 10 | 11 | public static void main(String[] args) { 12 | System.out.println(uniquePairs(new int[]{1, 1, 2, 45, 46, 46}, 47)); 13 | System.out.println(uniquePairs(new int[]{1, 1}, 2)); 14 | System.out.println(uniquePairs(new int[]{1, 5, 1, 5}, 6)); 15 | } 16 | 17 | private static int uniquePairs(int[] nums, int target) { 18 | Set set = new HashSet<>(), paired = new HashSet<>(); 19 | int count = 0; 20 | for (int num : nums) { 21 | int rem = target - num; 22 | if (set.contains(rem) && !paired.contains(num)) { 23 | set.remove(rem); 24 | paired.add(num); 25 | paired.add(rem); 26 | count++; 27 | } else { 28 | set.add(num); 29 | } 30 | } 31 | return count; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /topFacebookQuestions/BalanceBrackets.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Created on: Sep 09, 2020 5 | * Questions: https://www.facebookrecruiting.com/portal/coding_practice_question/?problem_id=211548593612944 6 | */ 7 | public class BalanceBrackets { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | static boolean isBalanced(String s) { 13 | Stack stack = new Stack<>(); 14 | for (char cur : s.toCharArray()) { 15 | if (cur == '(' || cur == '{' || cur == '[') stack.add(cur); 16 | else if (stack.isEmpty()) return false; 17 | else if (cur == ')' && stack.pop() != '(') return false; 18 | else if (cur == ']' && stack.pop() != '[') return false; 19 | else if (cur == '}' && stack.pop() != '{') return false; 20 | } 21 | return stack.isEmpty(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /topFacebookQuestions/ChangeInAForeignCurrency.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 08, 2020 3 | * Questions: 4 | */ 5 | public class ChangeInAForeignCurrency { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | private static boolean helper(int target, int[] denominations, Boolean[] dp) { 11 | if (target < 0) return false; 12 | if (target == 0) return true; 13 | if (dp[target] != null) return dp[target]; 14 | for (int cur : denominations) { 15 | if (helper(target - cur, denominations, dp)) { 16 | return dp[target] = true; 17 | } 18 | } 19 | return dp[target] = false; 20 | } 21 | 22 | 23 | static boolean canGetExactChange(int targetMoney, int[] denominations) { 24 | Boolean[] dp = new Boolean[targetMoney + 1]; 25 | return helper(targetMoney, denominations, dp); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /topFacebookQuestions/ContinuousSubarraySum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: Jul 23, 2020 6 | * Questions: https://leetcode.com/problems/continuous-subarray-sum/ 7 | */ 8 | public class ContinuousSubarraySum { 9 | public static void main(String[] args) { 10 | System.out.println(checkSubarraySum(new int[]{23, 2, 4, 6, 7}, 6)); 11 | System.out.println(checkSubarraySum(new int[]{0, 0}, 0)); 12 | } 13 | 14 | public static boolean checkSubarraySum(int[] nums, int k) { 15 | int sum = 0; 16 | Map map = new HashMap<>(); 17 | map.put(0, -1); 18 | 19 | for (int i = 0; i < nums.length; i++) { 20 | sum += nums[i]; 21 | if (k != 0) sum %= k; 22 | if (i - map.getOrDefault(sum, i) > 1) { 23 | return true; 24 | } 25 | map.putIfAbsent(sum, i); 26 | } 27 | return false; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /topFacebookQuestions/CountingTriangles.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created on: Sep 09, 2020 5 | * Questions: https://www.facebookrecruiting.com/portal/coding_practice_question/?problem_id=720422605157879 6 | */ 7 | public class CountingTriangles { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | int countDistinctTriangles(ArrayList arr) { 13 | Set> sides = new HashSet<>(); 14 | for (Sides cur : arr) { 15 | List curSides = new ArrayList<>(Arrays.asList(cur.a, cur.b, cur.c)); 16 | Collections.sort(curSides); 17 | sides.add(curSides); 18 | } 19 | return sides.size(); 20 | } 21 | 22 | static class Sides { 23 | int a; 24 | int b; 25 | int c; 26 | 27 | Sides(int a, int b, int c) { 28 | this.a = a; 29 | this.b = b; 30 | this.c = c; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /topFacebookQuestions/EncryptedWords.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Sep 08, 2020 3 | * Questions: https://www.facebookrecruiting.com/portal/coding_practice_question/?problem_id=223547538732703 4 | */ 5 | public class EncryptedWords { 6 | public static void main(String[] args) { 7 | System.out.println(findEncryptedWord("abc") + " = bac"); 8 | System.out.println(findEncryptedWord("abcd") + " = bacd"); 9 | System.out.println(findEncryptedWord("abcxcba") + " = xbacbca"); 10 | System.out.println(findEncryptedWord("facebook") + " = eafcobok"); 11 | } 12 | 13 | static String findEncryptedWord(String s) { 14 | if (s.length() < 2) return s; 15 | int mid = (s.length() - 1) / 2; 16 | return s.charAt(mid) + 17 | findEncryptedWord(s.substring(0, mid)) + 18 | findEncryptedWord(s.substring(mid + 1)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /topFacebookQuestions/KthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Jul 19, 2020 5 | * Questions: https://leetcode.com/problems/kth-largest-element-in-an-array/ 6 | */ 7 | public class KthLargestElementInAnArray { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int findKthLargest(int[] nums, int k) { 13 | PriorityQueue pq = new PriorityQueue<>((v1, v2) -> v1 - v2); 14 | for (int val : nums) { 15 | pq.add(val); 16 | if (pq.size() > k) { 17 | pq.poll(); 18 | } 19 | } 20 | return pq.peek(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /topFacebookQuestions/MissingElementInSortedArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 26, 2020 3 | * Questions: 4 | */ 5 | public class MissingElementInSortedArray { 6 | public static void main(String[] args) { 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /topFacebookQuestions/ProductOfArrayExceptSelf.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 17, 2020 3 | * Questions: 4 | */ 5 | public class ProductOfArrayExceptSelf { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static int[] productExceptSelf(int[] nums) { 11 | int len = nums.length; 12 | if (len == 0) return nums; 13 | int[] left = new int[len], res = new int[len]; 14 | left[0] = 1; 15 | for (int i = 1; i < len; i++) { 16 | left[i] = left[i - 1] * nums[i - 1]; 17 | } 18 | int prod = 1; 19 | for (int i = len - 1; i >= 0; i--) { 20 | res[i] = left[i] * prod; 21 | prod *= nums[i]; 22 | } 23 | return res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /topFacebookQuestions/RandomPickIndex.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created on: Jul 26, 2020 5 | * Questions: https://leetcode.com/problems/random-pick-index/ 6 | */ 7 | public class RandomPickIndex { 8 | public static void main(String[] args) { 9 | int[] nums = {1, 2, 2, 3, 5, 6, 5, 7, 9}; 10 | Solution sol = new Solution(nums); 11 | System.out.println(sol.pick(nums[sol.random.nextInt(nums.length)])); 12 | } 13 | 14 | static class Solution { 15 | Map> map; 16 | Random random; 17 | 18 | public Solution(int[] nums) { 19 | map = new HashMap<>(); 20 | random = new Random(); 21 | for (int i = 0; i < nums.length; i++) { 22 | map.computeIfAbsent(nums[i], val -> new ArrayList<>()).add(i); 23 | } 24 | } 25 | 26 | public int pick(int target) { 27 | List idx = map.get(target); 28 | return idx.get(random.nextInt(idx.size())); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /topFacebookQuestions/SeatingArrangements.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.LinkedList; 3 | 4 | /** 5 | * Created on: Sep 07, 2020 6 | * Questions: https://www.facebookrecruiting.com/portal/coding_practice_question/?problem_id=2444722699191194 7 | */ 8 | public class SeatingArrangements { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | static int minOverallAwkwardness(int[] arr) { 14 | Arrays.sort(arr); 15 | LinkedList seating = new LinkedList<>(); 16 | int max = 0, len = arr.length; 17 | for (int i = 0; i < len; i++) { 18 | int cur = arr[i++]; 19 | if (!seating.isEmpty()) { 20 | max = Math.max(max, cur - seating.getFirst()); 21 | } 22 | seating.addFirst(cur); 23 | if (i < len) { 24 | cur = arr[i]; 25 | max = Math.max(max, cur - seating.getLast()); 26 | seating.addLast(cur); 27 | } 28 | } 29 | max = Math.max(max, Math.abs(seating.getFirst() - seating.getLast())); 30 | return max; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /topFacebookQuestions/SlowSums.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | /** 4 | * Created on: Sep 07, 2020 5 | * Questions: https://www.facebookrecruiting.com/portal/coding_practice_question/?problem_id=836241573518034 6 | */ 7 | public class SlowSums { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | static int getTotalTime(int[] arr) { 13 | PriorityQueue pq = new PriorityQueue<>((v1, v2) -> v2 - v1); 14 | for (int val : arr) pq.add(val); 15 | int max = pq.poll(), result = 0; 16 | while (!pq.isEmpty()) { 17 | max += pq.poll(); 18 | result += max; 19 | pq.add(max); 20 | max = pq.poll(); 21 | } 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /topFacebookQuestions/SubarraySumEqualsK.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | /** 5 | * Created on: Jul 17, 2020 6 | * Questions: 7 | */ 8 | public class SubarraySumEqualsK { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static int subarraySum(int[] nums, int k) { 14 | Map map = new HashMap<>(); 15 | map.put(0, 1); 16 | int sum = 0, op = 0; 17 | for (int num : nums) { 18 | sum += num; 19 | if (map.containsKey(sum - k)) { 20 | op += map.get(sum - k); 21 | } 22 | map.put(sum, map.getOrDefault(sum, 0) + 1); 23 | } 24 | return op; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /topFacebookQuestions/ValidNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Jul 23, 2020 3 | * Questions: https://leetcode.com/problems/valid-number/ 4 | */ 5 | public class ValidNumber { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public boolean isNumber(String s) { 11 | StringBuilder sb = new StringBuilder(); 12 | for (char c : s.trim().toCharArray()) { 13 | if (Character.isDigit(c) || c == '+' || c == '-' || c == 'e' || c == '.') { 14 | sb.append(c); 15 | } else { 16 | if (sb.length() > 0 && c == ' ') return false; 17 | else return false; 18 | } 19 | } 20 | try { 21 | Double.parseDouble(sb.toString()); 22 | return true; 23 | } catch (Exception e) { 24 | return false; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /topFacebookQuestions/ValidateStackSequences.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | /** 4 | * Created on: Jul 21, 2020 5 | * Questions: https://leetcode.com/problems/validate-stack-sequences/ 6 | */ 7 | public class ValidateStackSequences { 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public boolean validateStackSequences(int[] pushed, int[] popped) { 13 | int l1 = pushed.length, l2 = popped.length; 14 | if (l1 != l2) return false; 15 | int p2 = 0; 16 | 17 | Stack stack = new Stack<>(); 18 | 19 | for (int num : pushed) { 20 | while (!stack.isEmpty() && popped[p2] == stack.peek()) { 21 | stack.pop(); 22 | p2++; 23 | } 24 | stack.add(num); 25 | } 26 | 27 | while (!stack.isEmpty() && stack.peek() == popped[p2]) { 28 | stack.pop(); 29 | p2++; 30 | } 31 | return stack.isEmpty() && p2 == l2; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /topMicrosoftQuestions/DayOfWeekThatIsKDaysLater.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 31, 2020 3 | * Questions: https://leetcode.com/discuss/interview-question/703151/ 4 | */ 5 | 6 | public class DayOfWeekThatIsKDaysLater { 7 | 8 | static String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; 9 | 10 | public static void main(String[] args) { 11 | System.out.println(getDayOfWeekThatIsKDaysLater("Wed", 2)); 12 | System.out.println(getDayOfWeekThatIsKDaysLater("Sat", 23)); 13 | } 14 | 15 | private static String getDayOfWeekThatIsKDaysLater(String day, int k) { 16 | int cur = 0; 17 | for (int i = 0; i < 7; i++) { 18 | if (days[i] == day) { 19 | cur = i; 20 | break; 21 | } 22 | } 23 | k %= 7; 24 | int nextDay = (cur + k) % 7; 25 | return days[nextDay]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /topMicrosoftQuestions/FindNUniqueIntegersSumUpToZero.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.LinkedList; 3 | 4 | /** 5 | * Created on: Oct 30, 2020 6 | * Questions: https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ 7 | */ 8 | 9 | public class FindNUniqueIntegersSumUpToZero { 10 | 11 | public static void main(String[] args) { 12 | System.out.println(Arrays.toString(sumZero(5))); 13 | } 14 | 15 | public static int[] sumZero(int n) { 16 | LinkedList list = new LinkedList<>(); 17 | int len = n; 18 | int[] result = new int[n]; 19 | if (n % 2 == 1) { 20 | list.add(0); 21 | n--; 22 | } 23 | int num = 1; 24 | while (n > 0) { 25 | list.addFirst(-1 * num); 26 | list.addLast(num); 27 | num++; 28 | n -= 2; 29 | } 30 | for (int i = 0; i < len; i++) { 31 | result[i] = list.get(i); 32 | } 33 | return result; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /topMicrosoftQuestions/MaxInsertsToObtainStringWithout3ConsecutiveA.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 31, 2020 3 | * Questions: https://leetcode.com/discuss/interview-question/398056/ 4 | */ 5 | 6 | public class MaxInsertsToObtainStringWithout3ConsecutiveA { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(maxInserts("dog")); 10 | } 11 | 12 | private static int maxInserts(String s) { 13 | int len = s.length(), inserts = 0, count = 0; 14 | for (int i = 0; i < len; i++) { 15 | if (s.charAt(i) == 'a') { 16 | count++; 17 | } else { 18 | inserts += 2 - count; 19 | count = 0; 20 | } 21 | if (count > 3) return -1; 22 | } 23 | // Insert towards the end. 24 | if (s.charAt(len - 1) != 'a') inserts += 2; 25 | else inserts += 2 - count; 26 | return inserts; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /topMicrosoftQuestions/MaxNetworkRank.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 30, 2020 3 | * Questions: https://leetcode.com/discuss/interview-question/364760/ 4 | * similar Question : https://leetcode.com/problems/maximal-network-rank/ 5 | */ 6 | 7 | public class MaxNetworkRank { 8 | 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | public static int maximalNetworkRank(int n, int[][] roads) { 14 | int[] count = new int[n]; 15 | boolean[][] hasRoad = new boolean[n][n]; 16 | for (int[] road : roads) { 17 | count[road[0]]++; 18 | count[road[1]]++; 19 | hasRoad[road[0]][road[1]] = hasRoad[road[1]][road[0]] = true; 20 | } 21 | int max = 0; 22 | for (int i = 0; i < n; i++) { 23 | for (int j = 0; j < n; j++) { 24 | if (i == j) continue; 25 | int val = count[i] + count[j] - (hasRoad[i][j] ? 1 : 0); 26 | max = Math.max(max, val); 27 | } 28 | } 29 | return max; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /topMicrosoftQuestions/MinDeletionsToObtainStringInRightFormat.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 31, 2020 3 | * Questions: https://leetcode.com/discuss/interview-question/786237/ 4 | */ 5 | 6 | public class MinDeletionsToObtainStringInRightFormat { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(minDeletion("BAAABAB") + " should be [2]"); 10 | System.out.println(minDeletion("BBABAA") + " should be [3]"); 11 | System.out.println(minDeletion("AABBBB") + " should be [0]"); 12 | } 13 | 14 | private static int minDeletion(String s) { 15 | int a = 0, len = s.length(); 16 | for (char c : s.toCharArray()) { 17 | if (c == 'A') a++; 18 | } 19 | // Initialize try deleting a's or b's, Take min as we need minimum value. 20 | int deletions = Math.min(a, len - a), b = 0; 21 | for (char c : s.toCharArray()) { 22 | if (c == 'B') { 23 | deletions = Math.min(deletions, a + b); 24 | b++; 25 | } else { 26 | a--; 27 | } 28 | } 29 | return deletions; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /topMicrosoftQuestions/MinStepsToMakePilesEqualHeight.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * Created on: Oct 31, 2020 5 | * Questions: https://leetcode.com/discuss/interview-question/364618/ 6 | */ 7 | 8 | public class MinStepsToMakePilesEqualHeight { 9 | 10 | public static void main(String[] args) { 11 | System.out.println(minSteps(new int[]{5, 2, 1})); 12 | } 13 | 14 | private static int minSteps(int[] nums) { 15 | if (nums == null || nums.length == 0) return 0; 16 | Arrays.sort(nums); 17 | int count = 0; 18 | for (int i = 0; i < nums.length - 1; i++) { 19 | if (nums[i] != nums[i + 1]) count++; 20 | } 21 | return count; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /topMicrosoftQuestions/ParticleVelocity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Oct 31, 2020 3 | * Questions: https://leetcode.com/discuss/interview-question/428272/ 4 | */ 5 | 6 | public class ParticleVelocity { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int numberOfArithmeticSlices(int[] a) { 13 | int len = a.length; 14 | int[] dp = new int[len]; 15 | if (len < 3) return 0; 16 | int count = 0; 17 | for (int i = 2; i < len; i++) { 18 | if (a[i] - a[i - 1] == a[i - 1] - a[i - 2]) { 19 | dp[i] = 1 + dp[i - 1]; 20 | count += dp[i]; 21 | if (count > 1_000_000_000) return -1; 22 | } 23 | } 24 | return count; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /topUberQuestions/IncreasingSequence.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created on: Nov 07, 2020 3 | * Questions: 4 | */ 5 | 6 | public class IncreasingSequence { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | static boolean almostIncreasingSequence(int[] nums) { 13 | int rem = 0; 14 | for (int i = 0; i < nums.length; i++) { 15 | if (i > 0 && nums[i] <= nums[i - 1]) { 16 | rem++; 17 | if (rem > 1) return false; 18 | // If by removing the current element, or pre element is possible 19 | if (i + 1 < nums.length && nums[i - 1] >= nums[i + 1] && 20 | i > 1 && nums[i - 2] >= nums[i]) return false; 21 | } 22 | } 23 | System.out.println(rem); 24 | return rem <= 1; 25 | } 26 | } 27 | --------------------------------------------------------------------------------