├── .github
└── FUNDING.yml
├── .gitignore
├── AlgoDS.iml
├── Licence.md
├── README-CN.md
├── README-RU.md
├── README.md
└── src
├── FastReader.java
├── adventofcode
├── Captcha_1.java
├── CheckSUm_2.java
├── DigitalPlumber_12.java
├── DiskDefragmentation_14.java
├── DuelingGenerators_15.java
├── Duet_18.java
├── FractalArt_21.java
├── HexEd_11.java
├── Interrupt_5.java
├── KnotHash_10.java
├── MemoryReallocation_6.java
├── PacketScanners_13.java
├── Paraphrase_4.java
├── PermutationPromanade_16.java
├── RecursiveCircus.java
├── Registrars_7.java
├── SeriesOfTubes_19.java
├── Spinlock_17.java
├── SpiralMemory_3.java
├── SporificaVirus_22.java
└── StreamProcessing_9.java
├── algo
├── 1todo
├── ReservoirSampling.java
├── Solution.java
├── TreeTraversals.java
├── UnionFind.java
├── dp
│ ├── DPIntroduction.md
│ ├── FibonacciNumber.java
│ ├── Knapsack01.java
│ ├── MaxWeightTransformation.java
│ ├── MinimizeArraySize.java
│ ├── MinimumSquareSum.java
│ └── SubsetSum.java
├── graph
│ ├── AStar.java
│ ├── BFS.java
│ ├── BFSHelper.java
│ ├── BellmanFord.java
│ ├── BidirectionalBFS.java
│ ├── BridgeUndirectedGraph.java
│ ├── CycleDetection.java
│ ├── DFS.java
│ ├── Dijsktra.java
│ ├── GraphWithTimeStamp.java
│ ├── IsBipartite.java
│ ├── IsConnected.java
│ ├── KruskalsMST.java
│ ├── PrimsMST.java
│ └── TopologicalSorting.java
├── numerals
│ ├── BabylonianSquareRoot.java
│ ├── Combination.java
│ ├── FermatPrimality.java
│ ├── GCD.java
│ └── SieveofEratosthenes.java
├── recursion
│ ├── Ackermann.java
│ ├── AckermannNonRecursive.java
│ ├── Factorial.java
│ └── TowerOfHanoi.java
├── sortingandsearching
│ ├── BinarySearch.java
│ ├── BubbleSort.java
│ ├── CountingSort.java
│ ├── HeapSort.java
│ ├── InsertionSort.java
│ ├── LinearSearch.java
│ ├── MergeSort.java
│ ├── QuickSort.java
│ ├── SelectionSort.java
│ └── TestSorting.java
└── string
│ ├── RabinKarpSubsequenceSearch.java
│ ├── ReplaceString.java
│ └── Trie.java
├── codeforces
├── BachgoldProblem.java
├── Coupon.java
├── LRU.java
├── ParallelogramisBack.java
├── SubsetGenerator.java
├── ValidateCard.java
└── Voting.java
├── codejam2018
├── Practice1.java
├── Practice2.java
├── Practice3.java
└── Practice4.java
├── contests
├── Base7.java
├── COnArray.java
├── KeyboardRow.java
├── Maze2.java
├── NextGreaterElementI.java
├── NextGreaterElementII.java
├── RelativeRanks.java
├── ReversePairs.java
├── ReverseString.java
├── Solution2.java
├── ZumaGame.java
├── contest25
│ ├── BoundaryofBinaryTree.java
│ └── ComplexNumberMultiplication.java
├── contest27
│ ├── BrickWall.java
│ ├── NextGreaterElement3.java
│ └── ReverseWordsinString3.java
├── contest30
│ ├── PermutationinString.java
│ ├── ReshapetheMatrix.java
│ └── SubarraySumEqualsK.java
├── contest34
│ └── ArrayNesting.java
├── contest36
│ ├── AddBoldTaginString.java
│ ├── MergeTwoBinaryTrees.java
│ ├── StringIterator.java
│ └── ValidTriangleNumber.java
├── contest37
│ └── MaxDistanceinArray.java
└── facebookHC
│ ├── FightingtheZombie.java
│ ├── LazyLoading.java
│ ├── ManicMoving.java
│ ├── PieProgressRound1.java
│ ├── ProgressPie.java
│ ├── Round1Test003.java
│ ├── output.txt
│ └── output2.txt
├── ds
├── 1todo
├── AVLTree.java
├── BST.java
├── BSTIterative.java
├── BSTTest.java
├── BSTWithDuplicate.java
├── DoublyLinkedList.java
├── HashedArrayTree.java
├── LinkedList.java
├── RedBlackTree.java
├── SkipList.java
├── SplayTree.java
├── Test.java
├── Tree.java
└── graph
│ ├── DirectedGraph.java
│ ├── Edge.java
│ ├── Graph.java
│ ├── UndirectedGraph.java
│ ├── Vertex.java
│ └── WeightedGraph.java
├── google
├── BunnyPrisonerLocating.java
├── DontGetVoluntereed.java
├── EscapePods.java
├── FreeTheBunnyPrisoners.java
├── FuelInjection.java
├── KClosestPoints.java
├── PowerHungry.java
├── PrepareBunnyEscape.java
├── QueueToDo.java
├── Re_Id.java
└── problem.txt
├── oi
├── DumpDataWriter.java
├── README.md
├── StopWatch.java
├── UsingBufferedReader.java
├── UsingBufferedStreams.java
├── UsingDirectBuffering.java
├── UsingInputStream.java
├── UsingMemoryMappedFile.java
├── UsingRandomAccess.java
└── UsingScanner.java
├── problems
├── Easy.txt
├── Hard.txt
├── Medium.txt
├── easy
│ ├── AddBinary.java
│ ├── AddDigits.java
│ ├── AddStrings.java
│ ├── AlternatingBits.java
│ ├── ArrangingCoins.java
│ ├── AssignCookies.java
│ ├── AverageofLevelsinBinaryTree.java
│ ├── BalancedBinaryTree.java
│ ├── BaseballGame.java
│ ├── BestTimeToBuyandSellStock2.java
│ ├── BestTimetoBuyandSellStock.java
│ ├── BinaryTreeLevelOrderTraversal.java
│ ├── BinaryTreeLevelOrderTraversal2.java
│ ├── BinaryTreePaths.java
│ ├── BinaryTreeTIlt.java
│ ├── CanPlaceFlowers.java
│ ├── ClimbingStairs.java
│ ├── ConstructRectangle.java
│ ├── ConstructStringfromBinaryTree.java
│ ├── ContainsDuplicate.java
│ ├── ContainsDuplicateII.java
│ ├── ConverstBSTtoGreaterTree.java
│ ├── ConvertaNumbertoHexadecimal.java
│ ├── CountAndSay.java
│ ├── CountPrimes.java
│ ├── DegreeOfAnArray.java
│ ├── DeleteNodeSingleLinkedList.java
│ ├── DiameterofBinaryTree.java
│ ├── FileSystem.java
│ ├── FindAllAnagramsinString.java
│ ├── FindAllNumbersDisappearedinanArray.java
│ ├── FindModeinBST.java
│ ├── FindPivotIndex.java
│ ├── FindSmallestLetterGreaterThanTarget.java
│ ├── FindSumOfALlLeftLeavesBT.java
│ ├── FindtheDifference389.java
│ ├── FirstUniqueCharacterinaString.java
│ ├── FirstbadVersion.java
│ ├── FizzBuzz.java
│ ├── FlippinganImage.java
│ ├── GenerateParenthesis.java
│ ├── GuessNumberHigherorLower.java
│ ├── HammingDistance.java
│ ├── HappyNumber.java
│ ├── HouseRobber.java
│ ├── ImageSmoother.java
│ ├── ImplementQueueusingStacks.java
│ ├── ImplementStackUsingQueues.java
│ ├── ImplementstrSt.java
│ ├── InsertionBit.java
│ ├── IntersectOfTwoArrray2.java
│ ├── IntersectionOfTwoArrays.java
│ ├── IntersectionofTwoLinkedLists.java
│ ├── InvertBinaryTree.java
│ ├── IslandPerimeter.java
│ ├── IsomorphicStrings.java
│ ├── JewelsAndStones.java
│ ├── JudgeRouteCircle.java
│ ├── LargestDifferenceArray.java
│ ├── LeafSimilarTrees.java
│ ├── LemonadeChange.java
│ ├── LengthofLastWord.java
│ ├── LetterCasePermutation.java
│ ├── LinkedListCycle.java
│ ├── LongestCommonPrefix.java
│ ├── LongestContinuousIncreasingSubsequence.java
│ ├── LongestHarmoniousSubsequence.java
│ ├── LongestPalindrome.java
│ ├── LowestCommonAncestorBST.java
│ ├── MagicalString.java
│ ├── MajorityElement.java
│ ├── MaxAreaOfIsland.java
│ ├── MaxConsecutiveZeros.java
│ ├── MaximizeDistancetoClosestPerson.java
│ ├── MaximumDepthofBinaryTree.java
│ ├── MergeSortedArray.java
│ ├── MergeTwoSortedLists.java
│ ├── MiddleoftheLinkedList.java
│ ├── MinCostClimbingStairs.java
│ ├── MinStack.java
│ ├── MinimumAbsoluteDifferenceinBST.java
│ ├── MinimumDepthofBinaryTree.java
│ ├── MinimumDistanceBetweenBSTNodes.java
│ ├── MinimumMovesToEqualArray.java
│ ├── MinimumTimeDifference.java
│ ├── MostCommonWord.java
│ ├── NumberComplement.java
│ ├── NumberofSegmentsinaString.java
│ ├── PaintFill.java
│ ├── Palindrome2.java
│ ├── PalindromeLinkedList.java
│ ├── PalindromeNumber.java
│ ├── PalindromePermutation.java
│ ├── Pangram.java
│ ├── PascalsTriangle.java
│ ├── PascalsTriangle2.java
│ ├── PathSum.java
│ ├── PathSum3.java
│ ├── PerfectNumber.java
│ ├── PositionsofLargeGroups.java
│ ├── PowerOfFour.java
│ ├── PowerofTwo.java
│ ├── QueuewithMinimum.java
│ ├── RangeAddition2.java
│ ├── RangeSumQuery.java
│ ├── RansomNote.java
│ ├── RecursiveMultiply.java
│ ├── RemoveDuplicatesLinkedList.java
│ ├── RemoveElement.java
│ ├── RemoveLinkedListElements.java
│ ├── RemoveNthNodeFromEndofList.java
│ ├── RemoveZeroes.java
│ ├── RepeatedSubstringPattern.java
│ ├── ReverseBits.java
│ ├── ReverseInteger.java
│ ├── ReverseLinkedList.java
│ ├── ReverseOnlyLetters.java
│ ├── ReverseString.java
│ ├── ReverseVowels.java
│ ├── RotateArray.java
│ ├── RotateString.java
│ ├── RotatedDigits.java
│ ├── SameTree.java
│ ├── SearchInsertPosition.java
│ ├── SecondMinimumNodeInBinaryTree.java
│ ├── ShortestDistancetoaCharacter.java
│ ├── ShortestWordDistance.java
│ ├── SingleElementinSortedArray.java
│ ├── SingleNumber136.java
│ ├── SumofLeftLeaves.java
│ ├── SumofTwoIntegers.java
│ ├── SwapNodesInPair.java
│ ├── SymmetricTree.java
│ ├── ThirdLargest.java
│ ├── TrimBinarySearchTree.java
│ ├── TripleSteps.java
│ ├── TwoSum.java
│ ├── TwoSumIVInputisaBST.java
│ ├── UglyNumber.java
│ ├── UniqueMorseCodeWords.java
│ ├── ValidAnagram.java
│ ├── ValidPalindrome.java
│ └── ValidParentheses.java
├── hard
│ ├── BinaryTreeMaximumPathSum.java
│ ├── CopyListwithRandomPointer.java
│ ├── CutOffTreesForGolfEvent.java
│ ├── Diagonaltraverse.java
│ ├── ExpressionAddOperators.java
│ ├── FindKthSmallestPairDistance.java
│ ├── FirstMissingPositive.java
│ ├── FreqStack.java
│ ├── InsertInterval.java
│ ├── InterleavingStrings.java
│ ├── LRUCache.java
│ ├── MaxChunksToMakeSorted2.java
│ ├── NumberOfAtoms.java
│ ├── PostOrderTraversalTree.java
│ ├── ReachingPoints.java
│ ├── SerializeAndDeserializeBT.java
│ ├── ShortestPalindrome.java
│ ├── SimilarStringGroups.java
│ ├── SlidingWindowMedian.java
│ ├── SwimInRisingWater.java
│ ├── TrappingRainWater.java
│ └── WordLadder2.java
├── medium
│ ├── AccountMerge.java
│ ├── AddTwoNumbers.java
│ ├── AddTwoNumbers2.java
│ ├── AdvantageShuffle.java
│ ├── AlienAlphabet.java
│ ├── AllNodesDistanceKinBinaryTree.java
│ ├── AllPathFromSourceToTarget.java
│ ├── AnimalShelter.java
│ ├── ArrayNesting.java
│ ├── AsteroidCollision.java
│ ├── BSTSequences.java
│ ├── BattleShipsInBoard.java
│ ├── BeautifulArrangement.java
│ ├── BinarySearchTreeIterator.java
│ ├── BinaryTreeInorderTraversal.java
│ ├── BinaryTreeLeftSIdeView.java
│ ├── BinaryTreePreorderTraversal.java
│ ├── BinaryTreePruning.java
│ ├── BinaryTreeRightSideView.java
│ ├── BoatstoSavePeople.java
│ ├── CBTInserter.java
│ ├── CarFleet.java
│ ├── CheapestFlightsWithinKStops.java
│ ├── CloneGraph.java
│ ├── CoinChange.java
│ ├── CoinChange2.java
│ ├── Combination.java
│ ├── CombinationSum.java
│ ├── CombinationSum2.java
│ ├── CombinationSum3.java
│ ├── CompareVersion.java
│ ├── ConsecutiveNumbersSum.java
│ ├── ConstructBTFromPreOrderAndInorder.java
│ ├── ConstructBinaryTreefromString.java
│ ├── ContainerWithMostWater.java
│ ├── ContinuousSubarraySum.java
│ ├── ConvertBSTToGreaterTree.java
│ ├── ConvertSortedArraytoBinarySearchTree.java
│ ├── ConvertSortedListtoBinarySearchTree.java
│ ├── CountCompleteBinarytree.java
│ ├── CountEval.java
│ ├── CountingBits.java
│ ├── CourseSchedule.java
│ ├── CourseScheduleII.java
│ ├── CustomSortString.java
│ ├── DailyTemperature.java
│ ├── DecodeString.java
│ ├── DecodeWays.java
│ ├── DeleteNodeinaBST.java
│ ├── EggDropPuzzle.java
│ ├── EmployeeImportance.java
│ ├── EncodeandDecodeTinyURL.java
│ ├── EqualTreePartition.java
│ ├── EvaluateReversePolishNotation.java
│ ├── FIndAndReplacePattern.java
│ ├── FindAllDuplicatesinanArray.java
│ ├── FindAndReplaceString.java
│ ├── FindDuplicateFileinSystem.java
│ ├── FindDuplicateSubtrees.java
│ ├── FindEventualSafeStates.java
│ ├── FindKClosestElements.java
│ ├── FindLargestElementinEachRow.java
│ ├── FindLeftMostElement.java
│ ├── FindMinimuminRotatedSortedArray.java
│ ├── FindPeakElement.java
│ ├── FindRightInterval.java
│ ├── FlattenBinaryTreetoLinkedList.java
│ ├── FlattenDictionary.java
│ ├── FlattenNestedListIterator.java
│ ├── FourSumII.java
│ ├── FriendsCycle.java
│ ├── GameofLife.java
│ ├── GasStation.java
│ ├── HIndex.java
│ ├── HandofStraights.java
│ ├── HouseRober2.java
│ ├── IncreasingSubsequences.java
│ ├── InsertIntoBST.java
│ ├── InsertionSortList.java
│ ├── IntegerBreak.java
│ ├── IntegertoRoman.java
│ ├── IsGraphBipartite.java
│ ├── IsSubsequence.java
│ ├── JumpGame.java
│ ├── KthLargestElementinanArray.java
│ ├── KthSmallestElementinaBST.java
│ ├── KthSymbolinGrammar.java
│ ├── LargestBSTSubtree.java
│ ├── LargestPlusSign.java
│ ├── LargetElementinRowsBT.java
│ ├── LetterCombinationsofaPhoneNumber.java
│ ├── LicenseKeyFormatting.java
│ ├── LinkedListComponents.java
│ ├── LinkedListCycle2.java
│ ├── LinkedListRandomNode.java
│ ├── LogSystem.java
│ ├── LonelyPixelI.java
│ ├── LongestAbsolutePath.java
│ ├── LongestMountaininArray.java
│ ├── LongestPalindromicSubstring.java
│ ├── LongestUnivaluePath.java
│ ├── LongestWordinDictionarythroughDeleting.java
│ ├── LowestCommonAncestorofaBinaryTree.java
│ ├── LuckyNumberEight.java
│ ├── MagicDictionary.java
│ ├── MapSum.java
│ ├── MaxChunksToMakeSorted.java
│ ├── MaxConsecutiveZeros2.java
│ ├── MaxIncreaseToKeepSkyline.java
│ ├── MaxIncreasingSubsequence.java
│ ├── MaximumBinaryTree.java
│ ├── MaximumLengthOfRepeatedSubArray.java
│ ├── MaximumProductSubarray.java
│ ├── MaximumSubarray.java
│ ├── MaximumSwap.java
│ ├── MaximumWidthofBinaryTree.java
│ ├── MergeIntervals.java
│ ├── MergekSortedLists.java
│ ├── MetaStrings.java
│ ├── MiniParser.java
│ ├── MinimumHeightTrees.java
│ ├── MinimumIndexSumOfTwoLists.java
│ ├── MinimumPathSum.java
│ ├── MinimumSizeSubArray.java
│ ├── MininumNumberOfArrowsToBurstBalloons.java
│ ├── MissingNumber.java
│ ├── MonotoneIncreasingDigit.java
│ ├── MostFrequentSubtreeSum.java
│ ├── MostProfitAssigningWork.java
│ ├── MultiplyStrings.java
│ ├── MyCalendar.java
│ ├── MyCalendarTwo.java
│ ├── NestedIterator.java
│ ├── NetworkDelay.java
│ ├── NextClosestTime.java
│ ├── NextPermutation.java
│ ├── NonoverlappingIntervals.java
│ ├── NumberofIslands.java
│ ├── NumberofMatchingSubsequences.java
│ ├── OddEvenLinkedList.java
│ ├── PalindromPermuatation2.java
│ ├── PalindromePairs.java
│ ├── PalindromicSubstrings.java
│ ├── PartitionLabel.java
│ ├── PartitionList.java
│ ├── PathSum2.java
│ ├── PeekingIterator.java
│ ├── Permutations.java
│ ├── Permutations2.java
│ ├── PopulatingNextRightPointersinEachNode.java
│ ├── PossibleBipartition.java
│ ├── Pow.java
│ ├── ProductofArrayExceptSelf.java
│ ├── QueueReconstructionByHeight.java
│ ├── RabbitsinForest.java
│ ├── RandomPickIndex.java
│ ├── ReachANumber.java
│ ├── ReconstructOriginalDigitsfromEnglish.java
│ ├── RedundantConnection.java
│ ├── RemoveComments.java
│ ├── RemoveDuplicatesFromList2.java
│ ├── RemoveKDigits.java
│ ├── ReorderList.java
│ ├── ReorderedPowerof2.java
│ ├── RepeatedDNASequences.java
│ ├── ReplaceWords.java
│ ├── ReplacementInteger.java
│ ├── ReverseLinkedListII.java
│ ├── ReverseString.java
│ ├── RoomsAndKeys.java
│ ├── RotateImage.java
│ ├── RotateList.java
│ ├── Searcha2DMatrix.java
│ ├── Searcha2DMatrixII.java
│ ├── SearchinRotatedArray2.java
│ ├── SearchinRotatedSortedArray.java
│ ├── SerializeandDeserializeBST.java
│ ├── SetMatrixZeroes.java
│ ├── ShiftingLetters.java
│ ├── ShoppingOffers.java
│ ├── ShortEncodingofWords.java
│ ├── ShortestWordDistance2.java
│ ├── ShortestWordDistance3.java
│ ├── ShuffleanArray.java
│ ├── SingleNumberII.java
│ ├── SmallestSubtreewithalltheDeepestNodes.java
│ ├── SortCharactersByFrequency.java
│ ├── SortColors.java
│ ├── SortList.java
│ ├── SortStack.java
│ ├── SpiralMatrix.java
│ ├── SpiralMatrix2.java
│ ├── SplitLinkedListinParts.java
│ ├── StackOfPlates.java
│ ├── SubArrayProductLessThanK.java
│ ├── SubSets.java
│ ├── SubsetsII.java
│ ├── Sum3.java
│ ├── Sum4.java
│ ├── SumRoottoLeafNumbers.java
│ ├── SummaryRanges.java
│ ├── Targetsum.java
│ ├── TaskScheduler.java
│ ├── TeemoAttacking.java
│ ├── TopKFrequentElements.java
│ ├── TopKFrequentWords.java
│ ├── TopVotedCandidate.java
│ ├── Triangle.java
│ ├── TwoKeysKeyboard.java
│ ├── TwoSumSortedArray.java
│ ├── UniquePaths.java
│ ├── UniquePathsII.java
│ ├── ValidPerfectSquare.java
│ ├── ValidSudoku.java
│ ├── ValidateBinarySearchTree.java
│ ├── VerifyPreorderSerializationofBinaryTree.java
│ ├── WaterAndJugProblem.java
│ ├── WidthOfBinaryTree.java
│ ├── WordBreak.java
│ ├── WordDictionary.java
│ ├── WordLadder.java
│ ├── WordSearch.java
│ ├── WordSubsets.java
│ └── ZigZagOrderLevelTraversalBST.java
└── utils
│ ├── Interval.java
│ ├── ListNode.java
│ ├── RandomListNode.java
│ ├── TreeNode.java
│ └── UndirectedGraphNode.java
├── timus
├── A3801893.java
├── ABProblem1000.java
├── Alchemy1573.java
├── AmusementPark1796.java
├── AnotherDressRehearsal2035.java
├── AntiCAPS.java
├── Bayan1563.java
├── BinaryLexicographicSequence1081.java
├── BritishScientistsSavetheWorld1925.java
├── CentipedesMorning1876.java
├── CipherMessage.java
├── CityBlocks1139.java
├── Copying1131.java
├── Cryptography1086.java
├── DemocracyinDanger1025.java
├── Devices2033.java
├── DivorceoftheSevenDwarfs1243.java
├── Donaldisapostman2023.java
├── DontAskWomanaboutHerAge1104.java
├── Easy1044.java
├── Elections1263.java
├── ElectrificationPlan1982.java
├── Factorials.java
├── Farm1349.java
├── FastReader.java
├── FinalStandings1100.java
├── FlatSpots1617.java
├── ForFansofStatistics1613.java
├── Fuses1327.java
├── GabyIvanushka1082.java
├── GameofNuts2068.java
├── GenealogicalTree.java
├── GoatInthegarden1084.java
├── Hieroglyphs.java
├── HistoryExam1196.java
├── IsenbaevNumber1837.java
├── LongStatement.java
├── Magician1370.java
├── MagneticStorms.java
├── Maximum1079.java
├── MaximumSum1146.java
├── Metro1119.java
├── NonYekaterinburgSubway1272.java
├── OneStepfromHappiness1493.java
├── Order1510.java
├── OverturnedNumbers2031.java
├── Palindrome1297.java
├── Parliament1136.java
├── PenaltyTime.java
├── Penguins.java
├── PhoneNumbers1002.java
├── ProductofDigits1014.java
├── QuestionsandAnswers1026.java
├── Rope1020.java
├── Sabotage1290.java
├── SacramentoftheSum1021.java
├── SandroBook1723.java
├── SegmentTree.java
├── SimpleExpression2066.java
├── Spammer1496.java
├── Spiral1224.java
├── SquareCountry1073.java
├── StoneGame1180.java
├── StonePile1005.java
├── Sum1068.java
├── Superstack.java
├── Taxi1607.java
├── TaxiforProgrammers2005.java
├── TearsofDrowned1935.java
├── TestTask2002.java
├── Thebattleneartheswamp1990.java
├── TopologicalSorting1280.java
├── TwoTeams1106.java
└── WeddingDinner2100.java
├── toptal
├── First.java
├── Second.java
└── Third.java
└── triplebyte
└── Board.java
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: sherxon
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | custom: # Replace with a single custom sponsorship URL
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | .idea/
3 | out/
4 | src/contests/Temp.java
5 | src/contests/facebookHC/out.txt
6 | src/contests/facebookHC/outround1test3.txt
7 | src/algo/temp/
--------------------------------------------------------------------------------
/AlgoDS.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/src/FastReader.java:
--------------------------------------------------------------------------------
1 | import java.io.BufferedReader;
2 | import java.io.IOException;
3 | import java.io.InputStreamReader;
4 | import java.util.StringTokenizer;
5 |
6 | /**
7 | * Created by sherxon on 12/3/16.
8 | */
9 | public class FastReader {
10 | BufferedReader bf;
11 | StringTokenizer st;
12 |
13 |
14 | public FastReader() {
15 | bf=new BufferedReader(new InputStreamReader(System.in));
16 | }
17 | String nextLine(){
18 | String st="";
19 | try {
20 | st=bf.readLine();
21 | } catch (IOException e) {
22 | e.printStackTrace();
23 | }
24 | return st;
25 | }
26 | String next(){
27 | while (st==null || !st.hasMoreTokens()){
28 | try {
29 | st= new StringTokenizer(bf.readLine());
30 | } catch (IOException e) {
31 | e.printStackTrace();
32 | }
33 |
34 | }
35 | return st.nextToken();
36 | }
37 | int nextInt(){
38 | return Integer.parseInt(next());
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/algo/1todo:
--------------------------------------------------------------------------------
1 | radixSort
2 | heapSort
3 | bucket sort
4 | introsort
5 | mergesort plus
6 | quicksort plus
7 | timsort
8 |
9 | Prim's
10 | Kruskall
11 | topological sort(all types)
12 | detect cycle in (un)directed graph
13 | detect odd cycle (of each component)
14 | Hamiltonian cycle
15 | Hachers graph
16 | vertex cover
17 | complement graph
18 | number of separate components
19 | is tree
20 | is Bipartite
21 | get spanning tree
22 | get components list
23 | toString
24 |
25 | BitSet
26 | BloomFilter
27 |
28 | hash, -> encodable, decodable, murmut, sha256
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/src/algo/ReservoirSampling.java:
--------------------------------------------------------------------------------
1 | package algo;
2 |
3 | /**
4 | * Created by sherxon on 5/21/17.
5 | */
6 | public class ReservoirSampling {
7 |
8 | /**
9 | * return k random elements from given stream without using any extra space.
10 | * assume k is valid
11 | */
12 | int[] getRandom(int[] stream, int k) {
13 | int[] result = new int[k];
14 | int i;
15 | for (i = 0; i < k; i++) {
16 | result[i] = stream[i]; // get first k elements into result
17 | }
18 | for (; i < stream.length; i++) {
19 | int rand = (int) (Math.random() * (i + 1)); // get random element between 0 and i
20 |
21 | if (rand < k) {
22 | result[rand] = stream[i];
23 | }
24 |
25 | }
26 | return result;
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/algo/UnionFind.java:
--------------------------------------------------------------------------------
1 | package algo;
2 |
3 | /**
4 | * Created by sherxon on 1/29/17.
5 | */
6 | public class UnionFind {
7 | int[] a;
8 | int[] sz;
9 | public UnionFind(int size) {
10 | a = new int[size + 1];
11 | sz = new int[size + 1];
12 | for (int i = 0; i < a.length; i++) {
13 | a[i] = i;
14 | sz[i] = 1;
15 | }
16 |
17 | }
18 |
19 | public void union(int i, int j) {
20 | int ip = find(i);
21 | int jp = find(j);
22 | if (sz[ip] < sz[jp]) {
23 | a[ip] = jp;
24 | sz[jp] += sz[ip];
25 | } else {
26 | sz[ip] += sz[jp];
27 | a[jp] = a[ip];
28 | }
29 |
30 | }
31 |
32 | private int find(int i) {
33 | while (a[i] != i) {
34 | a[i] = a[a[i]];
35 | i = a[i];
36 |
37 | }
38 | return i;
39 | }
40 |
41 | public boolean connected(int i, int j) {
42 | return find(i) == find(j);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/algo/dp/FibonacciNumber.java:
--------------------------------------------------------------------------------
1 | package algo.dp;
2 |
3 | /**
4 | * Created by sherxon on 3/2/17.
5 | */
6 | public class FibonacciNumber {
7 |
8 | int fib(int n) {
9 | if (n <= 0) return 0;
10 | if (n == 1 || n == 2) return 1;
11 | int f1 = 1;
12 | int f2 = 2;
13 | while (f1 < n) {
14 | int f3 = f1 + f2;
15 | f1 = f2;
16 | f2 = f3;
17 | }
18 | return f1;
19 | }
20 |
21 | int fibonacci(int[] a, int n) {
22 | if (n <= 0) return 0;
23 | if (n == 1 || n == 2) return 1;
24 | if (a[n] != 0) return a[n];
25 | a[n] = fibonacci(a, n - 1) + fibonacci(a, n - 2);
26 | return a[n];
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/algo/graph/GraphWithTimeStamp.java:
--------------------------------------------------------------------------------
1 | package algo.graph;
2 |
3 | import ds.graph.Graph;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /**
9 | * Created by sherxon on 4/16/17.
10 | */
11 | /**
12 | * This is a graph with timestamps (in and out) in each vertex.
13 | * */
14 | public class GraphWithTimeStamp {
15 |
16 | protected Graph graph;
17 | protected Map in;
18 | protected Map out;
19 | int time;
20 |
21 | public GraphWithTimeStamp(Graph graph) {
22 | this.graph = graph;
23 | in= new HashMap<>();
24 | out= new HashMap<>();
25 | }
26 |
27 | protected void addTimeStamp(Integer current){
28 | time++;
29 | in.put(current, time);
30 | for (Integer neighbor : graph.getNeighbors(current)) {
31 |
32 | if(!in.containsKey(neighbor))
33 | addTimeStamp(neighbor);
34 | }
35 | time++;
36 | out.put(current, time);
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/algo/graph/IsConnected.java:
--------------------------------------------------------------------------------
1 | package algo.graph;
2 |
3 | import ds.graph.Graph;
4 |
5 | import java.util.Set;
6 |
7 | /**
8 | * Created by sherxon on 4/16/17.
9 | */
10 | /**
11 | * To find If given graph connected or not, we do dfs and compare all visited nodes during dfs with graph's
12 | * vertices if they are the same set of vertices, it means the graphs is connected. Running time is the same as
13 | * DFS.
14 | * */
15 | public class IsConnected extends DFS{
16 | Graph graph;
17 |
18 | public IsConnected(Graph graph) {
19 | super(graph);
20 | this.graph=graph;
21 | }
22 |
23 | public boolean isConnected(){
24 | search(1); // any random vertex
25 |
26 | Set graphVertices=graph.getVertices();
27 |
28 | if(graphVertices.size()!=visited.size())return false;
29 |
30 | for (Integer integer : graph.getVertices()) {
31 | if(!visited.contains(integer)) return false;
32 | }
33 | return true;
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/algo/numerals/GCD.java:
--------------------------------------------------------------------------------
1 | /*
2 | * The greatest common divisor is the largest natural number that divides two numbers without leaving a remainder.
3 | */
4 |
5 | public class GCD {
6 |
7 | public static int gcd(int num1, int num2) {
8 | if (num1 == 0) // If the first number becomes 0, then the second number is the GCD of the two numbers.
9 | return num2;
10 | return gcd(num2 % num1, num1); // Else, find the GCD of the remainder when second number is divided by the first, and the first number.
11 | }
12 |
13 | public static void main(String[] args) {
14 | System.out.println(gcd(35, 10));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/algo/numerals/SieveofEratosthenes.java:
--------------------------------------------------------------------------------
1 | package algo.numerals;
2 |
3 | /**
4 | * Created by sherxon on 1/13/17.
5 | */
6 |
7 | /**
8 | * This is finding prime numbers up to given number N. Space complexity is N.
9 | * The ides is to mark all numbers are divisible by i starting from 2 in every step.
10 | */
11 | public class SieveofEratosthenes {
12 | public static void main(String[] args) {
13 | findPrimes(100);
14 | }
15 |
16 | // print all prime numbers up to given number n
17 | static void findPrimes(int n) {
18 | boolean[] primes = new boolean[n];
19 |
20 | for (int i = 2; i < n; i++)
21 | if (!primes[i])
22 | for (int j = i * i; j < primes.length; j += i)
23 | primes[j] = true;
24 |
25 | for (int i = 2; i < primes.length; i++)
26 | if (!primes[i])
27 | System.out.println(i);
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/algo/recursion/Factorial.java:
--------------------------------------------------------------------------------
1 | package algo.recursion;
2 | /*
3 | * Factorial is the product of all numbers from 1 to n.
4 | * Example : 5! = 5 x 4 x 3 x 2 x 1 = 120
5 | * This can also be written as 5! = 5 x 4!
6 | */
7 |
8 | public class Factorial {
9 |
10 | private static long factorial(int num) {
11 | if (num <= 1) // 1! = 1, hence return 1 when the num becomes 1.
12 | return 1;
13 | return num * factorial(num - 1); // num! = num * (num - 1)!
14 | }
15 |
16 | public static void main(String[] args) {
17 | System.out.println(factorial(10));
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/algo/sortingandsearching/LinearSearch.java:
--------------------------------------------------------------------------------
1 | public class LinearSearch {
2 |
3 | public static boolean linearSearch(T[] array, T element) {
4 | for (int i = 0; i < array.length; i++) {
5 | if (array[i].equals(element))
6 | return true;
7 | }
8 | return false;
9 | }
10 |
11 | public static void main(String[] args) {
12 | Integer[] array = {10, 30, 65, 98, 465, 48};
13 | System.out.println(linearSearch(array, 48));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/algo/sortingandsearching/TestSorting.java:
--------------------------------------------------------------------------------
1 | package algo.sortingandsearching;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-16.
7 | */
8 | public class TestSorting {
9 | public static void main(String[] args) {
10 | int n = (int) (Math.random() * 10);
11 | for (int i = 0; i < n; i++) {
12 | //Integer[] a = new Integer[n];
13 | int[] a = new int[n];
14 | for (int j = 0; j < a.length; j++) {
15 | a[j] = (int) (Math.random() * 10);
16 | }
17 | System.out.print(Arrays.toString(a) + " ==>> ");
18 | CountingSort.sort(a);
19 |
20 |
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/codeforces/BachgoldProblem.java:
--------------------------------------------------------------------------------
1 | package codeforces;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-25.
7 | */
8 | public class BachgoldProblem {
9 | public static void main(String[] args) {
10 | Scanner in=new Scanner(System.in);
11 | int n=in.nextInt();
12 | if(n%2==0){
13 | System.out.println(n/2);
14 | for (int i = 0; i map = new TreeMap<>((a, b) -> b.compareTo(a));
15 | for (int i = 0; i < nums.length; i++) {
16 | map.put(nums[i], i);
17 | }
18 | String[] s = new String[nums.length];
19 | int i = 1;
20 | for (Integer integer : map.keySet()) {
21 | if (i == 1) {
22 | s[map.get(integer)] = "Gold Medal";
23 | } else if (i == 2) {
24 | s[map.get(integer)] = "Silver Medal";
25 | } else if (i == 3) {
26 | s[map.get(integer)] = "Bronze Medal";
27 | } else {
28 | s[map.get(integer)] = String.valueOf(i);
29 | }
30 | i++;
31 | }
32 | return s;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/contests/Solution2.java:
--------------------------------------------------------------------------------
1 | package contests;
2 |
3 | /**
4 | * Created by sherxon on 2/27/17.
5 | */
6 | public class Solution2 {
7 | public static void main(String[] args) {
8 |
9 | }
10 |
11 | static public String shortestPalindrome(String s) {
12 |
13 | if (s.length() <= 1) return s;
14 | char[] a = s.toCharArray();
15 | StringBuilder sb = new StringBuilder();
16 | int i = 0;
17 | int j = a.length - 1;
18 | while (i < j) {
19 | if (a[j] == a[i]) {
20 | j--;
21 | i++;
22 | } else {
23 | i = 0;
24 | }
25 | }
26 | System.out.println(s.substring(0, i));
27 |
28 | return sb.toString() + s.substring(i);
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/contests/contest25/ComplexNumberMultiplication.java:
--------------------------------------------------------------------------------
1 | package contests.contest25;
2 |
3 | /**
4 | * Created by sherxon on 3/25/17.
5 | */
6 | public class ComplexNumberMultiplication {
7 | public static void main(String[] args) {
8 |
9 | }
10 |
11 | public String complexNumberMultiply(String a, String b) {
12 | String s = "";
13 | String a1 = a.split("\\+")[0];
14 | String a2 = a.split("\\+")[1];
15 | String b1 = b.split("\\+")[0];
16 | String b2 = b.split("\\+")[1];
17 | long res = 0;
18 | if (a2.contains("\\-")) {
19 | int right = Integer.parseInt(b2.substring(0, b2.length() - 1));
20 | res = Integer.parseInt(a1) * Integer.parseInt(b1) + right * right;
21 |
22 | } else {
23 |
24 | }
25 | return s;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/contests/contest30/ReshapetheMatrix.java:
--------------------------------------------------------------------------------
1 | package contests.contest30;
2 |
3 | /**
4 | * Created by sherxon on 4/29/17.
5 | */
6 | public class ReshapetheMatrix {
7 | public int[][] matrixReshape(int[][] a, int r, int c) {
8 | if(a.length == 0 || a[0].length == 0)return a;
9 |
10 | if( r*c != a.length * a[0].length)return a;
11 |
12 | int[][] b=new int[r][c];
13 | int ii=0;
14 | int jj=0;
15 |
16 | for(int i=0; i map= new HashMap<>();
16 |
17 | int count=0;
18 | for(int i=0; i bst=new AVLTree<>();
9 | bst.insert(3);
10 | bst.insert(1);
11 | bst.insert(2);
12 | bst.insert(4);
13 | System.out.println(bst.search(2));
14 | String hello = new String("hello"); // in pool and in heap, reference to heap
15 | String helloWorld = hello + " world"; // ref pool
16 | String ss="hello world";
17 | System.out.println(helloWorld == ss); //
18 | System.out.println(-3>>1);
19 | System.out.println(-4>>>1);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/ds/SplayTree.java:
--------------------------------------------------------------------------------
1 | package ds;
2 |
3 | /**
4 | * Created by sherxon on 6/30/17.
5 | */
6 |
7 | import problems.utils.TreeNode;
8 |
9 | /**
10 | * This is implementation os splay tree. Running time is amortized O(logN) for lookup, insertion,
11 | * deletion. Splay trees splay the tree after each insertion and lookup operations so that accessed
12 | * nodes get closer to root. Garbage Collection and Cache are best use cases. No need to store additional
13 | * pointers with each node. There are three cases to consider when splaying:
14 | * Zig-Zig=> parent node (p) and X node are both left or right children.
15 | * Zig-Zag =>p is not root and x is the right child and p is the left child, or vice versa
16 | * Zig => when there is no grandparent of x. (parent is root )
17 | */
18 | public class SplayTree, V> {
19 | TreeNode root;
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/ds/Test.java:
--------------------------------------------------------------------------------
1 | package ds;
2 |
3 | /**
4 | * Created by sherxon on 5/25/17.
5 | */
6 | public class Test {
7 |
8 | public static void main(String[] args) {
9 | HashedArrayTree hash = new HashedArrayTree();
10 | for (int i = 0; i < 500; i++) {
11 | hash.add(i);
12 | //hash.printStats();
13 | System.out.println(hash.get(i));
14 | }
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/ds/Tree.java:
--------------------------------------------------------------------------------
1 | package ds;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-18.
5 | */
6 | public interface Tree {
7 | void insert(K k);
8 | boolean search(K k);
9 | void delete(K k);
10 | }
11 |
--------------------------------------------------------------------------------
/src/ds/graph/Graph.java:
--------------------------------------------------------------------------------
1 | package ds.graph;
2 |
3 | import java.util.Set;
4 |
5 | /**
6 | * Created by sherxon on 1/1/17.
7 | */
8 | public interface Graph {
9 | boolean addVertex(Integer t);
10 |
11 | Double addEdge(Integer from, Integer to);
12 |
13 | boolean addEdge(Integer from, Integer to, Double weight);
14 |
15 | boolean removeVertex(Integer t);
16 |
17 | boolean removeEdge(Integer from, Integer to);
18 |
19 | Set getVertices();
20 |
21 | Set getNeighbors(Integer ver);
22 | int size();
23 | }
--------------------------------------------------------------------------------
/src/google/BunnyPrisonerLocating.java:
--------------------------------------------------------------------------------
1 | package google;
2 |
3 | import java.math.BigInteger;
4 |
5 | /**
6 | * Created by sherxon on 6/20/17.
7 | */
8 | //Refer a friend: https://goo.gl/RkwMCp [ready]
9 |
10 | public class BunnyPrisonerLocating {
11 |
12 | public static void main(String[] args) {
13 | System.out.println(answer(100000, 100000));
14 | int a = 2000000001;
15 | }
16 |
17 | public static String answer(int x, int y) {
18 | BigInteger yy = BigInteger.ONE;
19 | int yi = 1;
20 | while (yi < y) {
21 | yy = yy.add(BigInteger.valueOf(yi));
22 | yi++;
23 | }
24 | yi++;
25 | int xi = 1;
26 | while (xi < x) {
27 | yy = yy.add(BigInteger.valueOf(yi));
28 | xi++;
29 | yi++;
30 | }
31 | return yy.toString();
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/oi/README.md:
--------------------------------------------------------------------------------
1 | # Java File IO approaches
2 | Currently This package contains test cases and benchmarks of the following Java classes.
3 | #### [Blog about File IO in Java](http://sherxon.com/blog/fastest-io-in-java)
4 |
5 | 1) [FileInputStream](https://github.com/sherxon/AlgoDS/blob/master/src/oi/UsingInputStream.java)
6 | 2) [BufferedInputStream](https://github.com/sherxon/AlgoDS/blob/master/src/oi/UsingBufferedStreams.java)
7 | 3) [Direct Buffering](https://github.com/sherxon/AlgoDS/blob/master/src/oi/UsingDirectBuffering.java)
8 | 4) [BufferedReader](https://github.com/sherxon/AlgoDS/blob/master/src/oi/UsingBufferedReader.java)
9 | 5) [MappedByteBuffer](https://github.com/sherxon/AlgoDS/blob/master/src/oi/UsingMemoryMappedFile.java)
10 |
11 | You can download and create test cases Using DumpDataWriter class and see results on you own machine.
12 |
13 |
14 |
--------------------------------------------------------------------------------
/src/oi/StopWatch.java:
--------------------------------------------------------------------------------
1 | package oi;
2 |
3 | import java.time.Clock;
4 |
5 | /**
6 | * Created by sherxon on 4/23/17.
7 | */
8 | public class StopWatch {
9 | private static long begin =0l;
10 | private static long end =0l;
11 |
12 | static void start(){
13 | begin = Clock.systemDefaultZone().millis();
14 | }
15 |
16 | static long stop(){
17 | end = Clock.systemDefaultZone().millis();
18 | return end-begin;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/oi/UsingRandomAccess.java:
--------------------------------------------------------------------------------
1 | package oi;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.io.RandomAccessFile;
6 |
7 | /**
8 | * Created by sherxon on 4/28/17.
9 | */
10 | public class UsingRandomAccess {
11 | public static void main(String[] args) throws IOException {
12 | //-------------- Test reading 1 MB file. --------------------
13 | StopWatch.start();
14 | RandomAccessFile file1=new RandomAccessFile(new File(DumpDataWriter.input1MB), "r");
15 | while (file1.read()!=-1);
16 | long duration = StopWatch.stop();
17 | System.out.println(duration);
18 |
19 | StopWatch.start();
20 | RandomAccessFile file2=new RandomAccessFile(new File(DumpDataWriter.input10MB), "r");
21 | while (file2.read()!=-1);
22 | long duration2 = StopWatch.stop();
23 | System.out.println(duration2);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/easy/AddDigits.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-23.
5 | */
6 |
7 | /**
8 | * Problem: Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
9 | * Solution: Read About Digital root in wikipedia.
10 | */
11 | public class AddDigits {
12 | public int addDigits(int num) {
13 | return num == 0 ? 0 : (num % 9 == 0 ? 9 : num % 9);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/problems/easy/AddStrings.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/10/17.
5 | */
6 |
7 | /**
8 | * Problem: Given two non-negative integers a and b (length of a and b < 5100) represented as string, return the sum of a and b.
9 | */
10 | public class AddStrings {
11 | /**
12 | * Start adding from the least significant digit.
13 | */
14 | static String addStrings(String a, String b) {
15 | int i=a.length()-1;
16 | int j=b.length()-1;
17 | int carry=0;
18 | StringBuilder sb= new StringBuilder();
19 | while (i>=0 || j>=0){
20 | int aa=0;
21 | int bb=0;
22 | if(i>=0)
23 | aa=a.charAt(i--)-'0';
24 | if(j>=0)
25 | bb=b.charAt(j--)-'0';
26 |
27 | int sum=(aa+bb+carry);
28 | sb.append(sum%10);
29 | carry=sum/10;
30 | }
31 | sb=sb.reverse();
32 | if(carry>0)sb.insert(0, carry);
33 | return sb.toString();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/problems/easy/AlternatingBits.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class AlternatingBits {
7 | public static void main(String[] args) {
8 | System.out.println(hasAlternatingBits(10));
9 | }
10 |
11 | static boolean hasAlternatingBits(int n) {
12 | Boolean x = null;
13 | int m = 0;
14 | for (int i = 0; i < 32; i++) {
15 | int k = ((n >> i) & 1);
16 | if (k == 1)
17 | m = m | (1 << i);
18 | if (x == null) {
19 | x = k == 1;
20 | continue;
21 | }
22 | if (x == (k == 1))
23 | return false;
24 | if (m == n)
25 | return true;
26 |
27 | x = !x;
28 | }
29 | return true;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/problems/easy/ArrangingCoins.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-29.
5 | */
6 | public class ArrangingCoins {
7 | public static void main(String[] args) {
8 | System.out.println(1<<3);
9 | }
10 |
11 | public int arrangeCoins(int n) {
12 | return (int) ((-1+(Math.sqrt(8l*n+1)))/2);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/problems/easy/AssignCookies.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by sherxon on 1/7/17.
7 | */
8 | public class AssignCookies {
9 | /**
10 | * We sort both arrays and search greedily. Time complexity is O(NlgN)
11 | * */
12 | public int findContentChildren(int[] g, int[] s) {
13 | if (g.length == 0 || s.length == 0) return 0;
14 | Arrays.sort(g);
15 | Arrays.sort(s);
16 | int left = 0;
17 | int right = 0;
18 | int count = 0;
19 | while (left < g.length && right < s.length) {
20 | if (g[left] <= s[right]) {
21 | left++;
22 | right++;
23 | count++;
24 | } else right++;
25 | }
26 | return count;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/easy/BaseballGame.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.Stack;
4 |
5 | public class BaseballGame {
6 | public int calPoints(String[] a) {
7 | if (a == null || a.length == 0)
8 | return 0;
9 | Stack stack = new Stack<>();
10 | for (int i = 0; i < a.length; i++) {
11 | String s = a[i];
12 | if (s.equals("D")) {
13 | stack.add(stack.peek() * 2);
14 | } else if (s.equals("C")) {
15 | stack.pop();
16 | } else if (s.equals("+")) {
17 | int top = stack.pop();
18 | int sc = stack.peek() + top;
19 | stack.add(top);
20 | stack.add(sc);
21 | } else {
22 | stack.add(Integer.parseInt(s));
23 | }
24 | }
25 | int sum = 0;
26 | while (!stack.isEmpty()) {
27 | sum += stack.pop();
28 | }
29 | return sum;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/problems/easy/BestTimeToBuyandSellStock2.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/29/17.
5 | */
6 | public class BestTimeToBuyandSellStock2 {
7 |
8 | public int maxProfit(int[] a) {
9 | if (a.length < 2) return 0;
10 | int total = 0;
11 | for (int i = 1; i < a.length; i++) {
12 | if (a[i] > a[i - 1]) total += a[i] - a[i - 1];
13 | }
14 | return total;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/problems/easy/BestTimetoBuyandSellStock.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-26.
5 | */
6 | public class BestTimetoBuyandSellStock {
7 | public int maxProfit(int[] a) {
8 | if(a.length==0)return 0;
9 | int max = 0;
10 | int min=a[0];
11 | for (int i = 1; i < a.length; i++) {
12 | max = Math.max(max, a[i] - min);
13 | min = Math.min(min, a[i]);
14 | }
15 | return max;
16 |
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/problems/easy/ClimbingStairs.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-29.
5 | */
6 | public class ClimbingStairs {
7 |
8 | public int climbStairs(int n) {
9 | if(n<4)return n;
10 | int f1=1;
11 | int f2=1;
12 | int f3=f1+f2;
13 | for(int i=1; i Math.abs(area / i - i)) {
16 | diff = Math.abs(area / i - i);
17 | ii = i;
18 | }
19 | }
20 | }
21 | return new int[]{Math.max(ii, area / ii), Math.min(ii, area / ii)};
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/problems/easy/ConstructStringfromBinaryTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 6/3/17.
7 | */
8 | public class ConstructStringfromBinaryTree {
9 |
10 | public String tree2str(TreeNode t) {
11 | StringBuilder sb = new StringBuilder();
12 | if (t == null) {
13 | return sb.toString();
14 | }
15 | pro(t, sb);
16 | return sb.toString();
17 | }
18 |
19 | void pro(TreeNode x, StringBuilder sb) {
20 | if (x == null) {
21 | return;
22 | }
23 |
24 | sb.append(x.val);
25 | if (x.left != null) {
26 | sb.append("(");
27 | pro(x.left, sb);
28 | sb.append(")");
29 | }
30 | if (x.left == null && x.right != null) {
31 | sb.append("(");
32 | sb.append(")");
33 | }
34 | if (x.right != null) {
35 | sb.append("(");
36 | pro(x.right, sb);
37 | sb.append(")");
38 | }
39 |
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/problems/easy/ContainsDuplicate.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Created by sherxon on 2016-12-30.
8 | */
9 | public class ContainsDuplicate {
10 | /**
11 | * In iteration of array We keep track of elements and in each iteration we need to check if this elements is
12 | * met already.
13 | * */
14 | public boolean containsDuplicate(int[] nums) {
15 | Set set = new HashSet<>();
16 | for (int i : nums) {
17 | if (!set.add(i)) return true;
18 | }
19 | return false;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/problems/easy/ConverstBSTtoGreaterTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Why Did you create this class? what does it do?
7 | */
8 | public class ConverstBSTtoGreaterTree {
9 | int sum = 0;
10 |
11 | public TreeNode convertBST(TreeNode root) {
12 | if (root == null)
13 | return root;
14 | go(root);
15 | return root;
16 | }
17 |
18 | int go(TreeNode x) {
19 | if (x == null)
20 | return 0;
21 | int right = go(x.right);
22 | sum += x.val;
23 | x.val = sum;
24 | int left = go(x.left);
25 | return x.val;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/easy/ConvertaNumbertoHexadecimal.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/6/17.
5 | */
6 | public class ConvertaNumbertoHexadecimal {
7 | public static void main(String[] args) {
8 | int n=0;
9 | String s=convert(n);
10 | System.out.println(Integer.toHexString(n));
11 | System.out.println(s);
12 | }
13 |
14 | private static String convert(int i) {
15 | StringBuilder builder= new StringBuilder();
16 | if(i<0){
17 |
18 | }else{
19 | while (i!=0){
20 | builder.insert(0, Integer.toHexString(i % 16));
21 | i/=16;
22 | }
23 | }
24 | return builder.toString();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/easy/CountAndSay.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/16/17.
5 | */
6 | public class CountAndSay {
7 | /**
8 | * We build the count and say sequence starting from 1.
9 | */
10 | public static String countAndSay(int n) {
11 | if(n == 1) return "1";
12 | else if(n == 2) return "11";
13 | StringBuilder sb= new StringBuilder("11");
14 | for(int i=3; i<=n; i++){
15 | char[] a=sb.toString().toCharArray();
16 | sb.setLength(0);
17 | char current=a[0];
18 | int count=0;
19 | for(int j=0; j map = new HashMap<>();
13 | int max = 0;
14 |
15 | public int diameterOfBinaryTree(TreeNode root) {
16 | if (root == null) return 0;
17 | int hl = height(root.left);
18 | int hr = height(root.right);
19 | max = Math.max(hl + hr + 2, max);
20 | if (hl > hr)
21 | diameterOfBinaryTree(root.left);
22 | else if (hl < hr)
23 | diameterOfBinaryTree(root.right);
24 | return max;
25 | }
26 |
27 | int height(TreeNode x) {
28 | if (x == null) return -1;
29 | int left = map.getOrDefault(x.left, height(x.left));
30 | int right = map.getOrDefault(x.right, height(x.right));
31 | map.put(x, Math.max(left, right) + 1);
32 | return map.get(x);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/easy/FindAllNumbersDisappearedinanArray.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.List;
4 | import java.util.stream.Collectors;
5 | import java.util.stream.IntStream;
6 |
7 | /**
8 | * Created by sherxon on 2016-12-30.
9 | */
10 | public class FindAllNumbersDisappearedinanArray {
11 | public List findDisappearedNumbers(int[] nums) {
12 | int[] a= new int[nums.length+1];
13 | for (int i = 0; i < nums.length; i++)
14 | a[nums[i]]=1;
15 | return IntStream.range(1, a.length).filter(i->a[i]==0).boxed().collect(Collectors.toList());
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/problems/easy/FindPivotIndex.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class FindPivotIndex {
7 | public int pivotIndex(int[] nums) {
8 | if (nums == null || nums.length == 0)
9 | return -1;
10 | int[] reverse = new int[nums.length];
11 | reverse[0] = nums[0];
12 | for (int i = 1; i < nums.length; i++) {
13 | reverse[i] = nums[i];
14 | nums[i] += nums[i - 1];
15 | }
16 | for (int i = nums.length - 2; i >= 0; i--) {
17 | reverse[i] += reverse[i + 1];
18 | }
19 | for (int i = 0; i < nums.length; i++) {
20 | if (reverse[i] == nums[i])
21 | return i;
22 | }
23 |
24 | return -1;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/easy/FindSmallestLetterGreaterThanTarget.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class FindSmallestLetterGreaterThanTarget {
7 | public static void main(String[] args) {
8 | System.out.println(nextGreatestLetter(new char[] {
9 | 'a', 'b'
10 | }, 'z'));
11 | }
12 |
13 | static public char nextGreatestLetter(char[] letters, char target) {
14 | int[] a = new int[26];
15 | int min = 0;
16 | for (int i = 0; i < letters.length; i++) {
17 | a[letters[i] - 'a']++;
18 | }
19 | for (int i = target - 'a' + 1; i < a.length; i++) {
20 | if (a[i] != 0)
21 | return (char) (i + 'a');
22 | }
23 | for (int i = 0; i < a.length; i++) {
24 | if (a[i] != 0)
25 | return (char) (i + 'a');
26 | }
27 | return '0';
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/easy/FindSumOfALlLeftLeavesBT.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 5/21/17.
7 | */
8 | public class FindSumOfALlLeftLeavesBT {
9 |
10 | public int sumOfLeftLeaves(TreeNode root) {
11 | if (root == null) {
12 | return 0;
13 | }
14 | return sum(root, root);
15 | }
16 |
17 | private int sum(TreeNode root, TreeNode child) {
18 | if (child == null) {
19 | return 0;
20 | }
21 | if (child.left == null && child.right == null && child == root.left) {
22 | return child.val;
23 | }
24 | return sum(child, child.left) + sum(child, child.right);
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/easy/FindtheDifference389.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-23.
5 | */
6 | public class FindtheDifference389 {
7 | public static void main(String[] args) {
8 | System.out.println(new FindtheDifference389().findTheDifference("aad", "aadt"));
9 | }
10 |
11 | public char findTheDifference(String s, String t) {
12 | int sum1=0;
13 | int sum2=0;
14 | for (char c : s.toCharArray()) {
15 | sum1+=c;
16 | }
17 | for (char c : t.toCharArray()) {
18 | sum2+=c;
19 | }
20 | return (char)(sum2-sum1);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/problems/easy/FirstUniqueCharacterinaString.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by sherxon on 1/1/17.
8 | */
9 | public class FirstUniqueCharacterinaString {
10 | public int firstUniqChar(String s) {
11 | char[] a=s.toCharArray();
12 | Map map= new HashMap<>();
13 | for(char c: a){
14 | if(map.containsKey(c))map.put(c, false);
15 | else map.put(c, true);
16 | }
17 |
18 | for(int i=0; i=2;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/easy/FizzBuzz.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by sherxon on 2016-12-23.
8 | */
9 | public class FizzBuzz {
10 | public List fizzBuzz(int n) {
11 | List list= new ArrayList<>(n);
12 | for (int i = 1; i <= n; i++) {
13 | if(i%3==0 && i%5==0)list.add("FizzBuzz");
14 | else if (i%3==0)list.add("Fizz");
15 | else if(i%5==0)list.add("Buzz");
16 | else list.add(String.valueOf(i));
17 | }
18 | return list;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/problems/easy/FlippinganImage.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class FlippinganImage {
7 | public int[][] flipAndInvertImage(int[][] a) {
8 | if (a == null || a.length == 0)
9 | return a;
10 | for (int i = 0; i < a.length; i++) {
11 | rinvert(a, i);
12 | }
13 | return a;
14 | }
15 |
16 | void rinvert(int[][] a, int i) {
17 | int ii = 0;
18 | int jj = a[i].length - 1;
19 | int[] c = a[i];
20 | while (ii < jj) {
21 | int temp = c[ii];
22 | c[ii] = c[jj];
23 | c[jj] = temp;
24 | ii++;
25 | jj--;
26 | }
27 | for (int k = 0; k < c.length; k++) {
28 | c[k] = c[k] == 1 ? 0 : 1;
29 | }
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/easy/GuessNumberHigherorLower.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-29.
5 | */
6 | public class GuessNumberHigherorLower {
7 | public int guessNumber(int n) {
8 | int i=1;
9 | int j=n;
10 | while(i<=j){
11 | int mid=i+(j-i)/2;
12 | int g=guess(mid);
13 | if(g==0)return mid;
14 | else if(g==1)i=mid+1;
15 | else j=mid-1;
16 | }
17 | return -1;
18 | }
19 |
20 | private int guess(int mid) {
21 | return 1;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/problems/easy/HammingDistance.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-23.
5 | */
6 | public class HammingDistance {
7 | public static int hammingDistance(int x,int y){
8 | return Integer.bitCount(x^y);
9 | }
10 |
11 | public int hammingDistance2(int x, int y) {
12 |
13 | String xs=Integer.toBinaryString(x);
14 | String ys=Integer.toBinaryString(y);
15 | String s1=makeBinary(xs, Math.max(xs.length(), ys.length()));
16 | String s2=makeBinary(ys, Math.max(xs.length(), ys.length()));
17 | int count=0;
18 | for (int i = 0; i < s1.length(); i++) {
19 | if(s1.charAt(i)!=s2.charAt(i))count++;
20 | }
21 | return count;
22 | }
23 | private String makeBinary(String xs, int max) {
24 | StringBuilder s=new StringBuilder(xs);
25 | while (s.length() set = new HashSet<>();
12 | while (n != 1) {
13 | int sum = 0;
14 | while (n != 0) {
15 | sum += Math.pow(n % 10, 2);
16 | n /= 10;
17 | }
18 | if (set.contains(sum)) return false;
19 | set.add(sum);
20 | n = sum;
21 |
22 | }
23 |
24 | return true;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/easy/HouseRobber.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-29.
5 | */
6 | public class HouseRobber {
7 | public int rob(int[] a) {
8 | if(a==null || a.length==0)return 0;
9 | if(a.length==1) return a[0];
10 | a[1]=Math.max(a[0], a[1]);
11 | for(int i=2; i map=new HashMap<>();
14 | List list= new ArrayList<>();
15 | for(int i=0; i0){
22 | list.add(i);
23 | map.put(i, map.get(i)-1);
24 | }
25 | }
26 | int[] aa=new int[list.size()];
27 | int ii=0;
28 |
29 | for(Integer intr:list)
30 | aa[ii++]=intr;
31 | return aa;
32 |
33 |
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/problems/easy/IntersectionOfTwoArrays.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Created by sherxon on 2016-12-27.
8 | */
9 | public class IntersectionOfTwoArrays {
10 | public int[] intersection(int[] nums1, int[] nums2) {
11 |
12 | Set set=new HashSet<>();
13 |
14 | for(int i:nums1)
15 | if(!set.contains(i))set.add(i);
16 | Set set2=new HashSet<>();
17 | for(int i:nums2)
18 | if(set.contains(i))set2.add(i);
19 | int[] a= new int[set2.size()];
20 | int i=0;
21 | for(Integer inte: set2){
22 | a[i++]=inte;
23 | }
24 | return a;
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/easy/InvertBinaryTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.LinkedList;
6 | import java.util.Queue;
7 |
8 | /**
9 | * Created by sherxon on 2016-12-24.
10 | */
11 | public class InvertBinaryTree {
12 | public TreeNode invertTree(TreeNode root) {
13 | if(root == null)return null;
14 | swap(root);
15 | invertTree(root.left);
16 | invertTree(root.right);
17 | return root;
18 | }
19 | public void swap(TreeNode x){
20 | TreeNode temp=x.left;
21 | x.left=x.right;
22 | x.right=temp;
23 | }
24 | public void invertIterative(TreeNode node){
25 |
26 | Queue q= new LinkedList<>();
27 | q.add(node);
28 | while (!q.isEmpty()){
29 | TreeNode x=q.poll();
30 | swap(x);
31 | if(x.left!=null)q.add(x.left);
32 | if(x.right!=null)q.add(x.right);
33 |
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/problems/easy/IslandPerimeter.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-30.
5 | */
6 | public class IslandPerimeter {
7 | public int islandPerimeter(int[][] a) {
8 | int p=0;
9 | for(int i=0; i0 && a[i][j-1]==1)p--;
14 | if(j0 && a[i-1][j]==1)p--;
16 | if(i map=new HashMap<>();
14 | Map map2=new HashMap<>();
15 | for(int i=0; i= max) {
20 | maxi = i;
21 | max = a[i];
22 | } else if (a[i] < min) {
23 | mini = i;
24 | min = a[i];
25 | if (mini > maxi) {
26 | max = a[i];
27 | maxi = mini;
28 | }
29 | }
30 | sum = Math.max(max - min, sum);
31 | }
32 |
33 | return sum;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/problems/easy/LemonadeChange.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class LemonadeChange {
7 | public boolean lemonadeChange(int[] bills) {
8 | int[] a = new int[3];
9 | for (int i = 0; i < bills.length; i++) {
10 | if (bills[i] == 5) {
11 | a[0]++;
12 | continue;
13 | } else if (bills[i] == 10) {
14 | a[1]++;
15 | a[0]--;
16 | if (a[0] < 0)
17 | return false;
18 | } else {
19 | a[2]++;
20 | if (a[0] < 1)
21 | return false;
22 | a[0]--;
23 | if (a[1] > 0) {
24 | a[1]--;
25 | } else {
26 | a[0] -= 2;
27 | if (a[0] < 0)
28 | return false;
29 | }
30 | }
31 | }
32 | return true;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/easy/LengthofLastWord.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/22/17.
5 | */
6 | public class LengthofLastWord {
7 | public int lengthOfLastWord(String s) {
8 | if (s == null || s.length() == 0) return 0;
9 | s = s.trim();
10 | for (int i = s.length() - 1; i >= 0; i--) {
11 | if (s.charAt(i) == ' ') return s.length() - i - 1;
12 | }
13 | return s.length();
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/problems/easy/LongestCommonPrefix.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/29/17.
5 | */
6 |
7 | /**
8 | * Write a function to find the longest common prefix string amongst an array of strings.
9 | */
10 | public class LongestCommonPrefix {
11 |
12 | /**
13 | * Simple approach to compare first, second, ... elements of every element in array with first element.
14 | * if any string with not equal character found, return prefix.
15 | */
16 | static String longestCommonPrefix(String[] strs) {
17 | if (strs.length == 0) return "";
18 | if (strs.length == 1) return strs[0];
19 |
20 | int len = strs[0].length();
21 | int i = 0;
22 | for (; i < len; i++) {
23 |
24 | for (int j = 1; j < strs.length; j++) {
25 | if (i == strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i))
26 | return strs[0].substring(0, i);
27 | }
28 | }
29 | return strs[0].substring(0, i);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/problems/easy/LongestContinuousIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class LongestContinuousIncreasingSubsequence {
7 | public int findLengthOfLCIS(int[] nums) {
8 | int count=0;
9 | if(nums==null || nums.length<=1)
10 | return nums.length;
11 |
12 | int c=1;
13 | for(int j=1; j q.val && root.val > p.val)
12 | return lowestCommonAncestor(root.left, p, q);
13 | else if (root.val < q.val && root.val < p.val)
14 | return lowestCommonAncestor(root.right, p, q);
15 | else
16 | return root;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/problems/easy/MajorityElement.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-30.
5 | */
6 | // 1) using soring, 2) using quick select 3) given below
7 | public class MajorityElement {
8 | public int majorityElement(int[] a) {
9 | // Arrays.sort(a);
10 | // return a[a.length/2];
11 | int m=a[0];
12 | int count=0;
13 | for(int i=0; i= a.length || i < 0 || j >= a[i].length || j < 0)
23 | return 0;
24 | if (a[i][j] == 0)
25 | return 0;
26 | a[i][j] = 0;
27 | return count(a, i + 1, j) + count(a, i - 1, j) + count(a, i, j + 1) + count(a, i, j - 1) + 1;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/easy/MaxConsecutiveZeros.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/14/17.
5 | */
6 | public class MaxConsecutiveZeros {
7 | int findMaxConsecutiveOnes(int[] a) {
8 | int max = 0;
9 | int counter = 0;
10 | for (int i = 0; i < a.length; i++) {
11 | if (a[i] == 1) {
12 | counter++;
13 | max = Math.max(counter, max);
14 | } else
15 | counter = 0;
16 | }
17 | return max;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/problems/easy/MaximizeDistancetoClosestPerson.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class MaximizeDistancetoClosestPerson {
7 | public int maxDistToClosest(int[] a) {
8 | int result = 0;
9 | int count = 0;
10 | int firstZeros = 0;
11 | for (int i = 0; i < a.length; i++) {
12 | if (a[i] == 0) {
13 | count++;
14 | } else {
15 | result = Math.max(result, count / 2 + count % 2);
16 | if (firstZeros == 0 && a[0] == 0)
17 | firstZeros = count;
18 | count = 0;
19 | }
20 | }
21 | int r = 0;
22 | r += (a[0] < a[1] ? 1 : 0);
23 | return Math.max(Math.max(result, firstZeros), count);
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/easy/MaximumDepthofBinaryTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-24.
7 | */
8 |
9 | /**
10 | * Given Binary Tree, return maximum depth of binary tree.
11 | */
12 | public class MaximumDepthofBinaryTree {
13 | /**
14 | * Find height of both left and right subtree and return max of them plus one
15 | */
16 | public int maxDepth(TreeNode root) {
17 | if (root == null) return 0;
18 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
19 | }
20 |
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/problems/easy/MergeSortedArray.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-27.
5 | */
6 | public class MergeSortedArray {
7 | public void merge(int[] a, int m, int[] b, int n) {
8 | if(a.length==0 || b.length==0)return;
9 | int i=m-1; int j=n-1; int k=m+n-1;
10 | while(i>=0 && j>=0 )a[k--]=a[i] > b[j] ? a[i--] : b[j--];
11 | while(j>=0) a[k--]=b[j--];
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/problems/easy/MiddleoftheLinkedList.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.ListNode;
4 |
5 | /**
6 | * Why Did you create this class? what does it do?
7 | */
8 | public class MiddleoftheLinkedList {
9 | public ListNode middleNode(ListNode x) {
10 | if (x == null || x.next == null)
11 | return x;
12 | int c = 0;
13 | ListNode y = x;
14 | while (y != null) {
15 | c++;
16 | y = y.next;
17 | }
18 | int mid = c / 2;
19 | int i = 0;
20 | while (i < mid) {
21 | i++;
22 | x = x.next;
23 | }
24 | return x;
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/easy/MinCostClimbingStairs.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class MinCostClimbingStairs {
7 |
8 | public int minCostClimbingStairs(int[] cost) {
9 | if (cost == null || cost.length == 0)
10 | return 0;
11 |
12 | for (int i = 2; i < cost.length; i++) {
13 | cost[i] += Math.min(cost[i - 1], cost[i - 2]);
14 | }
15 | return Math.min(cost[cost.length - 1], cost[cost.length - 2]);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/problems/easy/MinStack.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-29.
7 | */
8 | public class MinStack {
9 | private Stack stack;
10 | private Stack min;
11 |
12 | /** initialize your data structure here. */
13 |
14 | public MinStack() {
15 | stack = new Stack<>();
16 | min = new Stack<>();
17 | }
18 |
19 | public void push(int x) {
20 | stack.push(x);
21 | if (min.isEmpty() || x <= min.peek())
22 | min.push(x);
23 | }
24 |
25 | public void pop() {
26 | int p = stack.pop();
27 | if (min.peek() == p)
28 | min.pop();
29 |
30 | }
31 |
32 | public int top() {
33 | return stack.peek();
34 | }
35 |
36 | public int getMin() {
37 | return min.peek();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/problems/easy/MinimumAbsoluteDifferenceinBST.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 2/26/17.
7 | */
8 | public class MinimumAbsoluteDifferenceinBST {
9 | int min = Integer.MAX_VALUE;
10 | TreeNode prev = null;
11 |
12 | public int getMinimumDifference(TreeNode root) {
13 | inorder(root);
14 | return min;
15 | }
16 |
17 | void inorder(TreeNode x) {
18 | if (x == null) return;
19 | inorder(x.left);
20 | if (prev != null) {
21 | min = Math.min(min, Math.abs(prev.val - x.val));
22 | }
23 | prev = x;
24 | inorder(x.right);
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/easy/MinimumDepthofBinaryTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 |
4 | import problems.utils.TreeNode;
5 |
6 | /**
7 | * Created by sherxon on 2016-12-24.
8 | */
9 |
10 | /**
11 | * Given Binary Tree, return minimum depth of Binary Tree.
12 | */
13 | public class MinimumDepthofBinaryTree {
14 |
15 | public int minDepth(TreeNode root) {
16 | if (root == null) return 0;
17 |
18 | int left = minDepth(root.left);
19 | int right = minDepth(root.right);
20 |
21 | if (left == 0 || right == 0)
22 | return Math.max(left, right) + 1;
23 | else
24 | return Math.min(left, right) + 1;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/easy/MinimumDistanceBetweenBSTNodes.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Why Did you create this class? what does it do?
10 | */
11 | public class MinimumDistanceBetweenBSTNodes {
12 | public int minDiffInBST(TreeNode root) {
13 | List list = new ArrayList<>();
14 | go(root, list);
15 | int min = Integer.MAX_VALUE;
16 | for (int i = 1; i < list.size(); i++) {
17 | min = Math.min(min, list.get(i) - list.get(i - 1));
18 | }
19 | return min;
20 | }
21 |
22 | void go(TreeNode x, List list) {
23 | if (x == null)
24 | return;
25 | go(x.left, list);
26 | list.add(x.val);
27 | go(x.right, list);
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/easy/MinimumMovesToEqualArray.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/3/17.
5 | */
6 | //Incrementing all but one is equivalent to decrementing that one
7 | public class MinimumMovesToEqualArray {
8 | public int minMoves(int[] a) {
9 | if(a==null || a.length==0)return 0;
10 | int min=a[0];
11 | for(int i=1; i 0 && s.charAt(i) != ' ' && s.charAt(i - 1) == ' ') count++;
13 | i++;
14 | }
15 |
16 | return count + 1;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/problems/easy/PaintFill.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 5/5/17.
5 | */
6 | public class PaintFill {
7 |
8 | void paint(int[][] a, int i,int j, int color){
9 | if(a.length ==0 || a[0].length == 0)return;
10 | int orColor=a[i][j];
11 | helper(a, i, j, color, orColor);
12 | }
13 |
14 | private void helper(int[][] a, int i, int j, int color, int orColor) {
15 | if(i<0 || i>=a.length || j<0 || j>=a[i].length)return; // off limit
16 | if(a[i][j]!=orColor)return; // different color start
17 | a[i][j]=color;
18 | helper(a, i+1, j, color, orColor);
19 | helper(a, i-1, j, color, orColor);
20 | helper(a, i, j+1, color, orColor);
21 | helper(a, i, j-1, color, orColor);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/problems/easy/PalindromeNumber.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/11/17.
5 | */
6 | public class PalindromeNumber {
7 | public static void main(String[] args) {
8 | System.out.println(isPalindrome(1001));
9 | }
10 |
11 | static boolean isPalindrome(int x) {
12 | if (x == 0) return true;
13 | if (x < 0) return false;
14 | int xx = x;
15 | int m = x % 10;
16 | xx /= 10;
17 | while (xx != 0) {
18 | int rem = xx % 10;
19 | xx /= 10;
20 | m *= 10;
21 | m += rem;
22 | }
23 | return m == x;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/easy/PalindromePermutation.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * Created by sherxon on 4/28/17.
8 | */
9 | public class PalindromePermutation {
10 | /**
11 | * To be palindrome, string needs to have even number of the same characters and/or single character.
12 | * */
13 | public boolean canPermutePalindrome(String s) {
14 | if(s.length()<=1)return true;
15 | Set set= new HashSet<>();
16 |
17 | for(int i=0; i= 'A' && str.charAt(i) <= 'Z')
8 | pangram[str.charAt(i) - 'A'] = true;
9 | else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
10 | pangram[str.charAt(i) - 'a'] = true;
11 | }
12 |
13 | for (int i = 0; i < 26; i++)
14 | if (!pangram[i])
15 | return false;
16 | return true;
17 | }
18 |
19 | public static void main(String[] args) {
20 | System.out.println(isPangram("The quick brown fox jumps over the lazy dog") ? "The given string is Pangram" : "The given string is not a Pangram");
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/problems/easy/PascalsTriangle.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by sherxon on 2/17/17.
8 | */
9 | public class PascalsTriangle {
10 | public List> generate(int n) {
11 | List> list = new ArrayList<>();
12 | for (int i = 0; i < n; i++) {
13 | List l = new ArrayList<>(i);
14 | if (i == 0) {
15 | l.add(1);
16 | list.add(l);
17 | continue;
18 | }
19 | for (int j = 0; j <= i; j++) {
20 | if (j == 0 || j == i) {
21 | l.add(1);
22 | } else {
23 | l.add(list.get(i - 1).get(j) + list.get(i - 1).get(j - 1));
24 | }
25 | }
26 | list.add(l);
27 | }
28 | return list;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/easy/PascalsTriangle2.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by sherxon on 2/17/17.
8 | */
9 | public class PascalsTriangle2 {
10 | public List getRow(int n) {
11 | List list = new ArrayList<>();
12 | for (int i = 0; i <= n; i++) {
13 | List l = new ArrayList<>(i);
14 | if (i == 0) {
15 | l.add(1);
16 | } else {
17 | for (int j = 0; j <= i; j++) {
18 | if (j == 0 || j == i) {
19 | l.add(1);
20 | } else {
21 | l.add(list.get(j) + list.get(j - 1));
22 | }
23 | }
24 | }
25 | list = l;
26 | }
27 | return list;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/easy/PathSum.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-25.
7 | */
8 | public class PathSum {
9 | boolean r=false;
10 | public boolean hasPathSum(TreeNode root, int sum) {
11 | if(root==null) return false;
12 | f(root, sum, 0);
13 | return r;
14 | }
15 |
16 | void f(TreeNode x, int s, int p){
17 | if(x==null)return;
18 | x.val+=p;
19 | f(x.left, s, x.val);
20 | f(x.right, s, x.val);
21 | if(x.left==null && x.right==null && x.val==s)r=true;
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/problems/easy/PerfectNumber.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 3/25/17.
5 | */
6 | public class PerfectNumber {
7 | public static void main(String[] args) {
8 | System.out.println(checkPerfectNumber(1));
9 | }
10 |
11 | static public boolean checkPerfectNumber(int num) {
12 | if (num % 2 != 0) return false;
13 |
14 | long n = 0;
15 | int i = 1;
16 | while (n < num) {
17 | n = (long) (Math.pow(2, i) * (Math.pow(2, i + 1) - 1));
18 | i++;
19 | }
20 | return n == num;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/problems/easy/PositionsofLargeGroups.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Why Did you create this class? what does it do?
8 | */
9 | public class PositionsofLargeGroups {
10 | public List> largeGroupPositions(String s) {
11 | List> list = new ArrayList<>();
12 | if (s == null || s.length() < 3)
13 | return list;
14 |
15 | int i = 0;
16 | int j = 0;
17 | while (j <= s.length()) {
18 | if (j == s.length() || s.charAt(i) != s.charAt(j)) {
19 | if (j - i > 2) {
20 | List l = new ArrayList<>();
21 | l.add(i);
22 | l.add(j - 1);
23 | list.add(l);
24 | }
25 | i = j;
26 | }
27 | j++;
28 | }
29 | return list;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/easy/PowerOfFour.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/2/17.
5 | */
6 | public class PowerOfFour {
7 | public boolean isPowerOfFour(int n) {
8 | if(n<1)return false;
9 | if(n==1)return true;
10 | return (n & (n-1)) == 0 && ((Integer.toBinaryString(n).length()-1) %2==0 );
11 |
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/problems/easy/PowerofTwo.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/2/17.
5 | */
6 | public class PowerofTwo {
7 | public boolean isPowerOfTwo(int n) {
8 | if(n<1)return false;
9 | return (n & (n - 1)) == 0;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/problems/easy/QueuewithMinimum.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 3/28/17.
5 | */
6 |
7 | import java.io.PrintWriter;
8 | import java.util.LinkedList;
9 | import java.util.Queue;
10 |
11 | public class QueuewithMinimum {
12 | PrintWriter out;
13 | Queue queue = new LinkedList<>();
14 | LinkedList mins = new LinkedList<>();
15 |
16 | private void pop() {
17 | long last = queue.poll();
18 | if (mins.peek().compareTo(last) == 0) mins.poll();
19 | }
20 |
21 | private void min() {
22 | out.println(mins.peek());
23 | }
24 |
25 | private void push(long i) {
26 | queue.add(i);
27 | if (mins.isEmpty() || mins.peekLast().compareTo(i) <= 0)
28 | mins.add(i);
29 | else {
30 | while (!mins.isEmpty() && mins.peekLast().compareTo(i) > 0) {
31 | mins.removeLast();
32 | }
33 | mins.add(i);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/problems/easy/RangeAddition2.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 5/28/17.
5 | */
6 | public class RangeAddition2 {
7 |
8 | public int maxCount(int m, int n, int[][] ops) {
9 | if (ops == null || ops.length == 0 || ops[0].length == 0) {
10 | return m * n;
11 | }
12 | int x = ops[0][0];
13 | int y = ops[0][1];
14 | for (int[] a : ops) {
15 | x = Math.min(a[0], x);
16 | y = Math.min(a[1], y);
17 | }
18 | return x * y;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/problems/easy/RangeSumQuery.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-29.
5 | */
6 | public class RangeSumQuery {
7 | int a[];
8 | public RangeSumQuery(int[] nums) {
9 | a=nums;
10 | for(int i=1;i1->2, return 1->2.
13 | * Given 1->1->2->3->3, return 1->2->3.->3
14 | */
15 | public class RemoveDuplicatesLinkedList {
16 |
17 | public ListNode deleteDuplicates(ListNode head) {
18 | ListNode x=head;
19 | while(x!=null){
20 | if(x.next!=null && x.val==x.next.val){
21 | x.next=x.next.next;
22 | }else{
23 | x=x.next;
24 | }
25 | }
26 | return head;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/easy/RemoveElement.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-26.
5 | */
6 | public class RemoveElement {
7 | public int removeElement(int[] a, int val) {
8 | if(a.length==0)return 0;
9 | int v=0;
10 | for(int i=0; i set= new HashSet<>();
14 |
15 | String padding = "00000000000000000000000000000000"; //
16 | String result = padding + Integer.toBinaryString(n);
17 | result = result.substring(result.length() - 32, result.length()); // take the right-most 64 digits
18 |
19 | char[] a = result.toCharArray();
20 |
21 | StringBuilder sb = new StringBuilder();
22 |
23 | for (int i = a.length - 1; i >= 0; i--)
24 | sb.append(a[i]);
25 |
26 | return Integer.parseUnsignedInt(sb.toString(), 2);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/easy/ReverseInteger.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/2/17.
5 | */
6 | public class ReverseInteger {
7 | public int reverse(int x) {
8 | int ne=x<0 ? -1 : 1;
9 | x=Math.abs(x);
10 | long a=x%10;
11 | x/=10;
12 | while (x!=0){
13 | a*=10;
14 | a+=x%10;
15 | if(a < Integer.MIN_VALUE || a > Integer.MAX_VALUE)return 0;
16 | x/=10;
17 | }
18 | return Long.valueOf(a*ne).intValue();
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/problems/easy/ReverseOnlyLetters.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class ReverseOnlyLetters {
7 | public String reverseOnlyLetters(String s) {
8 | if (s == null || s.length() == 0)
9 | return s;
10 | char[] a = s.toCharArray();
11 | int i = 0;
12 | int j = a.length - 1;
13 | while (i < j) {
14 | if (!Character.isAlphabetic(a[i])) {
15 | i++;
16 | continue;
17 | }
18 | if (!Character.isAlphabetic(a[j])) {
19 | j--;
20 | continue;
21 | }
22 | char temp = a[i];
23 | a[i] = a[j];
24 | a[j] = temp;
25 | i++;
26 | j--;
27 |
28 | }
29 |
30 | return new String(a);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/problems/easy/ReverseString.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-23.
5 | */
6 |
7 | /**
8 | * Write a function that takes a string as input and returns the string reversed.
9 | */
10 |
11 | public class ReverseString {
12 | /**
13 | * The idea is to start swapping elements (a[i] with a[a.length-i])
14 | * */
15 | static public String reverseString(String s) {
16 | char[] a = s.toCharArray();
17 | int n = a.length - 1;
18 |
19 | for (int i = (n - 1) / 2; i >= 0; i--) {
20 | char temp = a[i];
21 | a[i] = a[n - i];
22 | a[n - i] = temp;
23 | }
24 | return String.valueOf(a);
25 | }
26 |
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/easy/RotateArray.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-27.
5 | */
6 |
7 | public class RotateArray {
8 |
9 | /**
10 | * The idea is simple. First we will reverse all array elements. Then do another reversion of elements
11 | * up to given kth-1 index and the of part of the array. Voila! rotated :)
12 | * Time complexity is O(N) + O(N) = O(N);
13 | * */
14 | public void rotate(int[] a, int k) {
15 | k %= a.length;
16 | reverse(a, 0, a.length - 1);
17 | reverse(a, 0, k - 1);
18 | reverse(a, k, a.length - 1);
19 | }
20 |
21 | private void reverse(int[] a, int lo, int hi) {
22 | while (lo < hi) {
23 | int temp = a[lo];
24 | a[lo] = a[hi];
25 | a[hi] = temp;
26 | lo++;
27 | hi--;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/easy/RotateString.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class RotateString {
7 |
8 | static boolean rotateString(String a, String b) {
9 | if (a == null || b == null || a.length() != b.length())
10 | return false;
11 | int c = -1;
12 | while ((c = a.indexOf(b.charAt(0), c + 1)) != -1) {
13 | String suba = a.substring(c, a.length());
14 | if (suba.equals(b.substring(0, suba.length())) &&
15 | a.substring(0, a.length() - suba.length()).equals(b.substring(suba.length(), b.length())))
16 | return true;
17 | }
18 | return false;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/problems/easy/SameTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-24.
7 | */
8 | public class SameTree {
9 | public boolean isSameTree(TreeNode p, TreeNode q) {
10 | if(p==null && q==null)return true;
11 | return q.val == p.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/problems/easy/SearchInsertPosition.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 1/11/17.
5 | */
6 | public class SearchInsertPosition {
7 | public int searchInsert(int[] a, int target) {
8 | int i = 0;
9 | int j = a.length - 1;
10 | while (i <= j) {
11 | int mid = i + (j - i) / 2;
12 | if (a[mid] == target) return mid;
13 | if (a[mid] > target) j = mid - 1;
14 | else i = mid + 1;
15 | }
16 | return i;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/problems/easy/SecondMinimumNodeInBinaryTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Why Did you create this class? what does it do?
9 | */
10 | public class SecondMinimumNodeInBinaryTree {
11 | public int findSecondMinimumValue(TreeNode root) {
12 | if(root==null || root.left==null)return -1;
13 | Queue q= new LinkedList<>();
14 | Set set= new HashSet<>();
15 | q.add(root);
16 |
17 | PriorityQueue pq= new PriorityQueue<>();
18 | while(!q.isEmpty()){
19 | TreeNode x=q.remove();
20 | if(set.add(x.val)){
21 | pq.add(x.val);
22 | }
23 |
24 | if(x.left!=null)
25 | q.add(x.left);
26 |
27 | if(x.right!=null)
28 | q.add(x.right);
29 | }
30 | if(set.size()<2)return -1;
31 | pq.remove();
32 | return pq.remove();
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/problems/easy/ShortestWordDistance.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 4/15/17.
5 | */
6 | public class ShortestWordDistance {
7 | public static void main(String[] args) {
8 | new ShortestWordDistance().shortestDistance(new String[]{"a","b","c","d","d"},"a", "d");
9 | }
10 |
11 | public int shortestDistance(String[] a, String word1, String word2) {
12 | int index1=-1;
13 | int index2=-1;
14 | int min=Integer.MAX_VALUE;
15 | for(int i=0;i 0 && a[mid] == a[mid - 1]) nei = mid - 1;
20 | else if (mid < a.length - 1 && a[mid] == a[mid + 1]) nei = mid + 1;
21 |
22 | if (mid == nei) return a[mid];
23 | int left = Math.min(mid, nei);
24 | if (left % 2 != 0) j = left - 1;
25 | else i = Math.max(nei, mid) + 1;
26 |
27 | }
28 | return -1;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/easy/SingleNumber136.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-24.
7 | */
8 | public class SingleNumber136 {
9 | public int singleNumber(int[] nums) {
10 | // Set s= new HashSet<>();
11 | // for(int i : nums){
12 | // if(s.contains(i))s.remove(i);
13 | // else s.add(i);
14 | // }
15 | // return s.iterator().next();
16 | return Arrays.stream(nums).reduce(0, (a,b)->a^b);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/problems/easy/SumofLeftLeaves.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-29.
7 | */
8 | public class SumofLeftLeaves {
9 | public int sumOfLeftLeaves(TreeNode root) {
10 | if(root == null)return 0;
11 | int ls=sumOfLeftLeaves(root.left);
12 | int rs=sumOfLeftLeaves(root.right);
13 | if(root.left!=null && root.left.left==null && root.left.right==null)
14 | ls+=root.left.val;
15 | return ls+rs;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/problems/easy/SumofTwoIntegers.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-23.
5 | */
6 | public class SumofTwoIntegers {
7 | public static void main(String[] args) {
8 | int a=1;
9 | int b=3;
10 | while (b != 0){
11 | int carry = (a & b) ; //CARRY is AND of two bits
12 |
13 | a = a ^b; //SUM of two bits is A XOR B
14 |
15 | b = carry << 1; //shifts carry to 1 bit to calculate sum
16 | }
17 |
18 | System.out.println(a);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/problems/easy/TrimBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * solution
7 | */
8 | public class TrimBinarySearchTree {
9 | public TreeNode trimBST(TreeNode root, int l, int r) {
10 | if(root==null)return null;
11 |
12 | root.left=trimBST(root.left, l, r);
13 | root.right=trimBST(root.right, l, r);
14 |
15 | if(root.val < l)
16 | return root.right;
17 | else if(root.val > r)
18 | return root.left;
19 |
20 | return root;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/problems/easy/TripleSteps.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 5/4/17.
5 | */
6 | public class TripleSteps {
7 |
8 | public static void main(String[] args) {
9 | int numberOfWays=numberOfWays(5);
10 |
11 | System.out.println(numberOfWays);
12 | }
13 |
14 | public static int numberOfWays(int n) {
15 | int[] a= new int[n+1];
16 | a[1]=1;
17 | a[2]=2;
18 | a[3]=4;
19 | if(n < 4) return a[n];
20 | for (int i = 4; i <= n; i++) {
21 | a[i]=a[i-1] + a[i-2] + a[i-3];
22 | }
23 | return a[n];
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/easy/TwoSum.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by sherxon on 2016-12-26.
8 | */
9 | public class TwoSum {
10 | public int[] twoSum(int[] a, int target) {
11 | Map map= new HashMap<>();
12 | for(int i=0; i map= new HashMap<>();
14 | go(map, root);
15 | for(Integer key : map.keySet()){
16 | int v=k-key;
17 | if(v!=key){
18 | if(map.containsKey(v))return true;
19 | }else{
20 | if(map.get(v)>1)return true;
21 | }
22 | }
23 | return false;
24 | }
25 | void go(Map map, TreeNode root){
26 | if(root==null)return;
27 | map.put(root.val, map.getOrDefault(root.val, 0)+1);
28 | go(map, root.left);
29 | go(map, root.right);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/problems/easy/UglyNumber.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-28.
5 | */
6 | public class UglyNumber {
7 | public boolean isUgly(int num) {
8 | if(num < 1)return false;
9 |
10 | while(num>1){
11 | if(num%2==0)num/=2;
12 | else if(num%3==0)num/=3;
13 | else if(num%5==0)num/=5;
14 | else return false;
15 | }
16 | return true;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/problems/easy/ValidAnagram.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-27.
5 | */
6 | public class ValidAnagram {
7 | public boolean isAnagram(String s, String t) {
8 | if (s.length() != t.length()) return false;
9 | int[] alphabet = new int[26];
10 | for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++;
11 | for (int i = 0; i < t.length(); i++) {
12 | int index = t.charAt(i) - 'a';
13 | if (alphabet[index] == 0) return false;
14 | alphabet[index]--;
15 | }
16 | return true;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/problems/easy/ValidPalindrome.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-29.
5 | */
6 | public class ValidPalindrome {
7 | public boolean isPalindrome(String s) {
8 | if(s==null || s.length()==0)return true;
9 | int i=0;
10 | int j=s.length()-1;
11 | while(i<=j){
12 | char left=s.charAt(i);
13 | char right=s.charAt(j);
14 | if(!Character.isLetterOrDigit(left))i++;
15 | else if(!Character.isLetterOrDigit(right))j--;
16 | else if(Character.toLowerCase(left)!=Character.toLowerCase(right))return false;
17 | else {
18 | i++;
19 | j--;
20 | }
21 | }
22 | return true;
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/easy/ValidParentheses.java:
--------------------------------------------------------------------------------
1 | package problems.easy;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Stack;
6 |
7 | /**
8 | * Created by sherxon on 2016-12-29.
9 | */
10 | public class ValidParentheses {
11 | public boolean isValid(String s) {
12 | char[] a= s.toCharArray();
13 | Stack stack= new Stack<>();
14 | Map map= new HashMap<>();
15 | map.put(']', '[');
16 | map.put(')', '(');
17 | map.put('}', '{');
18 | for(int i=0; i < a.length; i++){
19 | if(a[i] =='(' || a[i] == '{' || a[i] == '['){
20 | stack.add(a[i]);
21 | }else{
22 | if(stack.isEmpty() || stack.peek()!=map.get(a[i]))return false;
23 | stack.pop();
24 | }
25 |
26 | }
27 | return stack.isEmpty();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/hard/BinaryTreeMaximumPathSum.java:
--------------------------------------------------------------------------------
1 | package problems.hard;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by sherxon on 2/14/17.
10 | */
11 | public class BinaryTreeMaximumPathSum {
12 | int max = Integer.MIN_VALUE;
13 |
14 | public static void main(String[] args) {
15 | List list = new ArrayList<>();
16 |
17 | int ll = 1;
18 | System.out.println(Math.abs(2147483647 + (long) ll));
19 | }
20 |
21 | public int maxPathSum(TreeNode root) {
22 |
23 | if (root == null)
24 | return 0;
25 | find(root);
26 | return max;
27 | }
28 |
29 | int find(TreeNode x) {
30 | if (x == null)
31 | return 0;
32 |
33 | int left = Math.max(0, find(x.left));
34 | int right = Math.max(0, find(x.right));
35 |
36 | max = Math.max(max, left + right + x.val);
37 | x.val = Math.max(left, right) + x.val;
38 | return x.val;
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/problems/hard/SlidingWindowMedian.java:
--------------------------------------------------------------------------------
1 | package problems.hard;
2 |
3 | /**
4 | * Created by sherxon on 1/7/17.
5 | */
6 | public class SlidingWindowMedian {
7 | public static void main(String[] args) {
8 |
9 | }
10 |
11 | public double[] medianSlidingWindow(int[] a, int k) {
12 | double[] b= new double[a.length-k+1];
13 | int [] temp=new int[k];
14 | for (int i = 0; i < a.length; i++) {
15 |
16 | }
17 | return null;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/problems/hard/TrappingRainWater.java:
--------------------------------------------------------------------------------
1 | package problems.hard;
2 |
3 | /**
4 | * Created by sherxon on 6/10/17.
5 | */
6 | public class TrappingRainWater {
7 |
8 | public int trap(int[] height) {
9 | if (height == null || height.length == 0) {
10 | return 0;
11 | }
12 | int sum = 0;
13 | for (int i = 0; i < height.length; i++) {
14 | int x = i;
15 | int y = i;
16 | int maxL = 0;
17 | int maxR = 0;
18 | while (x >= 0 || y < height.length) {
19 | if (x >= 0) {
20 | maxL = Math.max(height[x], maxL);
21 | x--;
22 | }
23 | if (y < height.length) {
24 | maxR = Math.max(height[y], maxR);
25 | y++;
26 | }
27 | }
28 | int min = Math.min(maxL, maxR);
29 | int diff = height[i] < min ? min - height[i] : 0;
30 | sum += diff;
31 | }
32 | return sum;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/medium/AnimalShelter.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.LinkedList;
4 |
5 | /**
6 | * Created by sherxon on 5/2/17.
7 | */
8 | /**
9 | * this problem also can be solved using one linked list. however it takes the same amount of space
10 | * and much longer time.
11 | * */
12 | public class AnimalShelter {
13 | LinkedList dogs =new LinkedList<>();
14 | LinkedList cats =new LinkedList<>();
15 |
16 | void pushCat(Integer cat){
17 | cats.push(cat);
18 | }
19 | void pushDog(Integer dog){
20 | cats.push(dog);
21 | }
22 | void popDog(Integer dog){
23 | dogs.pollFirst();
24 | }
25 | void popCat(Integer cat){
26 | cats.pollFirst();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/medium/ArrayNesting.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 5/28/17.
5 | */
6 | public class ArrayNesting {
7 |
8 | public int arrayNesting(int[] nums) {
9 | if (nums == null || nums.length == 0)
10 | return 0;
11 |
12 | boolean[] a = new boolean[nums.length];
13 | int max = 0;
14 | for (int i = 0; i < a.length; i++) {
15 | int j = i;
16 | int k = 0;
17 | while (!a[j]) {
18 | a[j] = true;
19 | j = nums[j];
20 | k++;
21 | }
22 | max = Math.max(k, max);
23 | }
24 | return max;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/medium/BattleShipsInBoard.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/11/17.
5 | */
6 | public class BattleShipsInBoard {
7 | public int countBattleships(char[][] a) {
8 | int counter = 0;
9 | for (int i = 0; i < a.length; i++) {
10 | for (int j = 0; j < a[i].length; j++) {
11 | if (a[i][j] == 'X' && j == a[i].length - 1 && i == a.length - 1) counter++;
12 | if (a[i][j] == 'X' && j == a[i].length - 1 && i < a.length - 1 && a[i + 1][j] == '.') counter++;
13 | if (a[i][j] == 'X' && j < a[i].length - 1 && i < a.length - 1 && a[i + 1][j] == '.' && a[i][j + 1] == '.')
14 | counter++;
15 | if (a[i][j] == 'X' && j < a[i].length - 1 && i == a.length - 1 && a[i][j + 1] == '.') counter++;
16 | }
17 | }
18 | return counter;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/problems/medium/BinarySearchTreeIterator.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.Stack;
6 |
7 | /**
8 | * Created by sherxon on 1/4/17.
9 | */
10 | public class BinarySearchTreeIterator {
11 | Stack stack;
12 |
13 | public BinarySearchTreeIterator(TreeNode root) {
14 | stack = new Stack<>();
15 | add(root);
16 |
17 | }
18 |
19 | /**
20 | * @return whether we have a next smallest number
21 | */
22 | public boolean hasNext() {
23 | return stack.size() > 1;
24 | }
25 |
26 | /**
27 | * @return the next smallest number
28 | */
29 | public int next() {
30 | TreeNode pop = stack.pop();
31 | add(pop.right);
32 | return pop.val;
33 | }
34 |
35 | void add(TreeNode x) {
36 | while (x != null) {
37 | stack.add(x);
38 | x = x.left;
39 | }
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/problems/medium/BinaryTreeLeftSIdeView.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by sherxon on 1/22/17.
10 | */
11 | public class BinaryTreeLeftSIdeView {
12 | public List rightSideView(TreeNode root) {
13 | List list = new ArrayList<>();
14 | if (root == null) return list;
15 | findRec(root, list, 0);
16 | return list;
17 | }
18 |
19 | private void findRec(TreeNode root, List list, int i) {
20 | if (root == null) return;
21 | if (list.size() == i) list.add(root.val);
22 | findRec(root.left, list, i + 1);
23 | findRec(root.right, list, i + 1);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/medium/BinaryTreePreorderTraversal.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.List;
6 | import java.util.Stack;
7 |
8 | /**
9 | * Created by sherxon on 1/3/17.
10 | */
11 | public class BinaryTreePreorderTraversal {
12 | private void preOrderIterative(TreeNode x, List list) {
13 | Stack stack=new Stack<>();
14 | stack.add(x);
15 | while (!stack.isEmpty()){
16 | TreeNode treeNode=stack.pop();
17 | list.add(treeNode.val);
18 | if(treeNode.right!=null)
19 | stack.add(treeNode.right);
20 | if(treeNode.left!=null)
21 | stack.add(treeNode.left);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/problems/medium/BinaryTreePruning.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Why Did you create this class? what does it do?
7 | */
8 | public class BinaryTreePruning {
9 | public TreeNode pruneTree(TreeNode root) {
10 | if (root == null)
11 | return root;
12 | if (prune(root) && root.val == 0) {
13 | return null;
14 | }
15 | return root;
16 | }
17 |
18 | boolean prune(TreeNode x) {
19 | if (x == null)
20 | return true;
21 | boolean l = prune(x.left);
22 | boolean r = prune(x.right);
23 | if (l)
24 | x.left = null;
25 | if (r)
26 | x.right = null;
27 | return x.val == 0 && x.right == null && x.left == null;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/medium/BoatstoSavePeople.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Why Did you create this class? what does it do?
7 | */
8 | public class BoatstoSavePeople {
9 | public int numRescueBoats(int[] people, int limit) {
10 | if (people == null || people.length == 0)
11 | return 0;
12 | if (people.length == 1)
13 | return 1;
14 | Arrays.sort(people);
15 | int i = 0;
16 | int j = people.length - 1;
17 | int c = 0;
18 | while (i <= j) {
19 | if (people[i] + people[j] <= limit) {
20 | i++;
21 | }
22 | j--;
23 | c++;
24 | }
25 | return c;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/medium/CloneGraph.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.UndirectedGraphNode;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /**
9 | * Created by sherxon on 1/5/17.
10 | */
11 | public class CloneGraph {
12 |
13 | Map map=new HashMap<>();
14 | public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
15 | return cloneG(node);
16 | }
17 |
18 | private UndirectedGraphNode cloneG(UndirectedGraphNode node) {
19 | if(node==null)return null;
20 | if(map.containsKey(node.label))
21 | return map.get(node.label);
22 |
23 | UndirectedGraphNode nn= new UndirectedGraphNode(node.label);
24 | map.put(nn.label, nn);
25 | for (UndirectedGraphNode neighbor : node.neighbors) {
26 | UndirectedGraphNode clone=cloneG(neighbor);
27 | nn.neighbors.add(clone);
28 | }
29 | return nn;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/medium/CoinChange2.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * @author Sherali Obidov.
7 | */
8 | public class CoinChange2 {
9 |
10 | int counter=0;
11 | public int change(int amount, int[] coins) {
12 | if(amount <0 || coins==null)return 0;
13 | if(amount==0 && coins.length==0)return 1;
14 | go(amount, coins, 0);
15 | return counter;
16 | }
17 | void go(int amount, int[] coins, int j){
18 | if(j>coins.length || amount<0)return;
19 | if(amount==0){
20 | counter++;
21 | return;
22 | }
23 |
24 | for(int i=j; i a[l]) {
19 | l++;
20 | } else {
21 | r--;
22 | }
23 | }
24 | return max;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/medium/ContinuousSubarraySum.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 2/26/17.
5 | */
6 | public class ContinuousSubarraySum {
7 | public boolean checkSubarraySum(int[] a, int k) {
8 | if (a.length == 0) return false;
9 | if (k == 0) {
10 | for (int i = 1; i < a.length; i++) {
11 | a[i] += a[i - 1];
12 | if (a[i] == 0) return true;
13 | }
14 | } else {
15 | for (int i = 1; i < a.length; i++) {
16 | a[i] += a[i - 1];
17 | if (a[i] % k == 0) return true;
18 | }
19 | for (int i = 0; i < a.length; i++) {
20 | for (int j = i + 2; j < a.length; j++) {
21 | if ((a[j] - a[i]) % k == 0) return true;
22 | }
23 | }
24 | }
25 |
26 | return false;
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/medium/ConvertBSTToGreaterTree.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 3/19/17.
7 | */
8 | public class ConvertBSTToGreaterTree {
9 | public TreeNode convertBST(TreeNode root) {
10 | if (root == null) return null;
11 | f(root, 0);
12 | return root;
13 | }
14 |
15 | int f(TreeNode root, int val) {
16 | if (root == null) return val;
17 | int r = f(root.right, val);
18 | root.val = r + root.val;
19 | return f(root.left, root.val);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/problems/medium/ConvertSortedArraytoBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 1/5/17.
7 | */
8 | public class ConvertSortedArraytoBinarySearchTree {
9 | /**
10 | * As an array is sorted, we can find root of array by finding middle element in constant time.
11 | * then divide both left and right parts of array and apply the method again to find root of subtrees
12 | */
13 | public TreeNode sortedArrayToBST(int[] a) {
14 | if (a.length == 0) return null;
15 | return helper(a, 0, a.length - 1);
16 | }
17 |
18 | private TreeNode helper(int[] a, int lo, int hi) {
19 | if (lo > hi) return null;
20 | int mid = lo + (hi - lo) / 2;
21 | TreeNode head = new TreeNode(a[mid]);
22 | head.left = helper(a, lo, mid - 1);
23 | head.right = helper(a, mid + 1, hi);
24 | return head;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/medium/CountCompleteBinarytree.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-29.
7 | */
8 | public class CountCompleteBinarytree {
9 | public int countNodes(TreeNode x) {
10 | if(x==null)return 0;
11 | int l=leftsize(x.left);
12 | int r=rightsize(x.right);
13 | if(l==r) return (1< list= new ArrayList<>();
13 | Map map= new HashMap<>();
14 |
15 | // Encodes a URL to a shortened URL.
16 | public String encode(String longUrl) {
17 | if(longUrl == null || longUrl.length()==0) return longUrl;
18 | if(map.containsKey(longUrl))return map.get(longUrl);
19 |
20 | String su=String.valueOf(list.size());
21 |
22 | map.put(longUrl, su);
23 |
24 | list.add(longUrl);
25 | return su;
26 | }
27 |
28 | // Decodes a shortened URL to its original URL.
29 | public String decode(String shortUrl) {
30 | if(shortUrl==null || shortUrl.length()==0)
31 | return shortUrl;
32 | return list.get(Integer.parseInt(shortUrl));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/medium/EqualTreePartition.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /**
9 | * @author Sherali Obidov.
10 | */
11 | public class EqualTreePartition {
12 | Map map= new HashMap<>();
13 | int total=0;
14 | public boolean checkEqualTree(TreeNode root) {
15 | if(root==null || (root.left==null && root.right==null))return false;
16 | total=sum(root);
17 | return go(root);
18 | }
19 |
20 | boolean go(TreeNode root){
21 | if(root==null)return false;
22 | if(total==map.get(root)*2)return true;
23 | return go(root.left) || go(root.right);
24 | }
25 | int sum(TreeNode root){
26 | if(root==null)return 0;
27 | Integer l=map.get(root.left);
28 | Integer r=map.get(root.right);
29 | if(l==null)l=sum(root.left);
30 | if(r==null)r=sum(root.right);
31 | map.put(root, l+r+root.val);
32 | return l+r+root.val;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/medium/FindAllDuplicatesinanArray.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by sherxon on 1/5/17.
8 | */
9 |
10 | public class FindAllDuplicatesinanArray {
11 |
12 | /**
13 | * This find all duplicate elements from array. The idea is to negate previous elements. if the previous element
14 | * is already negative this element is duplicate. Time complexity is O(N) and in-place.
15 | */
16 | public List findDuplicates(int[] a) {
17 |
18 | List list = new ArrayList<>();
19 |
20 | for (int i = 0; i < a.length; ++i) {
21 | int index = Math.abs(a[i]) - 1;
22 | if (a[index] < 0)
23 | list.add(index + 1);
24 | a[index] *= -1;
25 | }
26 | return list;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/medium/FindDuplicateSubtrees.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.List;
8 | import java.util.Map;
9 |
10 | /**
11 | * @author Sherali Obidov.
12 | */
13 | public class FindDuplicateSubtrees {
14 | public List findDuplicateSubtrees(TreeNode root) {
15 | List list = new ArrayList<>();
16 | if(root==null) return list;
17 |
18 | Map map= new HashMap<>();
19 | postOrder(root, map, list);
20 | return list;
21 | }
22 |
23 | String postOrder(TreeNode root, Map map, List list){
24 | if(root==null)return ".";
25 | String s= root.val + "," + postOrder(root.left, map, list) + "," + "," + postOrder(root.right, map, list);
26 | if(map.getOrDefault(s, 0)==1)list.add(root);
27 | map.put(s, map.getOrDefault(s, 0)+1);
28 | return s;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/problems/medium/FindKClosestElements.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.PriorityQueue;
7 |
8 | /**
9 | * @author Sherali Obidov.
10 | */
11 | public class FindKClosestElements {
12 |
13 | public List findClosestElements(List arr, int k, int x) {
14 | List list= new ArrayList<>();
15 | if(arr==null || arr.size()==0 || k==0)return list;
16 |
17 | PriorityQueue q= new PriorityQueue<>((a, b)-> {
18 | int d= (Math.abs(x-a))-(Math.abs(x-b));
19 | if(d==0)return a-b;
20 | return d;
21 | });
22 | q.addAll(arr);
23 | if(q.size() list=new LinkedList<>();
22 | find(root, list, 0);
23 | return list.getLast();
24 |
25 | }
26 | void find(TreeNode x, List list, int level){
27 | if(x==null)return;
28 | if(list.size()==level)list.add(x.val);
29 | find(x.left, list, level+1);
30 | find(x.right, list, level+1);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/medium/FindMinimuminRotatedSortedArray.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-30.
5 | */
6 | public class FindMinimuminRotatedSortedArray {
7 | public static void main(String[] args) {
8 | System.out.println(new FindMinimuminRotatedSortedArray().findMin(
9 | //new int[]{6,7,1,2,3,4,5}
10 | new int[]{4 ,5 ,6 ,7 ,0, 1, 2}
11 | //new int[]{3,4,5,6,7,1,2}
12 | ));
13 | }
14 | public int findMin(int[] a) {
15 | int i=0;
16 | int j=a.length-1;
17 | while (i<=j){
18 | int mid=i+(j-i)/2;
19 | if(i==mid || j==mid)return Math.min(a[i], Math.min(a[j], a[mid]));
20 | if(a[mid]>a[j])i=mid;
21 | else if(a[mid] 0 && mid < a.length - 1 && a[mid] >= a[mid - 1] && a[mid] >= a[mid + 1]) return mid;
19 |
20 | if (mid < a.length - 1 && a[mid] < a[mid + 1])
21 | lo = mid + 1;
22 | else
23 | hi = mid - 1;
24 | }
25 | return lo;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/medium/FindRightInterval.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.Interval;
4 |
5 | import java.util.TreeMap;
6 |
7 | /**
8 | * Created by sherxon on 1/31/17.
9 | */
10 | public class FindRightInterval {
11 |
12 | static int[] findRightInterval(Interval[] intervals) {
13 | if (intervals.length == 0) return new int[0];
14 | int[] a = new int[intervals.length];
15 | TreeMap map = new TreeMap<>();
16 | int i = 0;
17 | for (Interval interval : intervals) {
18 | map.put(interval.start, i++);
19 | }
20 | for (int ii = 0; ii < a.length; ii++) {
21 | Integer key = map.ceilingKey(intervals[ii].end);
22 | if (key == null) a[i] = -1;
23 | else a[i] = map.get(key);
24 | }
25 |
26 | return a;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/medium/FourSumII.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by sherxon on 1/13/17.
8 | * Time complexity: O(n^2)
9 | * Space complexity: O(n^2)
10 | */
11 |
12 | public class FourSumII {
13 | public int fourSumCount(int[] a, int[] b, int[] c, int[] d) {
14 | Map map = new HashMap<>();
15 | for (int i = 0; i < a.length; i++)
16 | for (int j = 0; j < b.length; j++)
17 | if (!map.containsKey(a[i] + b[j]))
18 | map.put(a[i] + b[j], 1);
19 | else
20 | map.put(a[i] + b[j], map.get(a[i] + b[j]) + 1);
21 |
22 | int counter = 0;
23 | for (int i = 0; i < c.length; i++)
24 | for (int j = 0; j < d.length; j++) {
25 | int target = 0 - (c[i] + d[j]);
26 | if (map.containsKey(target))
27 | counter += map.get(target);
28 | }
29 | return counter;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/problems/medium/GasStation.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/13/17.
5 | */
6 | public class GasStation {
7 | public int canCompleteCircuit(int[] gas, int[] cost) {
8 | int totgas = 0;
9 | int totcost = 0;
10 | for (int i = 0; i < gas.length; i++) {
11 | totgas += gas[i];
12 | totcost += cost[i];
13 | }
14 | if (totgas < totcost) return -1;
15 |
16 | for (int i = 0; i < gas.length; i++) {
17 | int current = 0;
18 | int k = i;
19 | for (int j = 0; j < cost.length; j++) {
20 | int jj = k % cost.length;
21 | current += gas[jj];
22 | current -= cost[jj];
23 | if (current < 0) break;
24 | k++;
25 | }
26 | if (current >= 0) return i;
27 | if (k > i) i = k;
28 | }
29 |
30 | return -1;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/medium/HIndex.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-31.
7 | */
8 | public class HIndex {
9 | // O(NlgN) solution
10 | public int hIndex(int[] a) {
11 | if(a==null || a.length==0)return 0;
12 | if(a.length==1 && a[0]==0)return 0;
13 | Arrays.sort(a);
14 | int max=0;
15 | for(int i=a.length-1; i>-1; i--){
16 | if(a[i]>max)max++;
17 | }
18 | return max;
19 | }
20 | //O(N) solution
21 | public int hIndex2(int[] a){
22 | int max=0;
23 | int b[] = new int[a.length+1];
24 | for (int i = 0; i < a.length; i++) {
25 | if(a[i]>=b.length)b[b.length-1]++;
26 | else b[a[i]]++;
27 | }
28 | for (int i = b.length-2; i >=0; i--)
29 | b[i]+=b[i+1];
30 | for (int i = b.length-1; i >=0; i--){
31 | if(b[i]>=i){
32 | return i;
33 | }
34 | }
35 |
36 | return max;
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/problems/medium/HandofStraights.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.TreeMap;
4 |
5 | /**
6 | * Why Did you create this class? what does it do?
7 | */
8 | public class HandofStraights {
9 | public boolean isNStraightHand(int[] a, int w) {
10 | if (a == null || w < 0)
11 | return false;
12 | if (a.length % w != 0)
13 | return false;
14 |
15 | TreeMap map = new TreeMap<>();
16 | for (int i = 0; i < a.length; i++) {
17 | map.put(a[i], map.getOrDefault(a[i], 0) + 1);
18 | }
19 | while (!map.isEmpty()) {
20 | int min = map.firstKey();
21 | for (int i = min; i < w + min; i++) {
22 | Integer val = map.get(i);
23 | if (val == null)
24 | return false;
25 | if (val == 1)
26 | map.remove(i);
27 | else
28 | map.put(i, val - 1);
29 | }
30 | }
31 | return true;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/problems/medium/InsertIntoBST.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Why Did you create this class? what does it do?
7 | */
8 | public class InsertIntoBST {
9 | public TreeNode insertIntoBST(TreeNode root, int val) {
10 | if (root == null)
11 | return new TreeNode(val);
12 |
13 | if (root.val < val)
14 | root.right = insertIntoBST(root.right, val);
15 | else
16 | root.left = insertIntoBST(root.left, val);
17 | return root;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/problems/medium/InsertionSortList.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.ListNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-31.
7 | */
8 | public class InsertionSortList {
9 | public ListNode insertionSortList(ListNode head) {
10 | if(head==null)return null;
11 | if(head.next==null)return head;
12 | ListNode x=head.next;
13 | while(x!=null){
14 | sort(head, x);
15 | x=x.next;
16 | }
17 | return head;
18 | }
19 | void sort(ListNode head, ListNode x){
20 | if(head==x)return;
21 | sort(head.next, x);
22 | if(head.val>head.next.val)
23 | swap(head, head.next);
24 | }
25 | void swap(ListNode a, ListNode b){
26 | int temp=a.val;
27 | a.val=b.val;
28 | b.val=temp;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/medium/IntegerBreak.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/5/17.
5 | */
6 | public class IntegerBreak {
7 | public int integerBreak(int n) {
8 | if(n==1 || n==2)return 1;
9 | if(n==3)return 2;
10 | if(n==4)return 4;
11 | int ts=n/3;
12 | int rem=n%3;
13 | if(rem==1){
14 | rem=4;
15 | if(ts>1)
16 | ts-=1;
17 | }else if(rem==0)rem=1;
18 | int sum=(int)(Math.pow(3, ts)*rem);
19 | return sum;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/problems/medium/IsSubsequence.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/9/17.
5 | */
6 | public class IsSubsequence {
7 | public static void main(String[] args) {
8 | System.out.println(isSubsequence("", "adddfdbdfdfdciiisderefdfdfdf"));
9 | }
10 | public static boolean isSubsequence(String s, String t) {
11 | char[] a=s.toCharArray();
12 | char[] b=t.toCharArray();
13 | int i=0;
14 | for (int j = 0; j < b.length; j++) {
15 | if(i listK = new ArrayList<>();
16 | while (n > 1) {
17 | if (k > Math.pow(2, n - 2)) {
18 | k -= Math.pow(2, n - 2);
19 | listK.add(false);
20 | } else {
21 | listK.add(true);
22 | }
23 | n--;
24 | }
25 | listK.add(true);
26 | Collections.reverse(listK);
27 | boolean res = false;
28 | for (Boolean aBoolean : listK) {
29 | if (!aBoolean)
30 | res = !res;
31 | }
32 | return res ? 1 : 0;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/medium/LongestMountaininArray.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class LongestMountaininArray {
7 | public int longestMountain(int[] a) {
8 | if (a == null || a.length < 3)
9 | return 0;
10 | int max = 0;
11 | for (int i = 1; i < a.length - 1; i++) {
12 | int ii = i;
13 | int jj = i;
14 | while (jj < a.length - 1 && a[jj] > a[jj + 1]) {
15 | jj++;
16 | }
17 | while (ii > 0 && a[ii] > a[ii - 1]) {
18 | ii--;
19 | }
20 | if (ii != i && jj != i)
21 | max = Math.max(max, jj - ii);
22 | }
23 | return max == 0 ? 0 : max + 1;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/medium/LongestUnivaluePath.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Why Did you create this class? what does it do?
9 | */
10 | public class LongestUnivaluePath {
11 | int max = 0;
12 |
13 | public int longestUnivaluePath(TreeNode root) {
14 | if (root == null)
15 | return 0;
16 | dfs(root);
17 | return max;
18 | }
19 |
20 | int dfs(TreeNode root) {
21 | if (root == null)
22 | return 0;
23 | int left = dfs(root.left);
24 | int right = dfs(root.right);
25 | if (root.left != null && root.left.val == root.val)
26 | left++;
27 | else
28 | left = 0;
29 | if (root.right != null && root.right.val == root.val)
30 | right++;
31 | else
32 | right = 0;
33 | max = Math.max(max, left + right);
34 | return Math.max(left, right);
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/problems/medium/LongestWordinDictionarythroughDeleting.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | import java.util.Collections;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by sherxon on 2/26/17.
10 | */
11 | public class LongestWordinDictionarythroughDeleting {
12 | public String findLongestWord(String s, List d) {
13 | Collections.sort(d);
14 | if (s == null || s.length() == 0)
15 | return s;
16 | String r = "";
17 | for (String w : d) {
18 | if (w.length() > r.length() && canBeMade(s, w)) {
19 | r = w;
20 | }
21 | }
22 | return r;
23 | }
24 |
25 | boolean canBeMade(String s, String w) {
26 | int ind = -1;
27 | for (int i = 0; i < w.length(); i++) {
28 | ind = s.indexOf(w.charAt(i), ind + 1);
29 | if (ind < 0)
30 | return false;
31 | }
32 | return true;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/medium/MaxConsecutiveZeros2.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/14/17.
5 | */
6 | public class MaxConsecutiveZeros2 {
7 |
8 | int findMaxConsecutiveOnes2(int[] a) {
9 | int max = findMaxConsecutiveOnes(a);
10 | if (max < a.length) max += 1;
11 | for (int i = 1; i < a.length - 1; i++) {
12 | if (a[i] == 0 && a[i - 1] == 1 && a[i + 1] == 1) {
13 | a[i] = 1;
14 | int count = findMaxConsecutiveOnes(a);
15 | a[i] = 0;
16 | max = Math.max(count, max);
17 | }
18 | }
19 | return max;
20 | }
21 |
22 | int findMaxConsecutiveOnes(int[] a) {
23 | int max = 0;
24 | int counter = 0;
25 | for (int i = 0; i < a.length; i++) {
26 | if (a[i] == 1) {
27 | counter++;
28 | max = Math.max(counter, max);
29 | } else
30 | counter = 0;
31 | }
32 | return counter;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/problems/medium/MaxIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/15/17.
5 | */
6 | public class MaxIncreasingSubsequence {
7 |
8 |
9 | static int lengthOfLIS(int[] a) {
10 | if (a.length == 0) return 0;
11 | int max = 1;
12 | int[] b = new int[a.length];
13 | for (int i = 0; i < b.length; i++) b[i] = 1;
14 | for (int i = 0; i < a.length; i++) {
15 | int maxsf = 0;
16 | for (int j = i - 1; j >= 0; j--) {
17 | if (a[i] > a[j]) {
18 | maxsf = Math.max(maxsf, b[j]);
19 | }
20 | }
21 | b[i] += maxsf;
22 | max = Math.max(max, b[i]);
23 | }
24 | return max;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/medium/MaximumBinaryTree.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Definition for a binary tree node.
7 | * public class TreeNode {
8 | * int val;
9 | * TreeNode left;
10 | * TreeNode right;
11 | * TreeNode(int x) { val = x; }
12 | * }
13 | */
14 | public class MaximumBinaryTree {
15 | public TreeNode constructMaximumBinaryTree(int[] a) {
16 | if(a==null || a.length==0)return null;
17 | return go(a, 0, a.length-1);
18 | }
19 |
20 | TreeNode go(int[]a, int lo, int hi){
21 | if(lo>hi)return null;
22 | if(hi==lo)return new TreeNode(a[lo]);
23 | int max=Integer.MIN_VALUE;
24 | int maxi=0;
25 | for(int i=lo; i<=hi; i++){
26 | if(a[i]>max){
27 | max=a[i];
28 | maxi=i;
29 | }
30 | }
31 | TreeNode root= new TreeNode(a[maxi]);
32 | root.left=go(a, lo, maxi-1);
33 | root.right=go(a, maxi+1, hi);
34 | return root;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/problems/medium/MaximumSubarray.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/2/17.
5 | */
6 | public class MaximumSubarray {
7 |
8 | /**
9 | * We use two max, maxSoFar -> max sub array found so far and maxEndingHere -> maximum sub array size
10 | * that ends in this index. This is in place solution and time Complexity is O(N).
11 | * */
12 | public int maxSubArray(int[] a) {
13 |
14 | if (a == null || a.length == 0) return 0;
15 |
16 | int maxSoFar = a[0];
17 | int maxEndingHere = a[0];
18 |
19 | for (int i = 1; i < a.length; i++) {
20 | maxEndingHere = Math.max(maxEndingHere + a[i], a[i]);
21 | maxSoFar = Math.max(maxSoFar, maxEndingHere);
22 | }
23 | return maxSoFar;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/medium/MaximumSwap.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class MaximumSwap {
7 | public int maximumSwap(int num) {
8 | char[] c=String.valueOf(num).toCharArray();
9 | for(int i=0; i= max){
14 | max=(int)c[j];
15 | maxi=j;
16 | }
17 | }
18 | if(c[maxi]!=c[i]){
19 | char temp=c[maxi];
20 | c[maxi]=c[i];
21 | c[i]=temp;
22 | break;
23 | }
24 | }
25 |
26 | return Integer.parseInt(new String(c));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/medium/MetaStrings.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 4/19/17.
5 | */
6 | public class MetaStrings {
7 | public static void main(String[] args) {
8 | System.out.println(isMetaString("geeks", "keegs")); // true
9 | System.out.println(isMetaString("rsting", "string")); // false
10 | System.out.println(isMetaString("Converse", "Conserve")); //true
11 | }
12 |
13 | static boolean isMetaString(String a, String b){
14 | if(a.length()!=b.length())return false;
15 | long sum=0;
16 | long sum2=0;
17 | int diffCount=0;
18 | for (int i = 0; i < a.length(); i++) {
19 | int aa=a.charAt(i)-'a';
20 | int bb=b.charAt(i)-'a';
21 | sum+=aa;
22 | sum2+=bb;
23 | diffCount+= aa == bb ? 0 : 1;
24 | }
25 | return sum==sum2 && diffCount<=2;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/medium/MinimumPathSum.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-30.
5 | */
6 | public class MinimumPathSum {
7 | public int minPathSum(int[][] a) {
8 | if(a==null && a.length==0)return 0;
9 | for(int i=0; i0 && j>0)
12 | a[i][j]=Math.min(a[i][j]+a[i][j-1],a[i][j]+a[i-1][j]);
13 | else if(i==0 && j>0)
14 | a[i][j]=a[i][j-1]+a[i][j];
15 | else if(j==0 && i>0)
16 | a[i][j]=a[i-1][j]+a[i][j];
17 | }
18 | }
19 | return a[a.length-1][a[0].length-1];
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/problems/medium/MinimumSizeSubArray.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-30.
5 | */
6 | public class MinimumSizeSubArray {
7 | public static void main(String[] args) {
8 | new MinimumSizeSubArray().minSubArrayLen(9, new int[]{3, 2, 1, 1, 1, 1});
9 | }
10 |
11 | public int minSubArrayLen(int s, int[] a) {
12 | if(a==null || a.length==0)return 0;
13 |
14 | for (int i = 1; i < a.length; i++)
15 | a[i]+=a[i-1];
16 |
17 | int i=-1;
18 | int j=0;
19 | int min=a.length+1;
20 | int ai=0;
21 | while(j=s){
24 | System.out.println(i + " " + j);
25 | min=Math.min(j-i, min);
26 | i++;
27 | }else j++;
28 | }
29 | min = min==a.length+1 ? 0 : min;
30 | return min;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/medium/MissingNumber.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-26.
5 | */
6 | public class MissingNumber {
7 | public int missingNumber(int[] a) {
8 | int s=0;
9 | int s1=0;
10 | for(int i=0; i twice = new TreeMap<>();
14 | TreeMap once = new TreeMap<>();
15 |
16 | public MyCalendarTwo() {
17 |
18 | }
19 |
20 | public boolean book(int start, int end) {
21 |
22 | return true;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/medium/NonoverlappingIntervals.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.Interval;
4 |
5 | import java.util.Arrays;
6 |
7 | /**
8 | * Created by sherxon on 4/5/17.
9 | */
10 | public class NonoverlappingIntervals {
11 | public int eraseOverlapIntervals(Interval[] intervals) {
12 | int count = 0;
13 | Arrays.sort(intervals, (a, b) -> {
14 | int count1 = a.start - b.start;
15 | if (count1 == 0)
16 | count1 = a.end - b.end;
17 | return count1;
18 | });
19 | for (int i = 1; i < intervals.length; i++) {
20 | if (intervals[i - 1].end > intervals[i].start) {
21 | intervals[i].end = Math.min(intervals[i - 1].end, intervals[i].end);
22 | count++;
23 | }
24 | }
25 | return count;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/medium/NumberofIslands.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/21/17.
5 | */
6 | public class NumberofIslands {
7 | public int numIslands(char[][] a) {
8 | int counter = 0;
9 | for (int i = 0; i < a.length; i++) {
10 | for (int j = 0; j < a[i].length; j++) {
11 | if (a[i][j] == '1') {
12 | countIt(a, i, j);
13 | counter++;
14 | }
15 | }
16 | }
17 | return counter - 1;
18 | }
19 |
20 | void countIt(char[][] a, int i, int j) {
21 | if (i >= 0 && i < a.length && j >= 0 && j < a[i].length && a[i][j] == '1')
22 | a[i][j] = '0';
23 | else
24 | return;
25 | countIt(a, i + 1, j);
26 | countIt(a, i, j + 1);
27 | countIt(a, i - 1, j);
28 | countIt(a, i, j - 1);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/medium/OddEvenLinkedList.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.ListNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-31.
7 | */
8 | public class OddEvenLinkedList {
9 | public ListNode oddEvenList(ListNode head) {
10 | if(head==null)return null;
11 | if(head.next==null || head.next.next==null)return head;
12 |
13 | ListNode x=head;
14 | ListNode evenHead=null;
15 | ListNode even=null;
16 | while(x!=null){
17 | if(even==null){
18 | even=x.next;
19 | evenHead=even;
20 | }else{
21 | even.next=x.next;
22 | even=even.next;
23 | }
24 | if(x.next!=null){
25 | x.next=x.next.next;
26 | }
27 | if(x.next==null){
28 | x.next=evenHead;
29 | break;
30 | }
31 |
32 | x=x.next;
33 |
34 | }
35 | return head;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/problems/medium/PalindromicSubstrings.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * @author Sherali Obidov.
5 | */
6 | public class PalindromicSubstrings {
7 | public int countSubstrings(String s) {
8 | if(s==null || s.length()==0)return 0;
9 |
10 | int count=s.length();
11 | char[] a =s.toCharArray();
12 |
13 | for(int i=1; i=0 && q=0 && q> pathSum(TreeNode root, int sum) {
13 | List> l= new ArrayList<>();
14 | f(root, sum, l, new ArrayList<>());
15 | String m="";
16 |
17 | return l;
18 | }
19 | void f(TreeNode x, int sum, List> l, List ll){
20 | if(x==null)return;
21 | ll.add(x.val);
22 | f(x.left, sum-x.val, l,new ArrayList<>(ll));
23 | f(x.right, sum-x.val, l, new ArrayList<>(ll));
24 | if(x.left==null && x.right==null && sum-x.val==0)l.add(ll);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/medium/PeekingIterator.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.Iterator;
4 | import java.util.LinkedList;
5 |
6 | /**
7 | * Created by sherxon on 1/6/17.
8 | */
9 | public class PeekingIterator implements Iterator {
10 |
11 |
12 | Iterator iterator;
13 | LinkedList list;
14 | public PeekingIterator(Iterator iterator) {
15 | // initialize any member here.
16 | this.iterator=iterator;
17 | list=new LinkedList<>();
18 | while (iterator.hasNext()){
19 | list.add(iterator.next());
20 | }
21 | }
22 |
23 | // Returns the next element in the iteration without advancing the iterator.
24 | public Integer peek() {
25 | return list.getFirst();
26 | }
27 |
28 |
29 | @Override
30 | public boolean hasNext() {
31 | return list.iterator().hasNext();
32 | }
33 |
34 | @Override
35 | public Integer next() {
36 | return list.removeFirst();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/problems/medium/Pow.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/11/17.
5 | */
6 | public class Pow {
7 | static double myPow(double x, int n) {
8 | double temp = x;
9 | if (n == 0) return 1;
10 | temp = myPow(x, n / 2);
11 | if (n % 2 == 0) return temp * temp;
12 | else {
13 | if (n > 0) return temp * temp * x;
14 | else return (temp * temp) / x;
15 | }
16 | }
17 |
18 | public static void main(String[] args) {
19 | System.out.println(myPow(2.00000, -2147483648));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/problems/medium/RabbitsinForest.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Why Did you create this class? what does it do?
8 | */
9 | public class RabbitsinForest {
10 |
11 | public int numRabbits(int[] a) {
12 | if (a == null || a.length == 0)
13 | return 0;
14 | Map map = new HashMap<>();
15 | for (int i = 0; i < a.length; i++) {
16 | int v = map.getOrDefault(a[i], 0);
17 | map.put(a[i], ++v);
18 | }
19 | int res = 0;
20 | for (Integer key : map.keySet()) {
21 | int v = map.get(key);
22 | if (key == 0) {
23 | res += v;
24 | continue;
25 | }
26 | if (key + 1 < v) {
27 | key++;
28 | res += key * (Math.ceil(v * 1.0 / key));
29 | } else {
30 | res += key + 1;
31 | }
32 | }
33 | return res;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/problems/medium/RemoveDuplicatesFromList2.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.ListNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-31.
7 | */
8 | public class RemoveDuplicatesFromList2 {
9 | public ListNode deleteDuplicates(ListNode head) {
10 | if(head==null)return null;
11 | if(head.next==null)return head;
12 | ListNode a=new ListNode(0);
13 | ListNode root=a;
14 | ListNode x=head;
15 | while(x!=null){
16 | ListNode y=x;
17 | while(y!=null && y.val==x.val)y=y.next;
18 | if(x.next==y){
19 | ListNode temp=new ListNode(x.val);
20 | a.next=temp;
21 | a=temp;
22 | }
23 | x=y;
24 | }
25 | return root.next;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/medium/RemoveKDigits.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/10/17.
5 | */
6 | public class RemoveKDigits {
7 |
8 | String removeKdigits(String a, int k) {
9 | StringBuilder sb=new StringBuilder(a);
10 | while (k>0){
11 | int i=1;
12 | while (isb.charAt(i)) break;
14 | i++;
15 | }
16 | sb.delete(i-1, i);
17 | while (sb.length()>0 && sb.charAt(0)=='0')
18 | sb.delete(0, 1);
19 | k--;
20 | }
21 | return sb.length()==0 ? "0" : sb.toString();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/problems/medium/RepeatedDNASequences.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * Created by sherxon on 1/17/17.
7 | */
8 | public class RepeatedDNASequences {
9 |
10 | public static List findRepeatedDnaSequences(String s) {
11 | Map map = new HashMap<>();
12 | List list = new ArrayList<>();
13 | Set set = new HashSet<>();
14 | if (s.length() == 0) return list;
15 | for (int i = 0; i <= s.length() - 10; i++) {
16 | String sub = s.substring(i, i + 10);
17 | if (map.containsKey(sub.hashCode()) && map.get(sub.hashCode()).equals(sub)) {
18 | set.add(sub);
19 | }
20 | map.put(sub.hashCode(), sub);
21 | }
22 | list.addAll(set);
23 | return list;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/problems/medium/ReverseString.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/9/17.
5 | */
6 | public class ReverseString {
7 | public static String reverseWords(String s) {
8 | StringBuilder sb= new StringBuilder();
9 | StringBuilder word= new StringBuilder();
10 | char[] a= s.trim().toCharArray();
11 | for(int i=0; i0) {
14 | sb.insert(0, word);
15 | sb.insert(0, " ");
16 | word.setLength(0);
17 | }
18 | }
19 | if(word.length()>0) {
20 | sb.insert(0, word);
21 | sb.insert(0, " ");
22 | word.setLength(0);
23 | }
24 | if(sb.length()>0)
25 | return sb.substring(1);
26 | else return sb.toString();
27 | }
28 |
29 | public static void main(String[] args) {
30 | System.out.println(reverseWords(" "));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/medium/RoomsAndKeys.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.HashSet;
4 | import java.util.List;
5 | import java.util.Set;
6 |
7 | /**
8 | * Why Did you create this class? what does it do?
9 | */
10 | public class RoomsAndKeys {
11 | public boolean canVisitAllRooms(List> rooms) {
12 | if (rooms == null || rooms.size() <= 1)
13 | return true;
14 | Set set = new HashSet<>();
15 | go(rooms, set, 0);
16 | return set.size() == rooms.size();
17 | }
18 |
19 | void go(List> rooms, Set set, int i) {
20 | if (set.contains(i))
21 | return;
22 | set.add(i);
23 | for (Integer key : rooms.get(i)) {
24 | if (!set.contains(key))
25 | go(rooms, set, key);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/medium/RotateImage.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 2/2/17.
5 | */
6 |
7 | /**
8 | * Rotate matrix by 90 degree in place. Rotating to other degrees such 180 270 is also similar to this
9 | */
10 | public class RotateImage {
11 |
12 | /**
13 | * The first solution is setting 4 rotated values in its own place.
14 | */
15 | void rotate(int[][] a) {
16 | int n = a.length;
17 | for (int i = 0; i < n / 2; i++) {
18 | for (int j = i; j < n - i - 1; j++) {
19 | int temp = a[i][j];
20 | a[i][j] = a[n - j - 1][i];
21 | a[n - j - 1][i] = a[n - i - 1][n - j - 1];
22 | a[n - i - 1][n - j - 1] = a[j][n - i - 1];
23 | a[j][n - i - 1] = temp;
24 | }
25 | }
26 | }
27 |
28 | /**
29 | * This is the second way. The idea is first reverse up to down, then swap the symmetry
30 | */
31 | public void rotate2(int[][] a) {
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/problems/medium/RotateList.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.ListNode;
4 |
5 | /**
6 | * Created by sherxon on 1/1/17.
7 | */
8 | public class RotateList {
9 | public ListNode rotateRight(ListNode head, int k) {
10 | if(head==null) return null;
11 | if(k==0)return head;
12 |
13 | int n=0;
14 | ListNode x=head;
15 | while(x!=null){
16 | n++;
17 | x=x.next;
18 | }
19 | k%=n;
20 | if(k==0)return head;
21 | int m=n-k-1;
22 | x=head;
23 | for(int i=0; i -1;
18 | }
19 | return false;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/problems/medium/ShiftingLetters.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class ShiftingLetters {
7 | public String shiftingLetters(String s, int[] a) {
8 | if (a == null || a.length == 0)
9 | return s;
10 | a[a.length - 1] %= 26;
11 | for (int i = a.length - 2; i >= 0; i--) {
12 | a[i] = (a[i] + a[i + 1]) % 26;
13 | }
14 | char[] c = s.toCharArray();
15 | for (int i = 0; i < a.length; i++) {
16 | c[i] = (char) (a[i] + c[i]);
17 | if (c[i] > 'z')
18 | c[i] = (char) (c[i] % 'z' + 'a' - 1);
19 | }
20 | return new String(c);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/problems/medium/ShortestWordDistance2.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.HashMap;
4 | import java.util.HashSet;
5 | import java.util.Map;
6 | import java.util.Set;
7 |
8 | /**
9 | * Created by sherxon on 4/15/17.
10 | */
11 | public class ShortestWordDistance2 {
12 |
13 | Map> map= new HashMap<>();
14 |
15 | public ShortestWordDistance2(String[] words) {
16 | for(int i=0; i());
19 | map.get(words[i]).add(i);
20 | }
21 | }
22 |
23 | public int shortest(String word1, String word2) {
24 | int min=Integer.MAX_VALUE;
25 | for(Integer i:map.get(word1)){
26 | for(Integer j:map.get(word2)){
27 | min=Math.min(min, Math.abs(i-j));
28 | }
29 | }
30 | return min;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/medium/ShuffleanArray.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/2/17.
5 | */
6 | public class ShuffleanArray {
7 | int [] a;
8 | int [] nums;
9 |
10 | public ShuffleanArray(int[] nums) {
11 | this.nums=nums;
12 | a= new int[nums.length];
13 | System.arraycopy(nums, 0, a, 0, nums.length);
14 | }
15 |
16 | /** Resets the array to its original configuration and return it. */
17 | public int[] reset() {
18 | return nums;
19 | }
20 |
21 | /** Returns a random shuffling of the array. */
22 | public int[] shuffle() {
23 | for(int i=0; i> i) & 1) == 1){
25 | count[i]++;
26 | }
27 | }
28 | res |=( (count[i]%3) << i );
29 | }
30 | return res;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/problems/medium/SortColors.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/17/17.
5 | */
6 | public class SortColors {
7 | public void sortColors(int[] nums) {
8 | int os = 0;
9 | int ones = 0;
10 | int twos = 0;
11 | for (int i = 0; i < nums.length; i++) {
12 | if (nums[i] == 0) os++;
13 | else if (nums[i] == 1) ones++;
14 | else twos++;
15 | }
16 | for (int i = 0; i < nums.length; i++) {
17 | if (os > 0) {
18 | nums[i] = 0;
19 | os--;
20 | } else if (ones > 0) {
21 | nums[i] = 1;
22 | ones--;
23 | } else {
24 | nums[i] = 2;
25 | }
26 | }
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/medium/SubSets.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by sherxon on 1/11/17.
8 | */
9 | public class SubSets {
10 |
11 | /**
12 | * This generates all subsets of given set.
13 | */
14 | public List> subsets(int[] a) {
15 | List> list = new ArrayList<>();
16 | boolean[] b = new boolean[a.length];
17 | generate(a, b, list, a.length);
18 | return list;
19 | }
20 |
21 | void generate(int[] a, boolean[] b, List> list, int n) {
22 | if (n == 0) {
23 | List l = new ArrayList<>();
24 | for (int i = 0; i < a.length; i++)
25 | if (b[i]) l.add(a[i]);
26 | list.add(l);
27 | } else {
28 | b[n - 1] = true;
29 | generate(a, b, list, n - 1);
30 |
31 | b[n - 1] = false;
32 | generate(a, b, list, n - 1);
33 | }
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/problems/medium/SumRoottoLeafNumbers.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-30.
7 | */
8 | public class SumRoottoLeafNumbers {
9 | int sum=0;
10 | public int sumNumbers(TreeNode root) {
11 | if(root==null)return 0;
12 | sum(root, 0);
13 | return sum;
14 | }
15 | public void sum(TreeNode x, int p){
16 | if(x==null) return;
17 | x.val=x.val+p;
18 | sum(x.left, x.val*10);
19 | sum(x.right, x.val*10);
20 | if(x.left==null && x.right==null)sum+=x.val;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/problems/medium/Targetsum.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/21/17.
5 | */
6 | public class Targetsum {
7 | static int counter = 0;
8 |
9 | public static void main(String[] args) {
10 | System.out.println(findTargetSumWays(new int[]{0, 0, 1}, 1));
11 | }
12 |
13 | static int findTargetSumWays(int[] a, int s) {
14 | findSum(a, a.length - 1, s);
15 | return counter;
16 | }
17 |
18 | private static void findSum(int[] a, int i, int s) {
19 |
20 | if (i == 0) {
21 | if (s + a[i] == 0) counter++;
22 | if (s - a[i] == 0) counter++;
23 | return;
24 | }
25 |
26 | findSum(a, i - 1, s + a[i]);
27 | findSum(a, i - 1, s - a[i]);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/medium/TeemoAttacking.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/28/17.
5 | */
6 | public class TeemoAttacking {
7 |
8 | public int findPoisonedDuration(int[] a, int t) {
9 | if (a.length == 0 || t == 0) return 0;
10 | if (a.length == 1) return t;
11 |
12 | int count = 0;
13 | for (int i = 0; i < a.length; i++) {
14 | if (i == 0) {
15 | count += t;
16 | continue;
17 | }
18 | if (a[i - 1] + t - 1 < a[i]) {
19 | count += t;
20 | } else {
21 | int need = a[i] + t - 1 - (a[i - 1] + t - 1);
22 | count += need;
23 | }
24 | }
25 |
26 | return count;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/problems/medium/TopKFrequentWords.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * Why Did you create this class? what does it do?
7 | */
8 | public class TopKFrequentWords {
9 |
10 | public List topKFrequent(String[] words, int k) {
11 | Map map = new HashMap<>();
12 | for (int i = 0; i < words.length; i++) {
13 | map.put(words[i], map.getOrDefault(words[i], 0) + 1);
14 | }
15 | PriorityQueue> queue = new PriorityQueue<>((a, b) -> {
16 | int c = b.getValue() - a.getValue();
17 | if (c == 0)
18 | return a.getKey().compareTo(b.getKey());
19 | return c;
20 | });
21 | queue.addAll(map.entrySet());
22 | List list = new ArrayList<>();
23 | while (k > 0) {
24 | list.add(queue.poll().getKey());
25 | k--;
26 | }
27 | return list;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/problems/medium/TwoSumSortedArray.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.math.BigInteger;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-27.
7 | */
8 | public class TwoSumSortedArray {
9 | public static void main(String[] args) {
10 | BigInteger bigInteger = new BigInteger("76");
11 | BigInteger.valueOf(1);
12 | System.out.println(bigInteger);
13 |
14 | // new TwoSumSortedArray().twoSum(new int[]{1,2,3,4,5,6,7,8}, 5);
15 | }
16 | public int[] twoSum(int[] a, int t) {
17 | int i=0;
18 | int j=a.length-1;
19 | while (i t) j--;
21 | else if (a[i] + a[j] < t) i++;
22 | else break;
23 | }
24 |
25 | return new int[]{i+1, j+1};
26 |
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/medium/UniquePaths.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/20/17.
5 | */
6 | public class UniquePaths {
7 | public int uniquePaths(int m, int n) {
8 | if (m == 0 || n == 0) return 0;
9 | if (m == 1 || n == 1) return 1;
10 | int[][] a = new int[m][n];
11 |
12 | for (int i = 0; i < a.length; i++)
13 | a[i][0] = 1;
14 | for (int i = 0; i < a[0].length; i++)
15 | a[0][i] = 1;
16 |
17 | for (int i = 1; i < a.length; i++) {
18 | for (int j = 1; j < a[i].length; j++) {
19 | a[i][j] = a[i][j - 1] + a[i - 1][j];
20 | }
21 | }
22 | return a[m - 1][n - 1];
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/problems/medium/ValidPerfectSquare.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/2/17.
5 | */
6 | // this also can be solved using newtons method, MIT 6.006 lec 12-13
7 | public class ValidPerfectSquare {
8 | public boolean isPerfectSquare(int num) {
9 | if(num<1)return false;
10 | if(num==1)return true;
11 | int temp=num;
12 | long i=1;
13 | long j=1;
14 | while(temp>=1){
15 | temp/=10;
16 | j*=10;
17 | }
18 | while(i<=j){
19 | long mid=i+(j-i)/2;
20 | if(mid*mid==num)return true;
21 | else if(mid*mid > num)j=mid-1;
22 | else i=mid+1;
23 | }
24 | return false;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/problems/medium/WaterAndJugProblem.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | /**
4 | * Created by sherxon on 1/12/17.
5 | */
6 | public class WaterAndJugProblem {
7 |
8 |
9 | boolean canMeasureWater(int x, int y, int z) {
10 | if (x == z || y == z) return true;
11 | if (x == 0 || y == 0 || x + y < z) return false;
12 | int a = getGCD(x, y);
13 | return z % a == 0;
14 | }
15 |
16 | int getGCD(int x, int y) {
17 | if (y == 0) return x;
18 | return getGCD(y, x % y);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/problems/medium/WidthOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import problems.utils.TreeNode;
4 |
5 | /**
6 | * Created by sherxon on 3/5/17.
7 | */
8 |
9 | /**
10 | * Diameter of binary tree
11 | */
12 | public class WidthOfBinaryTree {
13 |
14 | public int width(TreeNode root) {
15 | if (root == null) return 0;
16 |
17 | int heightLeft = height(root.left);
18 | int heightRight = height(root.right);
19 |
20 | int leftDiameter = width(root.left);
21 | int rightDiameter = width(root.right);
22 | return Math.max(heightLeft + heightRight + 1, Math.max(leftDiameter, rightDiameter));
23 | }
24 |
25 | private int height(TreeNode x) {
26 | if (x == null) return 0;
27 | return Math.max(height(x.left), height(x.right)) + 1;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/problems/medium/WordBreak.java:
--------------------------------------------------------------------------------
1 | package problems.medium;
2 |
3 | import java.util.HashSet;
4 | import java.util.List;
5 | import java.util.Set;
6 |
7 | /**
8 | * Created by sherxon on 3/3/17.
9 | */
10 | public class WordBreak {
11 |
12 | /**
13 | * We make helper array length of given word+1 and with all fields false.
14 | * The array element is true if such a word exists in dictionary.
15 | */
16 | public boolean wordBreak(String s, List wordDict) {
17 | Set set = new HashSet<>(wordDict);
18 | boolean[] a = new boolean[s.length() + 1];
19 | a[0] = true;
20 | for (int i = 0; i < a.length; i++) {
21 | if (a[i]) {
22 | for (int j = i + 1; j < a.length; j++) {
23 | if (set.contains(s.substring(i, j)))
24 | a[j] = true;
25 | }
26 | }
27 | if (a[a.length - 1]) return true;
28 | }
29 | return a[a.length - 1];
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/problems/utils/Interval.java:
--------------------------------------------------------------------------------
1 | package problems.utils;
2 |
3 | /**
4 | * Created by sherxon on 1/28/17.
5 | */
6 | public class Interval {
7 | public int start;
8 | public int end;
9 |
10 | public Interval() {
11 | start = 0;
12 | end = 0;
13 | }
14 |
15 | public Interval(int s, int e) {
16 | start = s;
17 | end = e;
18 | }
19 |
20 | @Override
21 | public String toString() {
22 | return "Interval{" +
23 | "start=" + start +
24 | ", end=" + end +
25 | '}';
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/problems/utils/ListNode.java:
--------------------------------------------------------------------------------
1 | package problems.utils;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-28.
5 | */
6 | public class ListNode {
7 | public int val;
8 | public ListNode next;
9 | public ListNode(int x) {
10 | val = x;
11 | next = null;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/problems/utils/RandomListNode.java:
--------------------------------------------------------------------------------
1 | package problems.utils;
2 |
3 | /**
4 | * Created by sherxon on 1/6/17.
5 | */
6 | public class RandomListNode {
7 | public int label;
8 | public RandomListNode next, random;
9 | public RandomListNode(int x) { this.label = x; }
10 | }
11 |
--------------------------------------------------------------------------------
/src/problems/utils/TreeNode.java:
--------------------------------------------------------------------------------
1 | package problems.utils;
2 |
3 | /**
4 | * Created by sherxon on 2016-12-24.
5 | */
6 | public class TreeNode {
7 | public int val;
8 | public TreeNode left;
9 | public TreeNode right;
10 | public TreeNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/src/problems/utils/UndirectedGraphNode.java:
--------------------------------------------------------------------------------
1 | package problems.utils;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * Created by sherxon on 1/5/17.
8 | */
9 | public class UndirectedGraphNode {
10 | public int label;
11 | public List neighbors;
12 | public UndirectedGraphNode(int x) {
13 | label = x;
14 | neighbors = new ArrayList();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/timus/ABProblem1000.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 |
8 | /**
9 | * Created by sherxon on 2016-10-30.
10 | */
11 | public class ABProblem1000 {
12 | public static void main(String[] args) throws IOException {
13 | BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
14 | String s=bufferedReader.readLine();
15 | int a=Integer.parseInt(s.split(" ")[0]);
16 | int b=Integer.parseInt(s.split(" ")[1]);
17 | PrintWriter writer= new PrintWriter(System.out);
18 | writer.write(a+b+"");
19 | writer.flush();
20 | writer.close();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/timus/Alchemy1573.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 2016-12-10.
7 | */
8 | public class Alchemy1573 {
9 | public static void main(String[] args) {
10 | Scanner in =new Scanner(System.in);
11 | int b=in.nextInt();
12 | int r=in.nextInt();
13 | int y=in.nextInt();
14 | int k=in.nextInt();
15 | int sum=1;
16 | for (int i = 0; i < k; i++) {
17 | String s=in.next();
18 | if(s.equals("Red"))sum*=r;
19 | else if(s.equals("Yellow"))sum*=y;
20 | else sum*=b;
21 | }
22 | System.out.println(sum);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/timus/AnotherDressRehearsal2035.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/6/16.
7 | */
8 | public class AnotherDressRehearsal2035 {
9 | public static void main(String[] args) {
10 | Scanner in =new Scanner(System.in);
11 | int x=in.nextInt();
12 | int y=in.nextInt();
13 | int c=in.nextInt();
14 | if(x+y < c) System.out.println("Impossible");
15 | else{
16 | int a=Math.min(Math.min(x, y), c);
17 | int b=c-a;
18 | if(x set= new HashSet<>();
15 | int count=0;
16 | for (int i = 0; i < n; i++) {
17 | String s=in.nextLine();
18 | if(set.contains(s))count++;
19 | else set.add(s);
20 | }
21 | System.out.println(count);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/timus/BritishScientistsSavetheWorld1925.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/5/16.
7 | */
8 | public class BritishScientistsSavetheWorld1925 {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n=in.nextInt();
12 | int k=in.nextInt();
13 | int sum1=k;
14 | int sum2=0;
15 | for (int i = 0; i = 0 ? res : "Big Bang!");
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/timus/CentipedesMorning1876.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/5/16.
7 | */
8 | public class CentipedesMorning1876 {
9 | public static void main(String[] args) {
10 | Scanner in =new Scanner(System.in);
11 | int a=in.nextInt();
12 | int b=in.nextInt();
13 | int max1=b*2+40;
14 | int max2=39*2 + 40 + (a-40)*2 + 1;
15 | int max=Math.max(max1, max2);
16 | System.out.println(max);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/timus/CityBlocks1139.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/8/16.
7 | */
8 | // not solved
9 | public class CityBlocks1139 {
10 | public static void main(String[] args) {
11 | Scanner in =new Scanner(System.in);
12 | int n=in.nextInt()-1;
13 | int m=in.nextInt()-1;
14 | if(m==n) System.out.println(m);
15 | else{
16 |
17 | }
18 |
19 |
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/timus/DemocracyinDanger1025.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * Created by sherxon on 2016-10-30.
8 | */
9 | public class DemocracyinDanger1025 {
10 | public static void main(String[] args) {
11 | Scanner in =new Scanner(System.in);
12 | int k=in.nextInt();
13 | int [] sons=new int[k];
14 | for (int i = 0; i < k; i++) {
15 | sons[i]=in.nextInt();
16 | }
17 | Arrays.sort(sons);
18 | int limit=sons.length/2;
19 | if(sons.length%2!=0)limit+=1;
20 | int res=0;
21 | for (int i = 0; i < limit; i++) {
22 | res+=sons[i]/2;
23 | if(sons[i]%2!=0)res+=1;
24 | }
25 | System.out.println(res);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/timus/DivorceoftheSevenDwarfs1243.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.math.BigInteger;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * Created by sherxon on 12/4/16.
8 | */
9 | public class DivorceoftheSevenDwarfs1243 {
10 | public static void main(String[] args) {
11 | Scanner in =new Scanner(System.in);
12 | BigInteger integer=new BigInteger(in.next());
13 | System.out.println(integer.remainder(new BigInteger(String.valueOf(7))));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/timus/Donaldisapostman2023.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/3/16.
7 | */
8 | public class Donaldisapostman2023 {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n= Integer.parseInt(in.nextLine());
12 | int prev=0;
13 | int steps=0;
14 | for (int i = 0; i < n; i++) {
15 | String s=in.nextLine();
16 | int b= getBox(s);
17 | steps+=(Math.abs(prev-b));
18 | prev=b;
19 | }
20 | System.out.println(steps);
21 | }
22 |
23 | private static int getBox(String s) {
24 | if(s.startsWith("A") || s.startsWith("P") || s.startsWith("O") || s.startsWith("R"))
25 | return 0;
26 | else if(s.startsWith("B") || s.startsWith("M") || s.startsWith("S"))
27 | return 1;
28 | else
29 | return 2;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/timus/DontAskWomanaboutHerAge1104.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/8/16.
7 | */
8 | public class DontAskWomanaboutHerAge1104 {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | char[] a=in.nextLine().toCharArray();
12 | int max=0;
13 | long sum=0;
14 | int k=0;
15 | for (int i = 0; i < a.length; i++) {
16 |
17 | if(Character.isAlphabetic(a[i]))
18 | k=a[i]-55;
19 | else {
20 | k=a[i]-48;
21 | }
22 | if(k>max)max=k;
23 | sum+=k;
24 | }
25 | int i = max+1;
26 | boolean yes=false;
27 | for (; i <=36 ; i++) {
28 | if(i-1>0 && sum%(i-1)==0) {
29 | yes=true;
30 | break;
31 | }
32 | }
33 | System.out.println(yes ? i : "No solution.");
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/timus/Easy1044.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/6/16.
7 | */
8 | public class Easy1044 {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n=in.nextInt();
12 | if(n==2) System.out.println(10);
13 | else if(n==4) System.out.println(670);
14 | else if(n==6) System.out.println(55252);
15 | else if(n==8) System.out.println(4816030);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/timus/Elections1263.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.text.DecimalFormat;
4 | import java.text.NumberFormat;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * Created by sherxon on 12/1/16.
9 | */
10 | public class Elections1263 {
11 | public static void main(String[] args) {
12 | Scanner in =new Scanner(System.in);
13 | int n=in.nextInt();
14 | int m=in.nextInt();
15 | int[] a= new int[n+1];
16 | for (int i = 1; i <=m; i++) {
17 | int k=in.nextInt();
18 | a[k]++;
19 | }
20 | NumberFormat formatter = new DecimalFormat("#0.00");
21 | for (int i = 1; i 0 ; i-=marks) {
18 | sum*=i;
19 | }
20 | System.out.println(sum);
21 | Arrays.stream(new int[]{}).sum();
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/timus/Farm1349.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/5/16.
7 | */
8 | public class Farm1349 {
9 | public static void main(String[] args) {
10 | Scanner in=new Scanner(System.in);
11 | int n=in.nextInt();
12 | if(n==1) System.out.println(1 + " " + 2 + " " + 3);
13 | else if(n==2) System.out.println(3 + " " + 4 + " " + 5);
14 | else System.out.println(-1);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/timus/FlatSpots1617.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * Created by sherxon on 12/6/16.
9 | */
10 | public class FlatSpots1617 {
11 | public static void main(String[] args) {
12 | Scanner in =new Scanner(System.in);
13 | int n=in.nextInt();
14 | Map map=new HashMap<>();
15 |
16 | for (int i = 0; i < n; i++) {
17 | int k=in.nextInt();
18 | if (!map.containsKey(k))
19 | map.put(k, 1);
20 | else map.put(k, map.get(k)+1);
21 | }
22 | System.out.println(map.values().stream().filter(s->s/4>0).
23 | reduce(0, (a,b)->a+b/4).intValue());
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/timus/Fuses1327.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 | import java.util.stream.IntStream;
5 |
6 | /**
7 | * Created by sherxon on 12/4/16.
8 | */
9 | public class Fuses1327 {
10 | public static void main(String[] args) {
11 | Scanner in =new Scanner(System.in);
12 | int a=in.nextInt();
13 | int b=in.nextInt();
14 | System.out.println(IntStream.range(a, b+1).filter(s->s%2!=0).count());
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/timus/GoatInthegarden1084.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/7/16.
7 | */
8 | public class GoatInthegarden1084 {
9 | public static void main(String[] args) {
10 | Scanner in =new Scanner(System.in);
11 | int x=10/(3*2);
12 | System.out.println(36*Math.PI);
13 | System.out.println(9/2 * (Math.acos(x)- Math.sqrt(1-x*x)));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/timus/Hieroglyphs.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.HashMap;
4 | import java.util.HashSet;
5 | import java.util.Map;
6 | import java.util.Set;
7 |
8 | /**
9 | * Created by sherxon on 12/5/16.
10 | */
11 | public class Hieroglyphs {
12 | public static void main(String[] args) {
13 | FastReader reader= new FastReader();
14 | int n=Integer.parseInt(reader.nextLine());
15 | Map> setMap= new HashMap<>();
16 | for (int i = 0; i < n; i++) {
17 | String s=reader.nextLine();
18 | if(!setMap.containsKey(s.charAt(0)))
19 | setMap.put(s.charAt(0), new HashSet<>());
20 | setMap.get(s.charAt(0)).add(s.charAt(1));
21 | }
22 | char r=reader.nextLine().charAt(0);
23 | if(setMap.containsKey(r))
24 | for (Character character : setMap.get(r)) {
25 | System.out.println(String.valueOf(r)+String.valueOf(character));
26 | }
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/timus/OneStepfromHappiness1493.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/5/16.
7 | */
8 | public class OneStepfromHappiness1493 {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | String s=in.nextLine();
12 | int a=Integer.parseInt(s.substring(0, 3));
13 | int b=Integer.parseInt(s.substring(3));
14 | boolean res;
15 | res = Math.abs(getSum(a) - getSum(b + 1)) == 0 || Math.abs(getSum(a) - getSum(b - 1)) == 0;
16 | System.out.println(res ? "Yes" : "No");
17 |
18 | }
19 |
20 | private static int getSum(int a) {
21 | int sum=0;
22 | while (a>0){
23 | sum+=a%10;
24 | a/=10;
25 | }
26 | return sum;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/timus/OverturnedNumbers2031.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/6/16.
7 | */
8 | public class OverturnedNumbers2031 {
9 | public static void main(String[] args) {
10 | Scanner in =new Scanner(System.in);
11 | int n=in.nextInt();
12 | if(n==1) System.out.println("11");
13 | else if(n==2) System.out.println("11 01");
14 | else if(n==3) System.out.println("16 06 68");
15 | else if(n==4) System.out.println("16 06 68 88");
16 | else System.out.println("Glupenky Pierre");
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/timus/PenaltyTime.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/5/16.
7 | */
8 | public class PenaltyTime {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n=in.nextInt();
12 | int m=in.nextInt();
13 | int sum=0;
14 | for (int i = 0; i < 10; i++) {
15 | sum+=in.nextInt();
16 | }
17 | sum*=20;
18 | System.out.println(m-sum >= n ? "No chance." : "Dirty debug :(");
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/timus/Rope1020.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.text.DecimalFormat;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * Created by sherxon on 12/3/16.
8 | */
9 | public class Rope1020 {
10 | public static void main(String[] args) {
11 | Scanner in =new Scanner(System.in);
12 | int n=in.nextInt();
13 | double r=in.nextDouble();
14 | double x = 0, y = 0, px = 0, py = 0, fx = 0, fy = 0;
15 | double l=0;
16 | for (int i = 0; i < n; i++) {
17 | x=in.nextDouble();
18 | y=in.nextDouble();
19 | if(i==0){fx=px=x;fy=py=y;}
20 | else {
21 | l+=Math.sqrt(Math.pow(px-x, 2) + Math.pow(py-y, 2));
22 | px=x;
23 | py=y;
24 | }
25 | }
26 | l+=Math.sqrt(Math.pow(x-fx, 2) + Math.pow(y-fy, 2));
27 | DecimalFormat f=new DecimalFormat("#.##");
28 | System.out.println(f.format(l+2*r*Math.PI));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/timus/SandroBook1723.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * Created by sherxon on 12/5/16.
9 | */
10 | public class SandroBook1723 {
11 | public static void main(String[] args) {
12 | Scanner in = new Scanner(System.in);
13 | Map map= new HashMap<>();
14 | char[] a=in.nextLine().toCharArray();
15 | for (char c : a) {
16 | if(!map.containsKey(c))
17 | map.put(c, 1);
18 | else
19 | map.put(c, map.get(c)+1);
20 | }
21 | int max=0;
22 | char c=0;
23 | for (Character character : map.keySet()) {
24 | if(max map= new HashMap<>();
15 | for (int i = 0; i < n; i++) {
16 | String s=in.nextLine();
17 | if(!map.containsKey(s))
18 | map.put(s, 1);
19 | else
20 | map.put(s, map.get(s)+1);
21 | }
22 | for (String s : map.keySet()) {
23 | if(map.get(s)>1){
24 | System.out.println(s);
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/timus/Spiral1224.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/6/16.
7 | */
8 | public class Spiral1224 {
9 | public static void main(String[] args) {
10 | Scanner in =new Scanner(System.in);
11 | long n=in.nextInt();
12 | long m=in.nextInt();
13 | System.out.println(Math.min(n,m)*2 - (n>m ? 1 :2));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/timus/Sum1068.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 | import java.util.stream.LongStream;
5 |
6 | /**
7 | * Created by sherxon on 2016-10-30.
8 | */
9 | public class Sum1068 {
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int m=in.nextInt();
13 | int n=Math.abs(m);
14 | long sum= LongStream.range(1, n + 1).sum();
15 | if(m<0){
16 | sum-=1;
17 | sum*=-1;
18 | }else if (m==0){
19 | sum=1;
20 | }
21 | System.out.println(sum);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/timus/Taxi1607.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/5/16.
7 | */
8 | public class Taxi1607 {
9 | public static void main(String[] args) {
10 | Scanner in =new Scanner(System.in);
11 | int a=in.nextInt();
12 | int b=in.nextInt();
13 | int x=in.nextInt();
14 | int y=in.nextInt();
15 | while (x>a){
16 | a+=b;
17 | if(a>x)a=x;
18 | x-=y;
19 | }
20 | System.out.println(Math.max(x, a));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/timus/TearsofDrowned1935.java:
--------------------------------------------------------------------------------
1 | package timus;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Created by sherxon on 12/6/16.
7 | */
8 | public class TearsofDrowned1935 {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n=in.nextInt();
12 | int sum=0;
13 | int max=0;
14 | for (int i = 0; i < n; i++) {
15 | int k=in.nextInt();
16 | sum+=k;
17 | if(max0){
19 | count++;
20 | }
21 | }
22 | if(count==13)count+=1;
23 | System.out.println(count*100);
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/toptal/Second.java:
--------------------------------------------------------------------------------
1 | package toptal;
2 |
3 | import java.math.BigInteger;
4 | import java.util.Arrays;
5 | import java.util.stream.Collectors;
6 |
7 | /**
8 | * Why Did you create this class? what does it do?
9 | */
10 | public class Second {
11 | public static void main(String[] args) {
12 | System.out.println(solution(new int[] { 1 }));
13 | }
14 |
15 | static public int solution(int[] a) {
16 | // write your code in Java SE 8
17 | if (a == null || a.length == 0)
18 | return 0;
19 | StringBuilder sb = new StringBuilder(a.length);
20 | for (int i = 0; i < a.length; i++) {
21 | sb.append(a[i]);
22 | }
23 | sb = sb.reverse();
24 | BigInteger integer = new BigInteger(sb.toString());
25 | integer = integer.multiply(BigInteger.valueOf(17));
26 | int result = 0;
27 | String s = integer.toString();
28 | for (int i = 0; i < s.length(); i++) {
29 | result += s.charAt(i) - '0';
30 | }
31 | return result;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/toptal/Third.java:
--------------------------------------------------------------------------------
1 | package toptal;
2 |
3 | /**
4 | * Why Did you create this class? what does it do?
5 | */
6 | public class Third {
7 | public int solution(int[] a) {
8 | // write your code in Java SE 8
9 | // 1,5,4,9,8,7,12,13,14
10 | // 0,1,0,2,1,0,0,0,0
11 | // 1,2,3,4,5,6,0
12 | if (a == null || a.length == 0)
13 | return 0;
14 | if (a.length == 1)
15 | return 1;
16 | int count = 0;
17 | int min = Integer.MAX_VALUE;
18 | for (int i = a.length - 1; i >= 0; i--) {
19 | if (a[i] < min) {
20 | count++;
21 | min = a[i];
22 | }
23 | }
24 | return count;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------