├── .github └── workflows │ ├── greetings.yml │ ├── issues_labeler.yml │ └── stale.yml ├── .vscode └── settings.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── CheatSheets ├── BigOCheatsheet.pdf ├── CPP-Cheatsheet.pdf ├── STLQuickReference1.29.pdf └── UserfulLinks.md ├── CodeChefProblems ├── ChefAndOperatorsCHOPRT.py ├── ChefAndRemissnessREMISS.py ├── FLOW002.c ├── FLOW004.py ├── FLOW006.py ├── FLOW007ReverseTheNumber.py ├── FLOW016GcdAndLcm.py ├── FLOW017SecondLargest.py ├── FLOW018SmallFactorial.cpp ├── FSQRTFindingSquareRoots.py ├── JanuaryChallenge2021Division3 │ ├── .vscode │ │ └── settings.json │ ├── ChefAndDivision3.cpp │ ├── EncodedString.cpp │ ├── FairElections.cpp │ ├── PointOfImpact.cpp │ ├── WatchingCPL.cpp │ └── a.out ├── LifeTheUniverseAndEverything.py ├── MahasenaAMR15A.py ├── NovemberCookOff2020 │ ├── .vscode │ │ └── settings.json │ ├── ChefAndIPCCertificates.cpp │ ├── FlipTheString.cpp │ └── a.out ├── NovemberLunchTime2020Division2 │ ├── GasolineIntroduction.cpp │ └── a.out ├── Problem │ ├── .vscode │ │ └── settings.json │ ├── CodepurCaresFund.cpp │ ├── FindMinimum.cpp │ ├── KidsAtHome.cpp │ ├── PreparingTest.cpp │ ├── PrintPattern.cpp │ └── a.out ├── ReverseTheNumber.cpp ├── ServantFLOW008.py ├── SmallestNumbersOfNotes.py ├── TheBlockGamePALL01.py ├── TotalExpensesFLOW009.py └── ValidTrianglesFLOW13.py ├── CodeForces ├── .vscode │ └── settings.json ├── A+B.py ├── AmusingJoke.cpp ├── AntonAndDanik.cpp ├── AntonAndLetters.cpp ├── AntonAndPolyhedrons.cpp ├── ArrivalOfTheGeneral.cpp ├── BearAndBigBrother.cpp ├── BoyOrGirl.py ├── CalculatingFunction.cpp ├── CandiesAndTwoSisters.cpp ├── ChatRoom.cpp ├── Codeforces Round #684 (Div. 2) │ ├── BuyTheString.cpp │ ├── SumOfMedians.cpp │ └── a.out ├── Codeforces Round #686 (Div. 3) │ ├── .vscode │ │ └── settings.json │ ├── PredefinedLibraries.cpp │ ├── SpecialPermutation.cpp │ └── a.out ├── Codeforces Round #693 (Div. 3) │ ├── .vscode │ │ └── settings.json │ ├── CardsForFriends.cpp │ ├── FairDivision.cpp │ └── a.out ├── DivisiblityProblems.cpp ├── DominoPiling.py ├── Dragons.cpp ├── Drinks.cpp ├── Dubstep.cpp ├── Educational Codeforces Round 98 (Rated for Div. 2) │ ├── RobotProgram.cpp │ └── TwoBrackets.cpp ├── Elephant.cpp ├── EvenOdds.cpp ├── Games.cpp ├── GeorgeAndAccommondation.cpp ├── GoodBye2020 │ ├── BovineDilemma.cpp │ └── LastMinuteEnhancements.cpp ├── HQ9+.cpp ├── HelpfulMaths.py ├── HitTheLottery.cpp ├── Hulk.cpp ├── IQTest.cpp ├── IWannaBeTheGuy.cpp ├── InSearchOfAnEasyProblem.cpp ├── InsomniaCure.cpp ├── IsYourHorseshoeOnTheOtherHoof.cpp ├── LuckyDivision.cpp ├── Magnets.cpp ├── NextRound.py ├── Pangram.cpp ├── PetyaAndStrings.py ├── Presents.cpp ├── Puzzles.cpp ├── QueueAtTheSchool.cpp ├── SoldierAndBananas.cpp ├── StonesOnTheTable.py ├── StringTask.py ├── Taxi.cpp ├── TheSum.py ├── Tram.cpp ├── Translation.cpp ├── TwoRegularPolygons.py ├── UltraFastMathematician.cpp ├── VanyaAndFence.cpp ├── VanyaAndLanterns.cpp ├── WayTooLongWords.py ├── Word.cpp ├── WordCapitalization.py ├── WrongSubtraction.cpp ├── YoungPhysicist.cpp ├── a.exe ├── a.out ├── bit++.cpp ├── football.py ├── output.exe ├── team.py ├── watermelon.py ├── x └── y ├── Codewars ├── AddingBigNumbers.js ├── BasicEncryption.cpp ├── BingoOrNot.java ├── CountTheSmileyFaces.cpp ├── DirectionsReduction.py ├── GapInPrimes.py ├── JosephusSurvivor.cpp ├── LeapYears.cpp ├── MatrixAddition.cpp ├── MultiplesOf3Or5.cpp ├── NumberOfPeopleInBus.cpp ├── NumberOfTrailingZeroesOfN.cpp ├── SumOfAngles.cpp ├── SumOfCubes.cpp ├── SumOfTwoIntegers.cpp ├── SumOfTwoLowestPosIntegers.js ├── SumStringAsNumbers.js ├── TwiceLinear.py ├── WhereMyAnagramsAt.py └── rot13.cpp ├── Company-wise Questions ├── CheckForBST.cpp ├── ConvertBinaryTreeToDLL.cpp ├── KLargestElements.cpp ├── ReverseALinkedListInGroupsOfGivenSize.cpp ├── SpecialStack.cpp └── SubarrayWithGivenSum.cpp ├── GeeksforGeeks ├── CheckIfCircularLinkedList.cpp ├── DeleteWithoutHeadPointer.cpp ├── DetectLoopInLinkedList.cpp ├── DetermineIfTwoTreesAreIdentical.cpp ├── DisplayLongestName.py ├── Graphs │ ├── .vscode │ │ └── c_cpp_properties.json │ └── DFSOfGraph.cpp ├── ImplementStackUsingLinkedList.cpp ├── KLargestElements.cpp ├── KthSmallestElement.py ├── MiddleOfThree.cpp ├── MirrorTree.cpp ├── MoveAllNegativeElementsToOneSide.cpp ├── ParenthesisChecker.cpp ├── Patterns │ └── Sliding Window │ │ └── MaxSumSubarrayOfSizeK.cpp ├── PreorderTraversal.cpp ├── PrintAlternateElementsOfAnArray.cpp ├── ProductOfArrayElements.py ├── ReverseAString.py ├── ReverseAnArray.py ├── ReverseArrayInGroups.py ├── RootToLeafPathsSum.cpp ├── RotateArray.py ├── SearchAnElementInAnArray.py ├── SecondLargest.cpp ├── Segregate0sAnd1s.cpp ├── SizeOfBinaryTree.cpp ├── SortAnArrayOf0s1sAnd2s.cpp ├── SortArrayOf012.cpp ├── SquareRootOfANumber.cpp ├── SumOfArrayElements.py ├── SumOfTwoNumbersWithoutUsingArithmeticOperators.cpp └── SymmetricTree.cpp ├── HackerRank ├── 10DaysOfJavaScript │ ├── Day0DataTypes.js │ ├── Day0HelloWorld.js │ ├── Day1ArithmeticOperators.js │ ├── Day1Functions.js │ ├── Day1LetandConst.js │ ├── Day2ConditionalStatementIfElse.js │ ├── Day2ConditionalStatementSwitch.js │ ├── Day2Loops.js │ ├── Day3Arrays.js │ ├── Day3Throw.js │ ├── Day3TryCatchAndFinally.js │ ├── Day4Classes.js │ ├── Day4CountObjects.js │ ├── Day4CreateaRectangleObject.js │ ├── Day5ArrowFunctions.js │ ├── Day5Inheritance.js │ ├── Day5TemplateLiterals.js │ ├── Day6BitwiseOperators.js │ ├── Day6JavascriptDates.js │ ├── Day7RegularExpressionsI.js │ ├── Day7RegularExpressionsII.js │ ├── Day7RegularExpressionsIII.js │ ├── Day8ButtonsContainer │ │ ├── css │ │ │ └── buttonsGrid.css │ │ ├── index.html │ │ └── js │ │ │ └── buttonsGrid.js │ ├── Day8CreateAButton │ │ ├── css │ │ │ └── button.css │ │ ├── index.html │ │ └── js │ │ │ └── button.js │ ├── Day9BinaryCalculator │ │ ├── css │ │ │ └── binaryCalculator.css │ │ ├── index.html │ │ └── js │ │ │ └── binaryCalculator.js │ ├── Practise1 │ │ ├── css │ │ │ └── button.css │ │ ├── index.html │ │ └── js │ │ │ └── button.js │ └── Practise2 │ │ ├── css │ │ └── buttonsGrid.css │ │ ├── index.html │ │ └── js │ │ └── buttonsGrid.js ├── 30DaysOfCode │ ├── Day0HelloWorld.cpp │ ├── Day10BinaryNumbers.py │ ├── Day112DArrays.cpp │ ├── Day12Inheritance.cpp │ ├── Day13AbstractClasses.cpp │ ├── Day14Scope.cpp │ ├── Day15linkedlist.cpp │ ├── Day16ExceptionsStringtoInteger.cpp │ ├── Day17MoreExceptions.cpp │ ├── Day18QueuesandStacks.cpp │ ├── Day19Interfaces.cpp │ ├── Day1DataTypes.cpp │ ├── Day20Sorting.cpp │ ├── Day21Generics.cpp │ ├── Day22BinarySearchTrees.cpp │ ├── Day23BSTLevelOrderTraversal.cpp │ ├── Day24MoreLinkedLists.cpp │ ├── Day25RunningTimeandComplexity.cpp │ ├── Day26NestedLogic.cpp │ ├── Day27Testing.cpp │ ├── Day28RegExPatternsAndIntroToDatabases │ │ ├── Day28RegExPatternsAndIntroToDatabases.cpp │ │ └── Day28RegExPatternsAndIntroToDatabases.py │ ├── Day29BitwiseAnd │ │ ├── Day29BitwiseAnd.cpp │ │ └── Day29BitwiseAnd.py │ ├── Day2Operators.cpp │ ├── Day3Conditionalstatements.cpp │ ├── Day4ClassvsInstance.cpp │ ├── Day5Loops.py │ ├── Day6LetsReview.py │ ├── Day7Arrays.py │ ├── Day8DictionariesandMaps.py │ └── Day9Recursion3.py ├── C++ │ ├── AccessingInheritedFunctions.cpp │ ├── ArraysIntroduction.cpp │ ├── BasicDataTypes.cpp │ ├── Boxit.cpp │ ├── Class.cpp │ ├── ClassesAndObjects.cpp │ ├── ConditionalStatements.cpp │ ├── ExceptionalServer.cpp │ ├── ForLoop.cpp │ ├── Functions1.cpp │ ├── InheritanceIntroduction.cpp │ ├── InheritedCode.cpp │ ├── MagicSpells.cpp │ ├── MapsStl.cpp │ ├── Pointer.cpp │ ├── PrintPretty.cpp │ ├── RectangleArea.cpp │ ├── SetsStl.cpp │ ├── StringStream.cpp │ ├── Strings.cpp │ ├── Structs.cpp │ ├── VariablesizedArrays.cpp │ ├── VectorErase.cpp │ └── VectorSort.cpp ├── C │ ├── 1dArraysInC.c │ ├── ArrayReversal.c │ ├── BitwiseOperators.c │ ├── BoxesThroughATunnel.c │ ├── CalculateTheNthTerm.c │ ├── ConditionalStatementsInC.c │ ├── DigitFrequency.c │ ├── ForLoopInC.c │ ├── FunctionsInC.c │ ├── PlayingWithCharacters.c │ ├── PointersInC.c │ ├── Pointers_1.c │ ├── PrintingPatternUsingLoops.c │ ├── PrintingTokens.c │ ├── SmallTrianglesLargeTriangles.c │ ├── StudentsMarksSum.c │ ├── SumAndDifferenceOfTwoNumbers.c │ └── SumOfDigitsOfAFiveDigitNumber.c ├── FunctionalProgramming │ └── HelloWorld.scala ├── InterviewPreparationKit │ └── Trees │ │ └── HeightOfABinaryTree.cpp ├── Java │ ├── Java1DArray.java │ ├── Java2DArray.java │ ├── JavaAbstractClass.java │ ├── JavaAnagrams.java │ ├── JavaCurrencyFormatter.java │ ├── JavaEndOfFile.java │ ├── JavaFactoryPattern.java │ ├── JavaIfElse.java │ ├── JavaInheritance1.java │ ├── JavaInheritance2.java │ ├── JavaInstanceOfKeyword.java │ ├── JavaIntToString.java │ ├── JavaInterface.java │ ├── JavaLoops1.java │ ├── JavaLoops2.java │ ├── JavaMethodOverriding.java │ ├── JavaMethodOverriding2SuperKeyword.java │ ├── JavaOutputFormatting.java │ ├── JavaRegex.java │ ├── JavaRegex2DuplicateWords.java │ ├── JavaStaticInitializerBlock.java │ ├── JavaStdinAndStdout1.java │ ├── JavaStdinAndStdout2.java │ ├── JavaStringReverse.java │ ├── JavaStringTokens.java │ ├── JavaStringsIntroduction.java │ ├── JavaSubArray.java │ ├── JavaSubString.java │ ├── JavaVarargsSimpleAddition.java │ ├── PatternSyntaxChecker.java │ └── WelcomeT.java ├── Problem-Solving │ ├── .vscode │ │ └── settings.json │ ├── Angryprofessor.py │ ├── AppleAndorange.py │ ├── Arrayds.py │ ├── Averybigsum.py │ ├── BeautifulDaysAtTheMovies.py │ ├── BetweenTwoSets.py │ ├── BinarySearchTreeInsertion.cpp │ ├── BirthdayCakeCandles.py │ ├── BirthdayChocolate.py │ ├── BonAppetit.py │ ├── BreakingTheRecords.py │ ├── CaesarCipher.py │ ├── CamelCase.py │ ├── CatsAndAMouse.py │ ├── CircularArrayRotation.py │ ├── CompareTheTriplets.py │ ├── CompareTwoLinkedLists.cpp │ ├── CountingValleys.py │ ├── CycleDetection.cpp │ ├── DayOfTheProgrammer.py │ ├── DeleteANode.cpp │ ├── DesignerPDFViewer.py │ ├── DiagonalDifference │ │ ├── DiagonalDifference.cpp │ │ └── DiagonalDifference.py │ ├── DivisibleSumPairs.py │ ├── DrawingBook.py │ ├── ElectronicsShop.py │ ├── EqualizeTheArray.py │ ├── ExtraLongFactorials.py │ ├── FindDigits.py │ ├── FindTheMedian.cpp │ ├── GetNodeValue.cpp │ ├── GradingStudents.py │ ├── HalloweenSale.py │ ├── InsertANodeAtTheHeadOfALinkedList.cpp │ ├── InsertANodeAtTheTailOfALinkedList.cpp │ ├── InsertionSortPart1.cpp │ ├── InsertionSortPart2.cpp │ ├── IntroToTutorialChallenges.py │ ├── JumpingOnTheClouds.cpp │ ├── Kangaroo.py │ ├── MarsExploration.py │ ├── MergeTwoSortedLinkedLists.cpp │ ├── MigratoryBirds.py │ ├── MinimaxSum.py │ ├── MinimumDistances.py │ ├── Pangrams.py │ ├── PickingNumbers.py │ ├── Plusminus.py │ ├── PrintInReverse.cpp │ ├── PrintTheElementsOfALinkedList.cpp │ ├── RepeatedString.py │ ├── ReverseALinkedList.cpp │ ├── SaveThePrisoner.cpp │ ├── SequenceEquation.py │ ├── SockMerchant.py │ ├── SolveMeFirst.py │ ├── SparseArrays.cpp │ ├── Staircase.py │ ├── TheHurdleRace.py │ ├── TimeConversion.py │ ├── TreeHeightOfABinaryTree.cpp │ ├── TreeInOrderTraversal.cpp │ ├── TreeLevelOrderTraversal.cpp │ ├── TreePostOrderTraversal.cpp │ ├── TreePreOrderTraversal.cpp │ ├── UtopianTree.py │ ├── ViralAdvertising.py │ └── WeightedUniformStrings.py ├── Python │ ├── AnyOrAll.py │ ├── Arrays.py │ ├── AthleteSort.py │ ├── CheckStrictSuperset.py │ ├── CheckSubset.py │ ├── Class2FindTheTorsionalAngle.py │ ├── Collections.Deque.py │ ├── Collections.OrderedDict.py │ ├── CollectionsCounterString.py │ ├── CollectionsNamedTuple.py │ ├── CompanyLogo.py │ ├── CompressTheString.py │ ├── Concatenate.py │ ├── DefaultDictTutorial.py │ ├── DesignerDoormat.py │ ├── DotAndCross.py │ ├── Exceptions.py │ ├── FindTheRunnerupScore.py │ ├── FindingThePercentage.py │ ├── GinortS.py │ ├── GroupGroups&Groupdict.py │ ├── InnerAndOuter.py │ ├── Input.py │ ├── IntroductionToSets.py │ ├── IterToolsCombinationsWithReplacement.py │ ├── IterablesAndIterators.py │ ├── ItertoolsCombinations.py │ ├── ItertoolsPermutations.py │ ├── ItertoolsProduct.py │ ├── LinearAlgebra.py │ ├── ListStringComprehensions.py │ ├── Lists.py │ ├── MapAndLambdaFunction.py │ ├── MaximizeIt.py │ ├── MeanVarAndStd.py │ ├── MinAndMax.py │ ├── ModDivMod.py │ ├── NestedLists.py │ ├── NumpEyeAndIdentity.py │ ├── NumpyArrayMathematics.py │ ├── NumpyFloorCeilAndRint.py │ ├── NumpyZerosAndOnes.py │ ├── PilingUp.py │ ├── Polynomials.py │ ├── Prime.py │ ├── PythonEvaluation.py │ ├── Re.FindAll&Re.FindIter.py │ ├── Re.Start&Re.End.py │ ├── ReduceFunction.py │ ├── RegexSubstitution.py │ ├── ReverseWordAndSwapCases.py │ ├── SetAdd.py │ ├── SetDifferenceString.py │ ├── SetDiscardRemovePop.py │ ├── SetIntersection.py │ ├── SetMutations.py │ ├── SetSymmertricDifference.py │ ├── SetUnion.py │ ├── StringFormatting.py │ ├── SumAndProd.py │ ├── TextAlignment.py │ ├── TextWrap.py │ ├── TheCaptainsRoom.py │ ├── TransposeAndFlatten.py │ ├── Tuples.py │ ├── WordOrder.py │ ├── WordsScore.py │ └── WriteAFunction.py └── Sql │ ├── AfricanCities.sql │ ├── AsianPopulation.sql │ ├── AveragePopulation.sql │ ├── AveragePopulationOfEachContinent.sql │ ├── BinaryTreeNodes.sql │ ├── DrawTheTriangle1.sql │ ├── DrawTheTriangle2.sql │ ├── HigherThan75Marks.sql │ ├── JapanPopulation.sql │ ├── Placements.sql │ ├── PopulationDensityDifference.sql │ ├── PrintPrimeNumbers.sql │ ├── RevisingAggregationsAverages.sql │ ├── RevisingAggregationsTheCountFunction.sql │ ├── RevisingAggregationsTheSumFunction.sql │ ├── SelectSecondMax.sql │ ├── TheBlunder.sql │ ├── TheReport.sql │ ├── TopEarners.sql │ ├── TypeOfTriangle.sql │ ├── WeaTherObservationStation2.sql │ ├── WeatherObservationStation10.sql │ ├── WeatherObservationStation11.sql │ ├── WeatherObservationStation12.sql │ ├── WeatherObservationStation13.sql │ ├── WeatherObservationStation14.sql │ ├── WeatherObservationStation15.sql │ ├── WeatherObservationStation16.sql │ ├── WeatherObservationStation17.sql │ ├── WeatherObservationStation18.sql │ ├── WeatherObservationStation19.sql │ ├── WeatherObservationStation5.sql │ ├── WeatherObservationStation7.sql │ ├── WeatherObservationStation8.sql │ └── WeatherObservationStation9.sql ├── JavaFiles ├── Applet │ ├── HelloJava.html │ ├── HelloWorld.class │ └── HelloWorld.java ├── Constructors │ ├── Constructor Overloading │ │ ├── ABCCollege.java │ │ └── Student.java │ ├── Non Argument Constructors │ │ ├── ConsDemo.class │ │ ├── MyClass.class │ │ └── MyClass.java │ └── Parameterized Constructors │ │ ├── ConsDemo.class │ │ ├── ConsDemo.java │ │ └── MyClass.class └── ObjectsAndClasses │ ├── Employee.class │ ├── Employee.java │ ├── EmployeeTest.class │ └── EmployeeTest.java ├── LICENSE ├── LeetCode ├── .directory ├── Algorithms │ ├── .vscode │ │ └── settings.json │ ├── Easy │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── 1bitAnd2bitCharacters.cpp │ │ ├── ArrayPartition1.cpp │ │ ├── BackspaceStringCompare.cpp │ │ ├── BestTimeToBuyAndSellStock │ │ │ ├── BestTimeToBuyAndSellStockM1.cpp │ │ │ └── BestTimeToBuyAndSellStockM2.cpp │ │ ├── BestTimeToBuyAndSellStockII.cpp │ │ ├── BigCountries.sql │ │ ├── BinaryTreeInorderTraversal.cpp │ │ ├── BinaryTreeLevelOrderTraversal.cpp │ │ ├── BinaryWatch.cpp │ │ ├── BuddyStrings.py │ │ ├── CalculateMoneyInLeetCodeBank.cpp │ │ ├── CanPlaceFlowers.cpp │ │ ├── CheckIfAll1sAreAtLeastLengthKAway.cpp │ │ ├── ClassesMoreThan5Students.sql │ │ ├── ClimbingStairs.cpp │ │ ├── Contains_Duplicate │ │ │ ├── ContainsDuplicateM1.cpp │ │ │ └── ContainsDuplicateM2.cpp │ │ ├── ConvertBinaryNumberInALinkedListToInteger.cpp │ │ ├── ConvertSortedArrayToBinarySearchTree.cpp │ │ ├── CountDaysSpentTogether.py │ │ ├── CountGoodTriplets.cpp │ │ ├── CountNumberOfHomogenousSubstrings.cpp │ │ ├── CountOfMatchesInTournament.cpp │ │ ├── CountSquareSumTriples.cpp │ │ ├── DecodeXoredArray.cpp │ │ ├── DefangingAnIPAddress │ │ │ ├── DefangingAnIPAddress.cpp │ │ │ └── DefangingAnIPAddress.py │ │ ├── DeleteCharactersToMakeFancyString.cpp │ │ ├── DesignAddAndSearchWordsDataStructure.cpp │ │ ├── DesignAnOrderedStream.cpp │ │ ├── DesignParkingSystem.cpp │ │ ├── DetermineIfStringHalvesAreAlike.py │ │ ├── DiameterOfBinaryTree.cpp │ │ ├── DistanceBetweenBusStops.cpp │ │ ├── DistributeCandies │ │ │ ├── DistributeCandies.cpp │ │ │ └── DistributeCandies.py │ │ ├── DistributeMoneyToMaximumChildren.cpp │ │ ├── ExcelSheetColumnNumber.cpp │ │ ├── Fibonacci_Number │ │ │ ├── FibonacciNumber.cpp │ │ │ ├── FibonacciNumberDP.cpp │ │ │ └── a.out │ │ ├── FindAllNumbersDisappearedInAnArray.cpp │ │ ├── FindCommonCharacters.cpp │ │ ├── FindModeInBinarySearchTree │ │ │ └── FindModeInBinarySearchTree.java │ │ ├── FindNumbersWithEvenNumberOfDigits.cpp │ │ ├── FindPivotIndex.cpp │ │ ├── FindTheDifference.cpp │ │ ├── FindTheDuplicateNumber │ │ │ ├── FindTheDuplicateNumberExtraSpace.cpp │ │ │ └── FindTheDuplicateNumberWithoutSpace.cpp │ │ ├── FindTheHighestAltitude.cpp │ │ ├── FindTheIndexOfTheFirstOccurrenceInAString.cpp │ │ ├── FindTheTownJudge │ │ │ └── FindTheTownJudge.java │ │ ├── FindWordsThatCanBeFormedByCharacters.cpp │ │ ├── FirstBadVersion.cpp │ │ ├── FizzBuzz.cpp │ │ ├── FlippingAnImage.cpp │ │ ├── GoalParserInterpretation.cpp │ │ ├── GuessNumberHigherOrLower.cpp │ │ ├── HappyNumber.cpp │ │ ├── HowManyNumbersAreSmallerThantheCurrentNumber.cpp │ │ ├── ImplementQueueUsingStacks.cpp │ │ ├── IncreasingOrderSearchTree.cpp │ │ ├── IntersectionOfTwoArrays.cpp │ │ ├── IntersectionOfTwoArraysII.cpp │ │ ├── Intersection_of_two_linked_lists.cpp │ │ ├── InvertBinaryTree.cpp │ │ ├── IslandPerimeter.cpp │ │ ├── JewelsAndStones │ │ │ ├── JewelsAndStones.cpp │ │ │ └── JewelsAndStones.py │ │ ├── KidsWiththeGreatestNumberofCandies.cpp │ │ ├── LemonadeChange.cpp │ │ ├── LengthOfLastWord.cpp │ │ ├── LicenseKeyFormatting.cpp │ │ ├── LinkedListCycle.cpp │ │ ├── LongestCommonPrefix.cpp │ │ ├── LongestHarmoniousSubsequence.cpp │ │ ├── LongestPalindrome.cpp │ │ ├── MajorityElement.cpp │ │ ├── MatrixDiagonalSum.cpp │ │ ├── MaxConsecutiveOnes.cpp │ │ ├── MaximumDepthOfNaryTree.cpp │ │ ├── MaximumDepthofBinaryTree.cpp │ │ ├── MaximumProductDifferenceBetweeTwoPairs │ │ │ ├── MaximumProductDifferenceBetweenTwoPairs.cpp │ │ │ └── MaximumProductDifferenceBetweenTwoPairs.py │ │ ├── MaximumRepeatingSubstring.cpp │ │ ├── MaximumSubarray_(KadaneAlgorithm).cpp │ │ ├── MaximumUnitsOnATruck.cpp │ │ ├── MergeSortedArray.cpp │ │ ├── MergeTwoBinaryTrees.cpp │ │ ├── MergeTwoSortedLists.cpp │ │ ├── MiddleOfTheLinkedList.cpp │ │ ├── MinCostClimbingStairs.cpp │ │ ├── MinStack.cpp │ │ ├── MinimumChangesToMakeAlternatingBinaryString.py │ │ ├── MinimumDepthofBinaryTree.cpp │ │ ├── MissingNumber.cpp │ │ ├── MostCommonWord.cpp │ │ ├── MoveZeroes.cpp │ │ ├── NArrayTreePostorderTraversal.cpp │ │ ├── NArrayTreePreorderTraversal.cpp │ │ ├── NthTribonacciNumber.cpp │ │ ├── NumberOfRecentCalls.cpp │ │ ├── NumberOfStudentsUnableToEatLunch.cpp │ │ ├── Number_of_1_Bits │ │ │ ├── NumberOf1Bits.cpp │ │ │ └── NumberOf1Bits.py │ │ ├── NumberofGoodPairs.cpp │ │ ├── NumberofStepsReduceNumbertoZero.cpp │ │ ├── PalindromeNumber.cpp │ │ ├── Palindrome_Linked_List │ │ │ ├── PalindromeLinkedListM1.cpp │ │ │ └── PalindromeLinkedListM2.cpp │ │ ├── PascalsTriangle │ │ │ ├── PascalsTriangle.cpp │ │ │ ├── PascalsTriangle.java │ │ │ └── PascalsTriangle.py │ │ ├── PathSum.cpp │ │ ├── PeakIndexInAMountainArray.cpp │ │ ├── PlusOne.cpp │ │ ├── RangeSumofBST.cpp │ │ ├── RemoveAllAdjacentDuplicatesInString.cpp │ │ ├── RemoveDuplicatesFromSortedArray.cpp │ │ ├── RemoveElement.cpp │ │ ├── RemoveLinkedListElements.cpp │ │ ├── RemoveOneElementToMakeTheArrayStrictlyIncreasing.cpp │ │ ├── ReverseInteger.cpp │ │ ├── ReverseLinkedList.cpp │ │ ├── ReverseOnlyLetters.cpp │ │ ├── ReverseString.cpp │ │ ├── ReverseWordsInAString3.cpp │ │ ├── RichestCustomerWealth.cpp │ │ ├── RobotReturnToOrigin.cpp │ │ ├── RomanToInteger.cpp │ │ ├── RotateString.cpp │ │ ├── RunningSumof1DArray.cpp │ │ ├── SameTree │ │ │ ├── SameTree.cpp │ │ │ └── SameTree.java │ │ ├── SearchInABinarySearchTree.cpp │ │ ├── SearchIndexPosition.cpp │ │ ├── SelfDividingNumbers.cpp │ │ ├── ShortestDistanceToACharacter.cpp │ │ ├── ShuffleString.cpp │ │ ├── ShuffleTheArray.cpp │ │ ├── SingleNumber.cpp │ │ ├── SmallestRangeI.cpp │ │ ├── SortArrayByParity.cpp │ │ ├── SortArrayByParity2.cpp │ │ ├── SplitAStringInBalancedStrings.cpp │ │ ├── Sqrt(x).cpp │ │ ├── SquaresOfASortedArray.cpp │ │ ├── SubtractProductSumofDigits.cpp │ │ ├── SubtreeOfAnotherTree.cpp │ │ ├── SumOfEvenNumbersAfterQueries.cpp │ │ ├── SumOfLeftLeaves.cpp │ │ ├── SymmetricTree.cpp │ │ ├── TheKWeakestRowsInAMatrix.cpp │ │ ├── ToLowerCase.cpp │ │ ├── TransposeMatrix.cpp │ │ ├── TwoSum.cpp │ │ ├── TwoSum2InputArrayIsSorted.cpp │ │ ├── UniqueBinarySearchTrees.cpp │ │ ├── UniqueEmailAddresses.cpp │ │ ├── UniqueMorseCodeWords.cpp │ │ ├── UnivaluedBinaryTree.cpp │ │ ├── ValidAnagram.cpp │ │ ├── ValidMountainArray.cpp │ │ ├── ValidPalindrome.cpp │ │ ├── ValidPalindrome2.cpp │ │ ├── ValidParentheses.cpp │ │ ├── ValidPhoneNumbers.sh │ │ ├── VerifyingAnAlienDictionary.cpp │ │ └── XorOperationInAnArray.cpp │ ├── Hard │ │ ├── BasicCalculator.cpp │ │ ├── BestTimeToBuyAndSellStockIII.cpp │ │ ├── BestTimeToBuyAndSellStockIV.cpp │ │ ├── BinaryTreeMaximumPathSum.cpp │ │ ├── BusRoutes.cpp │ │ ├── CherryPickup2.cpp │ │ ├── ConstructTargetArrayWithMultipleSums.cpp │ │ ├── CountVowelsPermutation.cpp │ │ ├── CourseSchedule3.cpp │ │ ├── DataStreamAsDisjointIntervals.cpp │ │ ├── EditDistance.cpp │ │ ├── ErectTheFence.cpp │ │ ├── FindMedianFromDataStream.cpp │ │ ├── FindTheLongestValidObstacleCourseAtEachPosition.cpp │ │ ├── FindTheMaximumSumOfNodeValues.cpp │ │ ├── KInversePairsArray.cpp │ │ ├── LongestCycleInAGraph.cpp │ │ ├── LongestValidParentheses.cpp │ │ ├── LongestZigZagPathInABinaryTree.cpp │ │ ├── MaxPointsOnALine.cpp │ │ ├── MaxSumOfRectangleNoLargerThanK.cpp │ │ ├── MaximumPerformanceOfATeam.cpp │ │ ├── MeetingRoomsIII.cpp │ │ ├── MinimumCostToCutAStick.cpp │ │ ├── MinimumDifficultyOfAJobSchedule.cpp │ │ ├── MinimumFallingPathSumII.cpp │ │ ├── MinimumInsertionStepsToMakeAStringPalindrome.cpp │ │ ├── MinimumNumberOfKConsecutiveBitFlips.cpp │ │ ├── MinimumNumberOfRefuelingStops.cpp │ │ ├── NQueens.cpp │ │ ├── NearestExitFromEntranceInMaze.cpp │ │ ├── NumberOfAtoms.cpp │ │ ├── NumberOfSubmatricesThatSumToTarget.cpp │ │ ├── NumberOfWaysToFormATargetStringGivenADictionary.cpp │ │ ├── OddEvenJump.cpp │ │ ├── OrderlyQueue.cpp │ │ ├── PaintHouseIII.cpp │ │ ├── PaintingTheWalls.cpp │ │ ├── PalindromePairs.cpp │ │ ├── ParsingABooleanExpression │ │ │ └── ParsingABooleanExpression.java │ │ ├── PoorPigs.cpp │ │ ├── PrefixAndSuffixSearch.cpp │ │ ├── PrefixAndSuffixSearch.java │ │ ├── PrefixAndSuffixSearch_explanation.txt │ │ ├── ProfitableSchemes.cpp │ │ ├── ReducingDishes.cpp │ │ ├── RemoveMaxNumberOfEdgesToKeepGraphFullyTraversable.cpp │ │ ├── RestoreTheArray.cpp │ │ ├── RussianDollEnvelops.cpp │ │ ├── ShortestPathVisitingAllNodes.cpp │ │ ├── StampingTheSequence.cpp │ │ ├── StringCompressionII.cpp │ │ ├── SumOfDistancesInTree.cpp │ │ ├── TheSkylineProblem.cpp │ │ ├── TrappingRainWater.cpp │ │ ├── UniquePathsIII.cpp │ │ ├── VerticalOrderTraversalOfABinaryTree.cpp │ │ ├── WordBreak2.cpp │ │ ├── WordLadder.cpp │ │ └── WordSearchII.cpp │ └── Medium │ │ ├── .vscode │ │ └── settings.json │ │ ├── 3Sum.cpp │ │ ├── 3SumClosest.cpp │ │ ├── AddTwoNumbers.cpp │ │ ├── AllPathsFromSourceToTarget.cpp │ │ ├── AllPossibleFullBinaryTrees.cpp │ │ ├── ArithmeticSubarrays.cpp │ │ ├── AsFarFromLandAsPossible.cpp │ │ ├── AverageWaitingTime.cpp │ │ ├── BagOfTokens.cpp │ │ ├── BeautfulArray.cpp │ │ ├── BeautifulArray.cpp │ │ ├── BestTeamWithNoConflicts.cpp │ │ ├── BestTimeToBuyAndSellStockWithCooldown.cpp │ │ ├── BestTimeToBuyAndSellStockWithTransaction.cpp │ │ ├── BinaryTreeInorderTraversal.cpp │ │ ├── BinaryTreeLevelOrderTraversal.cpp │ │ ├── BinaryTreePruning.cpp │ │ ├── BinaryTreeRightSideView.cpp │ │ ├── BreakAPalindrome.cpp │ │ ├── CapacityToShipPackagesWithinDDays.cpp │ │ ├── ChampagneTower.cpp │ │ ├── CheckCompletenessOfaBinaryTree.cpp │ │ ├── CoinChange.cpp │ │ ├── CoinChange2.cpp │ │ ├── CombinationSum.cpp │ │ ├── CombinationSumIV.cpp │ │ ├── ConcatenationOfConsecutiveBinaryNumbers.py │ │ ├── ConcatenationOfConsecutiveBinaryNumbers │ │ └── ConcatenationOfConsecutiveBinaryNumbers.py │ │ ├── ConstructBinaryTreeFromInorderAndPostorderTraversal.cpp │ │ ├── ConstructBinaryTreeFromPreorderAndInorderTraversal.cpp │ │ ├── ConstructBinaryTreeFromPreorderAndPostorderTraversal.cpp │ │ ├── ConstructQuadTree.cpp │ │ ├── ContainerWithMostWater.cpp │ │ ├── ContinuousSubarraySum.cpp │ │ ├── ConvertBSTtoGreaterTree.cpp │ │ ├── ConvertSortedListToBinarySearchTree.cpp │ │ ├── CountAndSay.cpp │ │ ├── CountCompleteTreeNodes.cpp │ │ ├── CountGoodNodesInBinaryTree.cpp │ │ ├── CountNodesEqualToAverageOfSubtree.cpp │ │ ├── CountSortedVowelStrings.cpp │ │ ├── CountSquareSubMatricesWithAllOnes │ │ └── CountSquareSubMatricesWithAllOnes.java │ │ ├── CountSubIslands.cpp │ │ ├── CountSubarraysWhereMaxElementAppearsAtLeastKTimes.cpp │ │ ├── CountSubarraysWithFixedBounds.cpp │ │ ├── CousinsInBinaryTreeII.cpp │ │ ├── DecodedStringAtIndex.cpp │ │ ├── DeepestLeavesSum │ │ └── DeepestLeavesSum.java │ │ ├── DesignCircularQueue.cpp │ │ ├── DesignFrontMiddleBackQueue.cpp │ │ ├── DesignUndergroundSystem.cpp │ │ ├── DistributeCoinsInBinaryTree.cpp │ │ ├── DominoAndTrominoTiling.cpp │ │ ├── EarliestPossibleDayOfFullBloom.cpp │ │ ├── EliminateMaximumNumberOfMonsters.cpp │ │ ├── EncodeAndDecodeTinyURL.cpp │ │ ├── FillingBookcaseShelves.cpp │ │ ├── FindACorrespondingNodeOfABinaryTreeInACloneOfThatTree.cpp │ │ ├── FindBottomLeftTreeValue.cpp │ │ ├── FindDuplicateFileInSystem.cpp │ │ ├── FindDuplicateFileInSystem.java │ │ ├── FindDuplicateSubtrees.cpp │ │ ├── FindFirstAndLastPositionOfElementInSortedArray.cpp │ │ ├── FindLargestValueInEachTreeRow.cpp │ │ ├── FindPeakElement.cpp │ │ ├── FindTheDuplicateNumber.cpp │ │ ├── FindTheIndexOfTheFirstOccurrenceInAString.cpp │ │ ├── FindTheMostCompetitiveSubsequence.cpp │ │ ├── FlattenBinaryTreeToLinkedList.cpp │ │ ├── FlattenNestedListIterator.cpp │ │ ├── FruitIntoBaskets.cpp │ │ ├── GenerateParantheses │ │ └── GenerateParantheses.java │ │ ├── GlobalAndLocalInversion │ │ ├── GlobalAndLocalInversion.java │ │ └── GlobalAndLocalInversions.cpp │ │ ├── GrayCode.cpp │ │ ├── HandOfStraights.cpp │ │ ├── HandOfStraights │ │ ├── HandOfStraights.cpp │ │ └── HandOfStraights.java │ │ ├── HouseRobber │ │ ├── HouseRobber.cpp │ │ └── HouseRobber.java │ │ ├── ImageOverlap.cpp │ │ ├── ImplementTrie.cpp │ │ ├── InsertDeleteGetRandom.cpp │ │ ├── InsertIntoBinarySearchTree.cpp │ │ ├── IntegerBreak.cpp │ │ ├── IsGraphBipartite.cpp │ │ ├── JumpGame.cpp │ │ ├── JumpGame2.cpp │ │ ├── JumpGame4.cpp │ │ ├── KeysAndRooms.cpp │ │ ├── KokoEatingBananas.cpp │ │ ├── KthLargestElementInAnArray │ │ ├── KthLargestElementInAnArray.cpp │ │ └── KthLargestElementInAnArray.java │ │ ├── KthSmallestElementInABST.cpp │ │ ├── LRUCache.cpp │ │ ├── LetterCombinationsOfAPhoneNumber.cpp │ │ ├── LexicographicallySmallestEquivalentString.cpp │ │ ├── LinkedListRandomNode.cpp │ │ ├── LongestBinarySubsequenceLessThanOrEqualToK.cpp │ │ ├── LongestCommonSubsequence.cpp │ │ ├── LongestConsecutiveSequence │ │ └── LongestConsecutiveSequence.java │ │ ├── LongestContinuousSubarrayWithAbsoluteDiffLessThanOrEqualToLimit.cpp │ │ ├── LongestIncreasingSubsequence.cpp │ │ ├── LongestPalindromeSubstring.cpp │ │ ├── LongestSubstringWithoutRepeatingCharacters.cpp │ │ ├── MagicSquaresInGrid.cpp │ │ ├── MagicalIndicesInAnArray.java │ │ ├── MakeSumDivisibleByP.cpp │ │ ├── MatrixBlockSum.cpp │ │ ├── MaxIncreaseToKeepCitySkyline.cpp │ │ ├── MaxNumberOfKSumPairs │ │ ├── MaxNumberOfKSumPairs.cpp │ │ └── MaxNumberOfKSumPairs.py │ │ ├── MaximalSquare.cpp │ │ ├── MaximumErasureValue.cpp │ │ ├── MaximumLengthOfAConcatenatedStringWithUniqueCharacters.cpp │ │ ├── MaximumLengthOfRepeatedSubarray.cpp │ │ ├── MaximumLengthOfSubarrayWithPositiveProduct.cpp │ │ ├── MaximumNumberOfGroupsEnteringACompetition.cpp │ │ ├── MaximumNumberOfPointsWithCost.cpp │ │ ├── MaximumProductOfWordLengths.cpp │ │ ├── MaximumProfitInJobScheduling.cpp │ │ ├── MaximumRowsCoveredByColumns.cpp │ │ ├── MaximumScoreFromPerformingMultiplicationOperations.cpp │ │ ├── MaximumSwaps │ │ └── MaximumSwaps.java │ │ ├── MaximumTotalImportanceOfRoads.java │ │ ├── MaximumWidthOfBinaryTree.cpp │ │ ├── MergeInBetweenLinkedLists.cpp │ │ ├── MergeIntervals.cpp │ │ ├── MinCostToConnectAllPoints.cpp │ │ ├── MinimizeDeviationInArray.cpp │ │ ├── Minimum SwapstoGroupAll1sTogetherII.cpp │ │ ├── MinimumCostForTickets.cpp │ │ ├── MinimumFallingPathSum.cpp │ │ ├── MinimumFuelCostToReportToTheCapital.cpp │ │ ├── MinimumGeneticMutation.cpp │ │ ├── MinimumNumberOfArrowsToBurstBalloons.cpp │ │ ├── MinimumNumberOfRungs.cpp │ │ ├── MinimumOperationsToReduceXToZero.cpp │ │ ├── MinimumPathSum.cpp │ │ ├── MinimumRemoveToMakeValidParantheses │ │ └── MinimumRemoveToMakeValidParantheses.java │ │ ├── MinimumSizeSubarraySum.cpp │ │ ├── MinimumTimeToCollectAllApplesInATree.cpp │ │ ├── MinimumWindowSubstring.cpp │ │ ├── MonotonicArray │ │ └── MonotonicArray.java │ │ ├── NAryTreeLevelOrderTraversal.cpp │ │ ├── NearestExitFromEntranceInMaze.cpp │ │ ├── NextPermutation.cpp │ │ ├── NonDecreasingArray.cpp │ │ ├── NonDecreasingSubsequences.cpp │ │ ├── NumberOfIslands.cpp │ │ ├── NumberOfNodesInTheSubTreeWithTheSameLabel.cpp │ │ ├── NumberOfProvinces.cpp │ │ ├── NumbersWithSameConsecutiveDifferences.cpp │ │ ├── OddEvenLinkedList.cpp │ │ ├── OnesAndZeroes.cpp │ │ ├── OpenTheLock.cpp │ │ ├── PalindromePartitioning.cpp │ │ ├── ParitioningIntoMinimumNumberOfDeciBinaryNumbers.cpp │ │ ├── PartitionLabels.cpp │ │ ├── PartitionList.cpp │ │ ├── PascalTriangleII │ │ └── PascalTriangleII.java │ │ ├── PathWithMinimumEffort.cpp │ │ ├── PerfectSquares.cpp │ │ ├── PermutationInString.cpp │ │ ├── PossibleBipartition.cpp │ │ ├── PrefixTreeOrTrie.notes.txt │ │ ├── ProductOfArrayExceptSelf.cpp │ │ ├── PushDominoes.cpp │ │ ├── QueensThatCanAttackTheKing │ │ └── QueensThatCanAttackTheKing.java │ │ ├── RangeSumQuery2D_Immutable.cpp │ │ ├── RemoveKDigits.cpp │ │ ├── RemoveNthNodeFromEndOfList.cpp │ │ ├── RemoveSubFoldersFromTheFileSystem │ │ └── RemoveSubFoldersFromTheFileSystem.java │ │ ├── ReorderList.cpp │ │ ├── ReorderedPowerOf2.cpp │ │ ├── RestoreIPAddresses.cpp │ │ ├── ReverseLinkedList2.cpp │ │ ├── RotateArray │ │ ├── RotateArray.cpp │ │ └── RotateArray.java │ │ ├── SatisfiabilityOfEqualityEquations.cpp │ │ ├── ScoreOfParentheses │ │ └── ScoreOfParentheses.java │ │ ├── SearchA2DMatrix.cpp │ │ ├── SearchA2DMatrix2.cpp │ │ ├── SearchInRotatedSortedArray.cpp │ │ ├── SearchInRotatedSortedArray2.cpp │ │ ├── SearchSuggestionsSystem.cpp │ │ ├── SecondMinimumNodeInABinaryTree.cpp │ │ ├── SenderWithLargestWordCount.java │ │ ├── SetMatrixZeroes.cpp │ │ ├── ShortestPathInAGridWithObstaclesElimination.cpp │ │ ├── ShortestPathWithAlternatingColors.cpp │ │ ├── ShortestUnsortedContinuousSubarray │ │ └── ShortestUnsortedContinuousSubarray.java │ │ ├── SimplifyPath.cpp │ │ ├── SmallestIntegerDivisiblebyK.cpp │ │ ├── SmallestStringStartingFromLeaf.cpp │ │ ├── SmallestStringWithSwaps.cpp │ │ ├── SnakesAndLadders.cpp │ │ ├── SortColors.cpp │ │ ├── SortList.cpp │ │ ├── SpiralMatrix.cpp │ │ ├── SpiralMatrix2.cpp │ │ ├── StringCompression.cpp │ │ ├── SubarrayProductLessThanK │ │ └── SubarrayProductLessThanK.java │ │ ├── SubarraySumEqualsK.cpp │ │ ├── Subsets.cpp │ │ ├── SumOfSubarrayMinimums.cpp │ │ ├── SurroundedRegions │ │ └── SurroundedRegions.java │ │ ├── SwapNodesInPairs.cpp │ │ ├── SwappingNodesInALinkedList.cpp │ │ ├── TaskSchedular │ │ ├── TaskSchedular.cpp │ │ └── TaskSchedular.java │ │ ├── TheKthFactorOfN.cpp │ │ ├── TheNumberOfFullRoundsYouHavePlayed.cpp │ │ ├── Triangle.cpp │ │ ├── TrimABinarySearchTree.cpp │ │ ├── UTF8Validation.cpp │ │ ├── UncrossedLines.cpp │ │ ├── UniqueBinarySearchTrees.cpp │ │ ├── UniqueLength3PalindromicSubsequences.cpp │ │ ├── UniquePaths.cpp │ │ ├── ValidSudoku │ │ ├── ValidSudoku.cpp │ │ └── ValidSudoku.java │ │ ├── ValidateBinarySearchTree.cpp │ │ ├── ValidateStackSequences.cpp │ │ ├── WhereWillTheBallFall.cpp │ │ ├── WordBreak.cpp │ │ ├── WordSearch.cpp │ │ ├── WordSubsets.cpp │ │ └── ZigzagConversion.cpp ├── Database │ ├── DuplicateSalary.sql │ ├── EmployeesEarningMoreThanTheirManagers.sql │ └── SecondHighestSalary.sql ├── Monthly Challenges │ ├── 2022_Challenges │ │ └── JanuaryChallenge │ │ │ └── PairsOfSongsWithTotalDurationDivisibleBy60.cpp │ ├── December_LeetCoding_Challenge │ │ └── Day2LinkedListRandomNode.cpp │ ├── November_LeetCoding_Challenge │ │ └── ConsecutiveCharacters │ │ │ ├── ConsecutiveCharacters.cpp │ │ │ └── ConsecutiveCharacters.py │ └── October_LeetCoding_Challenge │ │ ├── Day11_Remove_Duplicate_Letters │ │ └── Day11RemoveDuplicateLetters.cpp │ │ ├── Day13_Sort_List │ │ └── Day13SortList.java │ │ ├── Day14_House_Robber_II │ │ └── Day14HouseRobberII.java │ │ ├── Day15_Rotate_Array │ │ ├── Day15RotateArray.cpp │ │ └── Day15RotateArray.java │ │ ├── Day16_Search_A_2D_Matrix │ │ ├── Day16SearchA2DMatrix.cpp │ │ └── Day16SearchA2DMatrix.java │ │ ├── Day1_Number_of_Recent_Calls │ │ ├── Day1NumberOfRecentCalls.cpp │ │ └── Day1NumberOfRecentCalls.java │ │ ├── Day2_Combination_Sum │ │ ├── Day2CombinationSum.cpp │ │ └── Day2CombinationSum.java │ │ ├── Day3_Kdiff_Pairs_in_an_Array │ │ ├── Day3KDiffPairsInAnArray.cpp │ │ └── Day3KDiffPairsInAnArray.java │ │ ├── Day4_Remove_Covered_Intervals │ │ ├── Day4RemoveCoveredIntervals.cpp │ │ └── Day4RemoveCoveredIntervals.java │ │ ├── Day5_Complement_of_Base_10_Integer │ │ ├── Day5ComplementOfBase10Integer.java │ │ └── Day5ComplementOfBase10Integer.py │ │ ├── Day6_Insert_into_a_Binary_Search_Tree │ │ ├── Day6InsertIntoABinarySearchTree.cpp │ │ └── Day6InsertIntoABinarySearchTree.java │ │ ├── Day7_Rotate_List │ │ ├── Day7RotateList.cpp │ │ └── Day7RotateList.java │ │ ├── Day8_Binary_Search │ │ ├── Day8BinarySearch.cpp │ │ └── Day8BinarySearch.java │ │ └── Day9_Serialize_And_Deserialize_BST │ │ └── Day9SerializeAndDeserializeBST.java ├── PreparationGuide.md └── Top Interview Questions │ ├── Top_Interview_Questions_Easy │ ├── Array │ │ ├── BestTimetoBuyAndSellStock.cpp │ │ ├── ContainsDuplicates.cpp │ │ ├── DeleteNodeInALinkedList.cpp │ │ ├── IntersectionOfTwoArrays2.cpp │ │ ├── MaximumDepthOfBinaryTree.cpp │ │ ├── MoveZeros.cpp │ │ ├── RemoveDuplicatesFromSortedArray.cpp │ │ ├── RotateArray.cpp │ │ ├── RotateMatrix │ │ │ ├── RotateImage.cpp │ │ │ └── RotateMatrixAntiClockwise.cpp │ │ ├── SingleNumber.cpp │ │ ├── TwoSum.cpp │ │ ├── intersectionOfTwoArrays2.py │ │ ├── plusOne.py │ │ └── validSudoku.cpp │ ├── Strings │ │ ├── First Unique Character in a String │ │ │ ├── FirstUniqueCharacterInString.py │ │ │ └── FirstUniqueCharacterinString.cpp │ │ ├── ReverseInteger │ │ ├── ReverseInteger.cpp │ │ ├── a.out │ │ └── reverseString │ │ │ ├── reverseString.cpp │ │ │ └── reverseString.py │ └── Trees │ │ ├── BinaryTreeLevelOrderTraversal.cpp │ │ ├── MaximumDepthOfBinaryTree.cpp │ │ └── SymmetricTree.cpp │ └── Top_Interview_Questions_Medium │ └── Trees │ ├── BinaryTreeInorderTraversal.cpp │ └── SetMatrixZeros.cpp ├── MSLearn └── MissingPersons.py ├── MyNotes └── dataHiding.md ├── Notes.txt ├── Practice ├── codeSnippets.cpp ├── codeSnippets.cpp~ ├── isPrime.java └── printUnorderedPairs.java ├── README.md ├── StarredProblems ├── BetweenTwoSets.py ├── BinaryTreeNodes.sql ├── CheckIfPrimeNumber.cpp ├── Cognizant │ ├── ConvertBinaryToDecimal.cpp │ ├── PrimeNumbersUptoN.cpp │ ├── PrintDoubleQuotes.cpp │ └── a.out ├── CompressTheString.py ├── CycleDetection.cpp ├── DesignerDoorMat.py ├── DetectFloatingPointNumber.py ├── DigitFrequency.c ├── ExceptionalServer.cpp ├── ExceptionalServerExplaination.txt ├── GivenPointerDeleteNode.cpp ├── Group()Groups()&Groupdict().py ├── IterablesAndIterators.py ├── MaximizeIt.py ├── NumpyFloorCeilAndRint.py ├── PickingNumbers.py ├── PilingUp.py ├── Re.findall()&Re.finditer().py ├── Re.start()&Re.end().py ├── TopEarners.sql ├── WordOrder.py └── a.out ├── TopicWise ├── Linked List │ ├── IntersectionOfLinkedLists.cpp │ ├── MergeSortLinkedList.cpp │ ├── ReverseLinkedListRecursive.cpp │ ├── StackUsingLL.cpp │ └── detectLoopInLL.cpp └── StacksAndQueues │ ├── ParenthesisChecker.cpp │ ├── PrefixEvaluation.cpp │ └── stacksUsingArray.cpp ├── Worktech ├── Hard │ ├── BestTimeToBuyAndSellStockIII.java │ ├── InsertMinimumToMakePalindrome.java │ ├── RegularExpressionMatching.java │ ├── RestaurantReviews.java │ ├── SlidingWindowMaximum.java │ └── –MedianFromDataStream.java └── Medium │ ├── BinaryTreeZigZagLevelOrderTraversal.java │ ├── CompareVersionNumber.java │ ├── FourSum.java │ ├── SearchRotatedSortedArray.java │ └── TrainsAndPlatform.java └── w3school-Python ├── ClassInheritence.py ├── Classes.py └── Dictionaries.py /.github/workflows/issues_labeler.yml: -------------------------------------------------------------------------------- 1 | name: "Issue Labeler" 2 | on: 3 | issues: 4 | types: [opened, edited] 5 | 6 | jobs: 7 | triage: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: github/issue-labeler@v2.0 11 | with: 12 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 13 | configuration-path: .github/issues_labeler.yml 14 | enable-versioned-regex: 0 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp", 4 | "ios": "cpp", 5 | "xiosbase": "cpp" 6 | } 7 | } -------------------------------------------------------------------------------- /CheatSheets/BigOCheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CheatSheets/BigOCheatsheet.pdf -------------------------------------------------------------------------------- /CheatSheets/CPP-Cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CheatSheets/CPP-Cheatsheet.pdf -------------------------------------------------------------------------------- /CheatSheets/STLQuickReference1.29.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CheatSheets/STLQuickReference1.29.pdf -------------------------------------------------------------------------------- /CheatSheets/UserfulLinks.md: -------------------------------------------------------------------------------- 1 | # Usefull Links 2 | 3 | [https://www.bigocheatsheet.com/](https://www.bigocheatsheet.com/) 4 | -------------------------------------------------------------------------------- /CodeChefProblems/ChefAndOperatorsCHOPRT.py: -------------------------------------------------------------------------------- 1 | # cook your dish here 2 | try: 3 | n = int(input()) 4 | for i in range(n): 5 | x, y = list(map(int, input().split())) 6 | if(x < y): 7 | print("<") 8 | if(x > y): 9 | print(">") 10 | if(x == y): 11 | print("=") 12 | except: 13 | pass 14 | -------------------------------------------------------------------------------- /CodeChefProblems/ChefAndRemissnessREMISS.py: -------------------------------------------------------------------------------- 1 | # cook your dish here 2 | try: 3 | n = int(input()) 4 | for i in range(n): 5 | x, y = list(map(int, input().split())) 6 | if(x 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | int t; 8 | cin >> t; 9 | int temp = t; 10 | while (t--) 11 | { 12 | if (t != temp - 1) 13 | cout << endl; 14 | 15 | int N, K; 16 | cin >> N >> K; 17 | // K is height 18 | // ith box has height Hi 19 | 20 | // height of each tower is the sum of height of all the boxes that form it 21 | 22 | vector H; 23 | 24 | for (int i = 0; i < N; i++) 25 | { 26 | int num; 27 | cin >> num; 28 | H.push_back(num); 29 | } 30 | } 31 | return 0; 32 | } -------------------------------------------------------------------------------- /CodeChefProblems/JanuaryChallenge2021Division3/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeChefProblems/JanuaryChallenge2021Division3/a.out -------------------------------------------------------------------------------- /CodeChefProblems/LifeTheUniverseAndEverything.py: -------------------------------------------------------------------------------- 1 | try: 2 | n = int(input()) 3 | count = 0 4 | count += 1 5 | while(n != 42): 6 | if(count == 1): 7 | print(n) 8 | n = int(input()) 9 | count += 1 10 | else: 11 | print(n) 12 | n = int(input()) 13 | count += 1 14 | except: 15 | pass -------------------------------------------------------------------------------- /CodeChefProblems/MahasenaAMR15A.py: -------------------------------------------------------------------------------- 1 | try: 2 | a = int(input()) 3 | for i in range(a): 4 | weapon = list(map(int, input().split())) 5 | even_no = [i for i in weapon if i%2 == 0] 6 | odd_no = [j for j in weapon if j%2 == 1] 7 | 8 | if(len(even_no) <= len(odd_no)): 9 | print("NOT READY") 10 | else: 11 | print("READY FOR BATTLE") 12 | except Exception: 13 | pass 14 | -------------------------------------------------------------------------------- /CodeChefProblems/NovemberCookOff2020/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /CodeChefProblems/NovemberCookOff2020/ChefAndIPCCertificates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n, m, k; 9 | cin >> n >> m >> k; 10 | 11 | // n- students, k-lectures, 12 | 13 | int count = 0; 14 | for (int j = 0; j < n; j++) 15 | { 16 | int sum_time = 0; 17 | for (int i = 0; i < k; i++) 18 | { 19 | int time; 20 | cin >> time; 21 | sum_time += time; 22 | } 23 | 24 | int q; 25 | cin >> q; 26 | if (sum_time >= m && q <= 10) 27 | { 28 | count++; 29 | } 30 | } 31 | cout << count << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /CodeChefProblems/NovemberCookOff2020/FlipTheString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int T; 9 | 10 | cin >> T; 11 | 12 | while (T--) 13 | { 14 | string A, B; 15 | cin >> A >> B; 16 | 17 | if (A == B) 18 | { 19 | cout << 0 << endl; 20 | continue; 21 | } 22 | 23 | } 24 | return 0; 25 | } -------------------------------------------------------------------------------- /CodeChefProblems/NovemberCookOff2020/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeChefProblems/NovemberCookOff2020/a.out -------------------------------------------------------------------------------- /CodeChefProblems/NovemberLunchTime2020Division2/GasolineIntroduction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int T; 7 | cin >> T; 8 | int temp = T; 9 | while (T--) 10 | { 11 | if (T != temp - 1) 12 | cout << endl; 13 | int N; 14 | cin >> N; 15 | int sum = 0; 16 | for (int i = 0; i < N; i++) 17 | { 18 | int gas; 19 | cin >> gas; 20 | if (sum < i) 21 | break; 22 | else 23 | sum += gas; 24 | sum--; 25 | } 26 | cout << sum; 27 | } 28 | return 0; 29 | } -------------------------------------------------------------------------------- /CodeChefProblems/NovemberLunchTime2020Division2/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeChefProblems/NovemberLunchTime2020Division2/a.out -------------------------------------------------------------------------------- /CodeChefProblems/Problem/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /CodeChefProblems/Problem/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeChefProblems/Problem/a.out -------------------------------------------------------------------------------- /CodeChefProblems/ReverseTheNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | // your code goes here 8 | char a[50], temp; 9 | int n; 10 | cin>>n; 11 | while(n){ 12 | cin>>a; 13 | int j = strlen(a) - 1; 14 | for(int i=0; i 1000: 8 | price = 0.90 * price 9 | total_expense = price * quantity 10 | print("{:.6f}".format(total_expense)) 11 | except e: 12 | pass 13 | -------------------------------------------------------------------------------- /CodeChefProblems/ValidTrianglesFLOW13.py: -------------------------------------------------------------------------------- 1 | try: 2 | n = int(input()) 3 | for i in range(n): 4 | x, y, z = list(map(int, input().split())) 5 | sum = x+y+z 6 | if (sum == 180): 7 | print("YES") 8 | else: 9 | print("NO") 10 | except: 11 | pass -------------------------------------------------------------------------------- /CodeForces/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp", 4 | "vector": "cpp" 5 | } 6 | } -------------------------------------------------------------------------------- /CodeForces/A+B.py: -------------------------------------------------------------------------------- 1 | n = list(map(int, input().split())) 2 | print(sum(n)) 3 | -------------------------------------------------------------------------------- /CodeForces/AntonAndDanik.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin >> n; 9 | 10 | string games; 11 | cin >> games; 12 | 13 | int count_a = 0; 14 | int count_d = 0; 15 | for (char &i : games) 16 | { 17 | if (i == 'A') 18 | count_a++; 19 | else 20 | count_d++; 21 | } 22 | 23 | if (count_a > count_d) 24 | { 25 | cout << "Anton" << endl; 26 | } 27 | else if (count_a < count_d) 28 | { 29 | cout << "Danik" << endl; 30 | } 31 | else 32 | { 33 | cout << "Friendship" << endl; 34 | } 35 | return 0; 36 | } -------------------------------------------------------------------------------- /CodeForces/AntonAndLetters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | string s; 10 | getline(cin, s); 11 | 12 | int length, count = 0, i, x = 0; 13 | 14 | length = s.size(); 15 | sort(s.begin(), s.end()); 16 | 17 | for (int i = 0; i < length - 1; i++) 18 | { 19 | if (s[i] >= 97 && s[i] <= 122) 20 | { 21 | count++; 22 | if (s[i] == s[i + 1]) 23 | count--; 24 | } 25 | } 26 | cout << count << endl; 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /CodeForces/AntonAndPolyhedrons.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | 9 | int count = 0; 10 | for (int i = 0; i < n; i++) 11 | { 12 | string s; 13 | cin >> s; 14 | if (s == "Tetrahedron") 15 | count += 4; 16 | else if (s == "Cube") 17 | count += 6; 18 | else if (s == "Octahedron") 19 | count += 8; 20 | else if (s == "Dodecahedron") 21 | count += 12; 22 | else 23 | count += 20; 24 | } 25 | 26 | cout << count << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /CodeForces/BearAndBigBrother.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int a, b; 7 | cin >> a >> b; 8 | 9 | int count = 0; 10 | while (a <= b) 11 | { 12 | a = a * 3; 13 | b = b * 2; 14 | count++; 15 | } 16 | cout << count << endl; 17 | return 0; 18 | } -------------------------------------------------------------------------------- /CodeForces/BoyOrGirl.py: -------------------------------------------------------------------------------- 1 | n = str(input()) 2 | l = [i for i in n] 3 | set_l = set(l) 4 | count_set = len(set_l) 5 | if(count_set % 2 == 1): 6 | print("IGNORE HIM!") 7 | else: 8 | print("CHAT WITH HER!") 9 | -------------------------------------------------------------------------------- /CodeForces/CalculatingFunction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long long calculateFunc(long long sum, long long n) 5 | { 6 | if(n % 2 == 0) // even 7 | return n / 2; 8 | else 9 | return -1 * (n + 1)/2; 10 | } 11 | 12 | int main() 13 | { 14 | long long n ; 15 | cin>>n; 16 | long long sum = 0; 17 | long long result = calculateFunc(sum, n); 18 | cout<< result; 19 | return 0; 20 | } 21 | 22 | 23 | // f(1) = -1 24 | // f(2) = 1 25 | // f(3) = -2 26 | // f(4) = 2 27 | 28 | -------------------------------------------------------------------------------- /CodeForces/ChatRoom.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string s; 7 | cin >> s; 8 | string b = "hello"; 9 | int j = 0; 10 | 11 | for (int i = 0; i < s.size(); i++) 12 | { 13 | if (s[i] == b[j]) 14 | { 15 | j++; 16 | if (j == 5) 17 | break; 18 | } 19 | } 20 | if (j == 5) 21 | cout << "YES" << endl; 22 | else 23 | cout << "NO" << endl; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /CodeForces/Codeforces Round #684 (Div. 2)/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeForces/Codeforces Round #684 (Div. 2)/a.out -------------------------------------------------------------------------------- /CodeForces/Codeforces Round #686 (Div. 3)/SpecialPermutation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int t; 9 | cin >> t; 10 | while (t--) 11 | { 12 | int n; 13 | cin >> n; 14 | 15 | vector elements(n); 16 | for (int i = 2; i <= n; i++) 17 | { 18 | cout << i << " "; 19 | } 20 | cout << 1 << endl; 21 | } 22 | return 0; 23 | } -------------------------------------------------------------------------------- /CodeForces/Codeforces Round #686 (Div. 3)/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeForces/Codeforces Round #686 (Div. 3)/a.out -------------------------------------------------------------------------------- /CodeForces/Codeforces Round #693 (Div. 3)/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /CodeForces/Codeforces Round #693 (Div. 3)/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeForces/Codeforces Round #693 (Div. 3)/a.out -------------------------------------------------------------------------------- /CodeForces/DivisiblityProblems.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t; 7 | cin >> t; 8 | while (t--) 9 | { 10 | int a, b; 11 | cin >> a >> b; 12 | 13 | int count = 0; 14 | if (a % b != 0) 15 | count = b - a % b; 16 | cout << count << endl; 17 | } 18 | return 0; 19 | } -------------------------------------------------------------------------------- /CodeForces/DominoPiling.py: -------------------------------------------------------------------------------- 1 | n = list(map(int, input().split())) 2 | mul = n[0]*n[1] 3 | print(mul//2) -------------------------------------------------------------------------------- /CodeForces/Drinks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | long long n; 8 | cin>> n; 9 | double orange_count = 0; 10 | for(int i=0; i>p; 14 | orange_count += p / 100.0; 15 | // cout<< orange_count<<" "; 16 | } 17 | // cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string s; 7 | cin >> s; 8 | 9 | int flag = 1; 10 | for (int i = 0; i < s.size(); i++) 11 | { 12 | if (s[i] == 'W' && s[i + 1] == 'U' && s[i + 2] == 'B') 13 | { 14 | i += 2; 15 | if (flag == 0) 16 | { 17 | cout << " "; 18 | } 19 | } 20 | else 21 | { 22 | flag = 0; 23 | cout << s[i]; 24 | } 25 | } 26 | return 0; 27 | } -------------------------------------------------------------------------------- /CodeForces/Educational Codeforces Round 98 (Rated for Div. 2)/RobotProgram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t; 7 | cin >> t; 8 | while (t--) 9 | { 10 | int x, y; 11 | cin >> x >> y; 12 | } 13 | return 0; 14 | } -------------------------------------------------------------------------------- /CodeForces/Educational Codeforces Round 98 (Rated for Div. 2)/TwoBrackets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t; 7 | cin >> t; 8 | while (t--) 9 | { 10 | string s; 11 | cin >> s; 12 | int count_round = 0; 13 | int count_square = 0; 14 | for (int i = 0; i < s.size(); i++) 15 | { 16 | if (s[i] == '(') 17 | { 18 | count_square++; 19 | } 20 | if (s[i] == '(') 21 | } 22 | } 23 | return 0; 24 | } -------------------------------------------------------------------------------- /CodeForces/Elephant.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int x; 8 | cin >> x; 9 | 10 | int count; 11 | float result = (float)x / 5; 12 | count = ceil(result); 13 | cout << count << endl; 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /CodeForces/EvenOdds.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | long long n, k; 8 | cin>>n>> k; 9 | 10 | long long odd = (n+1) / 2, even = n / 2; 11 | 12 | if(k <= odd) 13 | { 14 | cout<< k*2 - 1; 15 | } 16 | else 17 | { 18 | cout<< (k - odd) * 2; 19 | } 20 | return 0; 21 | } 22 | 23 | 24 | // n is even - 3 25 | // 1 2 3 4 5 6 7 8 9 10 26 | 27 | // 1 3 5 7 9 10 8 6 4 2 28 | 29 | // n is odd 30 | // 1 2 3 4 5 6 7 31 | 32 | // 1 3 5 7 6 4 2 33 | 34 | // if n is odd (5 + 1) / 2 35 | -------------------------------------------------------------------------------- /CodeForces/Games.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeForces/Games.cpp -------------------------------------------------------------------------------- /CodeForces/GeorgeAndAccommondation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin>>n; 8 | int count = 0; 9 | for(int i=0; i>p>>q; 13 | 14 | if(q - p >= 2) 15 | { 16 | count++; 17 | } 18 | } 19 | cout< 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | string p; 8 | cin>>p; 9 | 10 | for(int i=0; i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | long long n; 7 | cin>>n; 8 | string output = ""; 9 | for(int i=1; i<=n; i++) 10 | { 11 | if(i % 2 == 1) 12 | { 13 | output += "I hate"; 14 | } 15 | else 16 | { 17 | output += "I love"; 18 | } 19 | 20 | if(i == n) 21 | { 22 | output += " it"; 23 | } 24 | else 25 | { 26 | output += " that "; 27 | } 28 | } 29 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int n; 6 | cin>>n; 7 | 8 | int hard_flag = 0; 9 | for(int i=0; i>opinion; 13 | if(opinion == 1) 14 | { 15 | hard_flag = 1; 16 | break; 17 | } 18 | } 19 | if(hard_flag) 20 | { 21 | cout<<"HARD"; 22 | } 23 | else 24 | { 25 | cout<<"EASY"; 26 | } 27 | return 0; 28 | } -------------------------------------------------------------------------------- /CodeForces/IsYourHorseshoeOnTheOtherHoof.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int s1, s2, s3, s4; 7 | cin >> s1 >> s2 >> s3 >> s4; 8 | 9 | unordered_set set; 10 | 11 | set.insert(s1); 12 | set.insert(s2); 13 | set.insert(s3); 14 | set.insert(s4); 15 | 16 | int count = 4 - set.size(); 17 | 18 | cout << count << endl; 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /CodeForces/LuckyDivision.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | 9 | int a[] = {4, 7, 47, 74, 744, 474, 447, 774, 747, 477}; 10 | int count = 0; 11 | for (int i = 0; i < 10; i++) 12 | { 13 | if (n == a[i] || n % a[i] == 0) 14 | { 15 | cout << "YES" << endl; 16 | return 0; 17 | } 18 | count++; 19 | } 20 | if (count == 10) 21 | cout << "NO" << endl; 22 | return 0; 23 | } -------------------------------------------------------------------------------- /CodeForces/Magnets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n; 9 | cin>>n; 10 | 11 | vector s(n); 12 | int count = 1; 13 | for(int i=0; i>m; 17 | if(i != 0 && s[i-1] != m) 18 | { 19 | count+=1; 20 | s[i] = m; 21 | } 22 | else 23 | { 24 | s[i] = m; 25 | } 26 | } 27 | 28 | cout<=a[k-1] and a[i] > 0): 6 | count += 1 7 | print(count) 8 | -------------------------------------------------------------------------------- /CodeForces/PetyaAndStrings.py: -------------------------------------------------------------------------------- 1 | x = str(input()) 2 | x = x.lower() 3 | y = str(input()) 4 | y = y.lower() 5 | for i in range(len(x)): 6 | if(ord(x[i]) < ord(y[i])): 7 | print(-1) 8 | break 9 | if(ord(x[i]) > ord(y[i])): 10 | print(1) 11 | break 12 | if(i == len(x) - 1): 13 | print(0) 14 | break 15 | -------------------------------------------------------------------------------- /CodeForces/Presents.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | int n; 8 | cin>>n; 9 | 10 | map p; 11 | 12 | for(int i=0; i>friend_num; 16 | p[friend_num-1] = i+1; 17 | } 18 | 19 | for(int i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int n, m; 9 | cin >> n >> m; 10 | 11 | vector puzzle(m, 0); 12 | for (int i = 0; i < m; i++) 13 | { 14 | cin >> puzzle[i]; 15 | } 16 | 17 | sort(puzzle.begin(), puzzle.end()); 18 | int min_count = puzzle[m - 1] - puzzle[0]; 19 | 20 | for (int k = 0; k <= (m - n); k++) 21 | { 22 | if (min_count > (puzzle[n + k - 1] - puzzle[k])) 23 | min_count = puzzle[n + k - 1] - puzzle[k]; 24 | cout << min_count << endl; 25 | } 26 | cout << min_count << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /CodeForces/QueueAtTheSchool.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | int n, t; 8 | 9 | cin >> n >> t; 10 | string s; 11 | cin >> s; 12 | while (t--) 13 | { 14 | for (int i = 0; i < s.size() - 1; i++) 15 | { 16 | if (s[i] == 'B' && s[i + 1] == 'G') 17 | { 18 | char temp = s[i]; 19 | s[i] = s[i + 1]; 20 | s[i + 1] = temp; 21 | i++; 22 | } 23 | } 24 | } 25 | cout << s << endl; 26 | return 0; 27 | } -------------------------------------------------------------------------------- /CodeForces/SoldierAndBananas.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int k, n, w; 7 | cin >> k >> n >> w; 8 | int sum = 0; 9 | for (int i = 1; i <= w; i++) 10 | { 11 | sum += i * k; 12 | } 13 | if (sum > n) 14 | cout << sum - n << endl; 15 | else 16 | cout << 0 << endl; 17 | return 0; 18 | } -------------------------------------------------------------------------------- /CodeForces/StonesOnTheTable.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeForces/StonesOnTheTable.py -------------------------------------------------------------------------------- /CodeForces/StringTask.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env pypy 2 | n = str(input()) 3 | n = n.lower() 4 | vowel = "aeiouy" 5 | consonants = "bcdfghjklmnpqrstvwxz" 6 | l = [] 7 | for i in n: 8 | if(i in consonants): 9 | l.append("."+i) 10 | l = "".join(l) 11 | print(l) 12 | 13 | 14 | -------------------------------------------------------------------------------- /CodeForces/TheSum.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | if n == 1 or n == 2: 3 | return 1 4 | elif n > 2: 5 | return fibonacci(n-1) + fibonacci(n-2) 6 | def sum_a(n): 7 | sum_a = 0 8 | if n == 1: 9 | sum_a = 1 10 | if n == 2: 11 | sum_a = 2 12 | if n > 2: 13 | sum_a = 2 14 | for i in range(3, n+1): 15 | sum_a = sum_a + fibonacci(i) 16 | return sum_a 17 | n = int(input()) 18 | print(sum_a(n)) 19 | 20 | -------------------------------------------------------------------------------- /CodeForces/Tram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin >> n; 8 | int inside_tram = 0; 9 | int max_inside_tram = 0; 10 | for (int i = 0; i < n; ++i) 11 | { 12 | int a, b; 13 | cin >> a >> b; 14 | 15 | inside_tram = inside_tram - a; 16 | inside_tram += b; 17 | max_inside_tram = max(max_inside_tram, inside_tram); 18 | } 19 | cout << max_inside_tram << endl; 20 | return 0; 21 | } -------------------------------------------------------------------------------- /CodeForces/Translation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | string s, t; 8 | cin >> s >> t; 9 | if (s.size() != t.size()) 10 | { 11 | cout << "NO" << endl; 12 | return 0; 13 | } 14 | int n = s.size(); 15 | 16 | for (int i = 0; i < s.size(); i++) 17 | { 18 | if (s[i] != t[n - i - 1]) 19 | { 20 | cout << "NO" << endl; 21 | return 0; 22 | } 23 | } 24 | cout << "YES" << endl; 25 | return 0; 26 | } -------------------------------------------------------------------------------- /CodeForces/TwoRegularPolygons.py: -------------------------------------------------------------------------------- 1 | t = int(input()) 2 | for i in range(t): 3 | n, m = list(map(int, input().split())) 4 | if(n%m == 0): 5 | print("YES") 6 | else: 7 | print("NO") 8 | -------------------------------------------------------------------------------- /CodeForces/UltraFastMathematician.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | string m, n; 7 | cin>>m>>n; 8 | 9 | for(int i=0; i 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n, h; 8 | vector a(n, 0); 9 | 10 | cin>>n>>h; 11 | 12 | for(int i=0; i>a[i]; 15 | } 16 | int result =0; 17 | for(int i=0; i 10): 6 | new_len = len_word-2 7 | print('%s%d%s'%(word[0],new_len,word[len_word-1])) 8 | else: 9 | print(word) 10 | -------------------------------------------------------------------------------- /CodeForces/Word.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | string s; 8 | cin >> s; 9 | int upper = 0; 10 | int lower = 0; 11 | 12 | for (int i = 0; i < s.size(); i++) 13 | { 14 | if (isupper(s[i])) 15 | upper++; 16 | if (islower(s[i])) 17 | lower++; 18 | } 19 | if (upper > lower) 20 | { 21 | transform(s.begin(), s.end(), s.begin(), ::toupper); 22 | } 23 | 24 | else 25 | transform(s.begin(), s.end(), s.begin(), ::tolower); 26 | cout << s << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /CodeForces/WordCapitalization.py: -------------------------------------------------------------------------------- 1 | n = str(input()) 2 | new_str = "" 3 | for i in range(1, len(n)): 4 | new_str += n[i] 5 | print(n[0].upper()+ new_str) -------------------------------------------------------------------------------- /CodeForces/WrongSubtraction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n, k; 7 | cin >> n >> k; 8 | 9 | for (int i = 0; i < k; i++) 10 | { 11 | if (n % 10 != 0) 12 | n = n - 1; 13 | else 14 | { 15 | n /= 10; 16 | } 17 | } 18 | cout << n << endl; 19 | return 0; 20 | } -------------------------------------------------------------------------------- /CodeForces/YoungPhysicist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin >> n; 9 | int sum1 = 0, sum2 = 0, sum3 = 0; 10 | for (int i = 0; i < n; i++) 11 | { 12 | int x, y, z; 13 | cin >> x >> y >> z; 14 | sum1 += x; 15 | sum2 += y; 16 | sum3 += z; 17 | } 18 | 19 | if (sum1 == 0 && sum2 == 0 && sum3 == 0) 20 | cout << "YES" << endl; 21 | else 22 | cout << "NO" << endl; 23 | return 0; 24 | } -------------------------------------------------------------------------------- /CodeForces/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeForces/a.exe -------------------------------------------------------------------------------- /CodeForces/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/CodeForces/a.out -------------------------------------------------------------------------------- /CodeForces/bit++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int n, x = 0; 7 | cin>>n; 8 | for(int i=0; i>stmt; 12 | if(stmt == "++X") 13 | ++x; 14 | else if(stmt == "X++") 15 | x++; 16 | else if(stmt == "--X") 17 | --x; 18 | else if(stmt == "X--") 19 | x--; 20 | } 21 | cout< s.split("").reverse(); 3 | 4 | function add(a, b) { 5 | [a, b] = [reverseArr(a), reverseArr(b)]; 6 | let carry = 0; 7 | const arr = [] 8 | const [mx, mn] = (a.length >= b.length) ? [a, b] : [b, a]; 9 | mx.forEach((itm, idx) => { 10 | let sm = Number(itm) + (Number(mn[idx]) || 0) + carry; 11 | [sm, carry] = sm > 9 ? [sm%10, 1] : [sm, 0]; 12 | arr.unshift(sm) 13 | }) 14 | if (carry) arr.unshift(carry); 15 | return arr.join("").replace(/^(0+)/, ""); 16 | } -------------------------------------------------------------------------------- /Codewars/BasicEncryption.cpp: -------------------------------------------------------------------------------- 1 | string encrypt(string text, int rule) 2 | { 3 | for (int i = 0; i < text.size(); i++) 4 | { 5 | text[i] += rule; 6 | } 7 | return text; 8 | }; -------------------------------------------------------------------------------- /Codewars/BingoOrNot.java: -------------------------------------------------------------------------------- 1 | package com.codewars.julesnuggy; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BingoOrNot { 6 | public static String bingo(int[] numberArray) { 7 | int counter = 0; 8 | int[] bingoArr = new int[] { 2, 9, 14, 7, 15 }; 9 | for (int a : bingoArr) { 10 | if (Arrays.stream(numberArray).anyMatch(i -> i == a)) 11 | counter++; 12 | } 13 | return counter == 5 ? "WIN" : "LOSE"; 14 | } 15 | } -------------------------------------------------------------------------------- /Codewars/CountTheSmileyFaces.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int countSmileys(std::vector arr) 4 | { 5 | int count = 0; 6 | for (auto elem : arr) 7 | { 8 | if (std::regex_match(elem, std::regex("[:;][-~]?[)D]"))) 9 | ++count; 10 | } 11 | return count; 12 | } -------------------------------------------------------------------------------- /Codewars/DirectionsReduction.py: -------------------------------------------------------------------------------- 1 | def dirReduc(arr): 2 | dict = {"NORTH":"SOUTH","SOUTH":"NORTH","EAST":"WEST","WEST":"EAST"} 3 | res = [] 4 | for i in arr: 5 | if res and dict[i] == res[-1]: 6 | res.pop() 7 | else: 8 | res.append(i) 9 | return res -------------------------------------------------------------------------------- /Codewars/GapInPrimes.py: -------------------------------------------------------------------------------- 1 | def gap(g, m, n): 2 | start = 0 3 | end = 0 4 | for i in range(m,n+1): 5 | if is_prime(i): 6 | print (i) 7 | if start == 0: 8 | start = i 9 | elif end == 0: 10 | end = i 11 | else: 12 | start = end 13 | end = i 14 | if end - start == g: 15 | return [start, end] 16 | return None 17 | 18 | def is_prime(n): 19 | if n <= 0 or n == 1: 20 | return False 21 | i = 2 22 | while (i <= n ** 0.5 ): 23 | if n % i == 0: 24 | return False 25 | i += 1 26 | return True 27 | -------------------------------------------------------------------------------- /Codewars/JosephusSurvivor.cpp: -------------------------------------------------------------------------------- 1 | int josephusSurvivor(int n, int k) 2 | { 3 | // your code here 4 | int return_result = 1; 5 | for (int i = 1; i <= n; ++i) 6 | { 7 | return_result = (return_result + k - 1) % i + 1; 8 | } 9 | return return_result; 10 | } -------------------------------------------------------------------------------- /Codewars/LeapYears.cpp: -------------------------------------------------------------------------------- 1 | bool IsLeapYear(int y) 2 | { 3 | if (y % 100 == 0) 4 | { 5 | if (y % 400 == 0) 6 | { 7 | return true; 8 | } 9 | else 10 | { 11 | return false; 12 | } 13 | } 14 | else 15 | { 16 | if (y % 4 == 0) 17 | { 18 | return true; 19 | } 20 | else 21 | { 22 | return false; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Codewars/MatrixAddition.cpp: -------------------------------------------------------------------------------- 1 | std::vector> matrixAddition(std::vector> a, std::vector> b) 2 | { 3 | for (int i = 0; i < a.size(); i++) 4 | for (int j = 0; j < a[i].size(); j++) 5 | a[i][j] += b[i][j]; 6 | return a; 7 | } -------------------------------------------------------------------------------- /Codewars/MultiplesOf3Or5.cpp: -------------------------------------------------------------------------------- 1 | int solution(int number) 2 | { 3 | int sum = 0; 4 | for (int i = 1; i <= number / 3; i++) 5 | { 6 | if (3 * i < number) 7 | sum += 3 * i; 8 | if (5 * i < number) 9 | sum += 5 * i; 10 | if (15 * i < number) 11 | sum -= 15 * i; 12 | } 13 | return sum; 14 | } -------------------------------------------------------------------------------- /Codewars/NumberOfPeopleInBus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | unsigned int number(const std::vector> &busStops) 5 | { 6 | int busOn = 0; 7 | int busOut = 0; 8 | int finalBus = 0; 9 | 10 | for (int i = 0; i < busStops.size(); i++) 11 | { 12 | busOn += busStops[i].first; 13 | } 14 | 15 | for (int i = 0; i < busStops.size(); i++) 16 | { 17 | busOut += busStops[i].second; 18 | } 19 | 20 | finalBus = busOn - busOut; 21 | 22 | return finalBus; 23 | } -------------------------------------------------------------------------------- /Codewars/NumberOfTrailingZeroesOfN.cpp: -------------------------------------------------------------------------------- 1 | long zeros(long n) 2 | { 3 | long result{}; 4 | int divisor = 5; 5 | while (n > divisor) 6 | { 7 | result += n / divisor; 8 | divisor *= 5; 9 | } 10 | return result; 11 | } -------------------------------------------------------------------------------- /Codewars/SumOfAngles.cpp: -------------------------------------------------------------------------------- 1 | int angle(int n) 2 | { 3 | return (n - 2) * 180; 4 | } -------------------------------------------------------------------------------- /Codewars/SumOfCubes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | unsigned int sum_cubes(unsigned int n) 3 | { 4 | // write your code here 5 | int n1 = n; 6 | int k = 0, s = 0; 7 | for (int i = 1; i <= n1; i++) 8 | { 9 | k = pow(i, 3); 10 | s += k; 11 | } 12 | return (s); 13 | } -------------------------------------------------------------------------------- /Codewars/SumOfTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int Add(int x, int y) 3 | { 4 | return log10(pow(10, x) * pow(10, y)); 5 | } -------------------------------------------------------------------------------- /Codewars/SumOfTwoLowestPosIntegers.js: -------------------------------------------------------------------------------- 1 | function sumTwoSmallestNumbers(arr) { 2 | var len = arr.length, 3 | i, j, stop; 4 | 5 | for (i=0; i < len; i++){ 6 | for (j=0, stop=len-i; j < stop; j++){ 7 | if (arr[j] > arr[j+1]){ 8 | arr[j]=arr[j]+arr[j+1]; 9 | arr[j+1]=arr[j]-arr[j+1]; 10 | arr[j]=arr[j]-arr[j+1]; 11 | } 12 | } 13 | } 14 | return arr[0]+arr[1]; 15 | 16 | } -------------------------------------------------------------------------------- /Codewars/SumStringAsNumbers.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | const reverseArr = (s) => s.split("").reverse(); 3 | 4 | function sumStrings(a, b) { 5 | [a, b] = [reverseArr(a), reverseArr(b)]; 6 | let carry = 0; 7 | const arr = []; 8 | const [mx, mn] = a.length >= b.length ? [a, b] : [b, a]; 9 | mx.forEach((itm, idx) => { 10 | let sm = Number(itm) + (Number(mn[idx]) || 0) + carry; 11 | [sm, carry] = sm > 9 ? [sm % 10, 1] : [sm, 0]; 12 | arr.unshift(sm); 13 | }); 14 | if (carry) arr.unshift(carry); 15 | return arr.join("").replace(/^(0+)/, ""); 16 | } 17 | -------------------------------------------------------------------------------- /Codewars/TwiceLinear.py: -------------------------------------------------------------------------------- 1 | def dbl_linear(n) : 2 | list = [1] 3 | x = 0 4 | y = 0 5 | 6 | while(len(list)<=n) : 7 | a = 2*list[x] + 1 8 | b = 3*list[y] + 1 9 | 10 | if a>b : 11 | list.append(b) 12 | y+= 1 13 | elif a 2 | using namespace std; 3 | 4 | std::string rot13(std::string source) 5 | { 6 | std::string transformed; 7 | for (size_t i = 0; i < source.size(); ++i) 8 | { 9 | if (isalpha(source[i])) 10 | { 11 | if ((tolower(source[i]) - 'a') < 13) 12 | { 13 | transformed.append(1, source[i] + 13); 14 | } 15 | else 16 | { 17 | transformed.append(1, source[i] - 13); 18 | } 19 | } 20 | else 21 | { 22 | transformed.append(1, source[i]); 23 | } 24 | } 25 | return transformed; 26 | } -------------------------------------------------------------------------------- /Company-wise Questions/ConvertBinaryTreeToDLL.cpp: -------------------------------------------------------------------------------- 1 | // Inorder - LDR 2 | 3 | 25 12 30 10 36 15 4 | 5 | 6 | 10 7 | 12 15 8 | 25 30 36 9 | 10 | -------------------------------------------------------------------------------- /GeeksforGeeks/CheckIfCircularLinkedList.cpp: -------------------------------------------------------------------------------- 1 | bool isCircular(Node *head) 2 | { 3 | // Your code here 4 | if(head == NULL) 5 | return true; 6 | Node *node = head->next; 7 | 8 | while(node != NULL && node != head) 9 | { 10 | node = node->next; 11 | } 12 | 13 | return (head == node); 14 | } 15 | 16 | // Time Complexity - O(N) 17 | // Space Complexity - O(1) 18 | -------------------------------------------------------------------------------- /GeeksforGeeks/DeleteWithoutHeadPointer.cpp: -------------------------------------------------------------------------------- 1 | void deleteNode(Node *del) 2 | { 3 | // Your code here 4 | del->data = del->next->data; 5 | del->next = del->next->next; 6 | } 7 | 8 | // Time Complexity - O(1) 9 | // Space Complexity - O(1) 10 | 11 | // [34, 3, 31, 98, 92, 23] 12 | 13 | // input - [31, 34, 92, 98] 14 | // tmpStack - 3 23, 31, 34, 92, 98 15 | // tmp - 16 | 17 | 18 | // tmp - 3 19 | 20 | // tmpStack.top() > tmp --> 3 > 34 --> 21 | // input.push(tmp.top()) 22 | // -------------------------------------------------------------------------------- /GeeksforGeeks/DetectLoopInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | bool detectLoop(Node* head) 2 | { 3 | // your code here 4 | Node *slow = head; 5 | Node *fast = head; 6 | // slow = slow->next; 7 | // head = fast->next->next; 8 | 9 | while(fast != NULL && fast->next != NULL) 10 | { 11 | slow = slow->next; 12 | fast = fast->next->next; 13 | if(fast == slow) 14 | { 15 | return true; 16 | } 17 | } 18 | return false; 19 | } 20 | 21 | // Time Complexity - O(N) 22 | // Space Complexity - O(1) 23 | 24 | -------------------------------------------------------------------------------- /GeeksforGeeks/DetermineIfTwoTreesAreIdentical.cpp: -------------------------------------------------------------------------------- 1 | // Recursive solution 2 | bool isIdentical(Node *r1, Node *r2) 3 | { 4 | //Your Code here 5 | 6 | if(r1 == NULL && r2 == NULL) 7 | { 8 | return true; 9 | } 10 | 11 | if(r1 == NULL || r2 == NULL) 12 | { 13 | return false; 14 | } 15 | 16 | if(r1->data == r2->data) 17 | { 18 | isIdentical(r1->left, r2->left); 19 | isIdentical(r1->right, r2->right); 20 | } 21 | else 22 | { 23 | return false; 24 | } 25 | } 26 | 27 | // Time Complexity - O(min(X1, X2)), X1 and X2 are the number of nodes in respective tree 28 | // Space Complexity - O(N), implicit stack 29 | 30 | 31 | -------------------------------------------------------------------------------- /GeeksforGeeks/DisplayLongestName.py: -------------------------------------------------------------------------------- 1 | #code 2 | T = int(input()) 3 | for i in range(T): 4 | N = int(input()) 5 | string = '' 6 | for i in range(N): 7 | name = str(input()) 8 | if len(string) == 0: 9 | string = name 10 | elif len(string) < len(name): 11 | string = name 12 | print(string) 13 | -------------------------------------------------------------------------------- /GeeksforGeeks/Graphs/.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Win32", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "defines": [ 9 | "_DEBUG", 10 | "UNICODE", 11 | "_UNICODE" 12 | ], 13 | "windowsSdkVersion": "10.0.19041.0", 14 | "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe", 15 | "cStandard": "c17", 16 | "cppStandard": "c++17", 17 | "intelliSenseMode": "windows-msvc-x64" 18 | } 19 | ], 20 | "version": 4 21 | } -------------------------------------------------------------------------------- /GeeksforGeeks/KLargestElements.cpp: -------------------------------------------------------------------------------- 1 | vector kLargest(int arr[], int n, int k) 2 | { 3 | // code here 4 | priority_queue pq; 5 | vector result; 6 | 7 | for(int i=0; i, greater > q; 25 | -------------------------------------------------------------------------------- /GeeksforGeeks/KthSmallestElement.py: -------------------------------------------------------------------------------- 1 | #code 2 | T = int(input()) 3 | for i in range(T): 4 | N = int(input()) 5 | array = list(map(int, input().split())) 6 | k = int(input()) 7 | array.sort() 8 | print(array[k-1]) 9 | -------------------------------------------------------------------------------- /GeeksforGeeks/MiddleOfThree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int n, j = 0; 8 | cin >> n; 9 | int a[n]; 10 | int b[n]; 11 | for (int i = 0; i < n; i++) 12 | cin >> a[i]; 13 | for (int i = 0; i < n; i++) 14 | { 15 | if (a[i] < 0) 16 | { 17 | b[j] = a[i]; 18 | j++; 19 | } 20 | } 21 | for (int i = 0; i < n; i++) 22 | { 23 | if (a[i] >= 0) 24 | { 25 | b[j] = a[i]; 26 | j++; 27 | } 28 | } 29 | for (int i = 0; i < n; i++) 30 | cout << b[i] << ","; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /GeeksforGeeks/MoveAllNegativeElementsToOneSide.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int n, j = 0; 8 | cin >> n; 9 | int a[n]; 10 | int b[n]; 11 | for (int i = 0; i < n; i++) 12 | cin >> a[i]; 13 | for (int i = 0; i < n; i++) 14 | { 15 | if (a[i] < 0) 16 | { 17 | b[j] = a[i]; 18 | j++; 19 | } 20 | } 21 | for (int i = 0; i < n; i++) 22 | { 23 | if (a[i] >= 0) 24 | { 25 | b[j] = a[i]; 26 | j++; 27 | } 28 | } 29 | for (int i = 0; i < n; i++) 30 | cout << b[i] << ","; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /GeeksforGeeks/ParenthesisChecker.cpp: -------------------------------------------------------------------------------- 1 | public: 2 | //Function to check if brackets are balanced or not. 3 | bool ispar(string x) 4 | { 5 | // Your code here 6 | stack s; 7 | 8 | for(auto ele: x) { 9 | if((ele == '}' || ele == ']' || ele == ')') && s.empty()) return false; 10 | if(ele == '{' || ele == '[' || ele == '(') s.push(ele); 11 | else if((ele == '}' && s.top() == '{') || (ele == ')' && s.top() == '(' )|| (ele == ']' && s.top() == '[')) s.pop(); 12 | else 13 | return false; 14 | } 15 | 16 | if(s.empty()) return true; 17 | return false; 18 | } 19 | 20 | 21 | // Time Complexity - O(N) 22 | // Space Complexity - O(N), since we're using a stack 23 | -------------------------------------------------------------------------------- /GeeksforGeeks/Patterns/Sliding Window/MaxSumSubarrayOfSizeK.cpp: -------------------------------------------------------------------------------- 1 | int maximumSumSubarray(int K, vector &Arr , int N){ 2 | // code here 3 | if(Arr.size() < K) return -1; 4 | 5 | int sum =0; 6 | 7 | for(int i=0; i 2 | using namespace std; 3 | 4 | int main() { 5 | //code 6 | int T, N; 7 | int arr[1200]; 8 | cin>>T; 9 | for(int k=0; k>N; 12 | for(int i=0; i>arr[i]; 15 | } 16 | for(int i=0; i arr[j+1]) 21 | { 22 | int temp = arr[j]; 23 | arr[j] = arr[j+1]; 24 | arr[j+1] = temp; 25 | } 26 | } 27 | } 28 | cout<data); 8 | 9 | if(root->left == NULL && root->right == NULL) 10 | return val; 11 | 12 | return treePathsSumUtil(root->left, val) + treePathsSumUtil(root->right, val); 13 | } 14 | 15 | /*You are required to complete below method */ 16 | long long treePathsSum(Node *root) 17 | { 18 | //Your code here 19 | return treePathsSumUtil(root, 0); 20 | } 21 | 22 | // Time Complexity - O(N), N is number of nodes in tree 23 | // Space Complexity - O(N), implicit stack space 24 | -------------------------------------------------------------------------------- /GeeksforGeeks/RotateArray.py: -------------------------------------------------------------------------------- 1 | #code 2 | T = int(input()) 3 | for i in range(T): 4 | N, D = list(map(int, input().split())) 5 | array = list(map(int, input().split())) 6 | array1 = array[D%len(array) :] + array[: D%len(array)] 7 | for i in (array1): 8 | print(i, end = ' ') 9 | print() 10 | 11 | -------------------------------------------------------------------------------- /GeeksforGeeks/SearchAnElementInAnArray.py: -------------------------------------------------------------------------------- 1 | #code 2 | 3 | T = int(input()) 4 | for i in range(T): 5 | N = int(input()) 6 | l = list(map(int, input().split())) 7 | element = int(input()) 8 | if(element in l): 9 | print(l.index(element)) 10 | else: 11 | print("-1") 12 | 13 | -------------------------------------------------------------------------------- /GeeksforGeeks/SecondLargest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | //code 6 | int T, N; 7 | int arr[1200]; 8 | cin>>T; 9 | for(int k=0; k>N; 12 | for(int i=0; i>arr[i]; 15 | } 16 | for(int i=0; i arr[j+1]) 21 | { 22 | int temp = arr[j]; 23 | arr[j] = arr[j+1]; 24 | arr[j+1] = temp; 25 | } 26 | } 27 | } 28 | cout<data == root2->data) 7 | { 8 | return isMirror(root1->left, root2->right) && isMirror(root1->right, root2->left); 9 | } 10 | return false; 11 | } 12 | 13 | // return true/false denoting whether the tree is Symmetric or not 14 | bool isSymmetric(struct Node* root) 15 | { 16 | return isMirror(root, root); 17 | } 18 | 19 | // Time Complexity - O(N), N is the number of nodes in the tree 20 | // Space Complexity - O(N), implicit stack 21 | -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Day8ButtonsContainer/css/buttonsGrid.css: -------------------------------------------------------------------------------- 1 | .buttonContainer { 2 | width: 75%; 3 | } 4 | 5 | .buttonContainer > .buttonClass { 6 | width: 30%; 7 | height: 48px; 8 | font-size: 24px; 9 | } 10 | -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Day8ButtonsContainer/js/buttonsGrid.js: -------------------------------------------------------------------------------- 1 | var b = document.getElementById('btn5'); 2 | var arr = [1, 2, 3, 6, 9, 8, 7, 4]; 3 | b.onclick = function () { 4 | arr.unshift(arr.pop()); 5 | document.getElementById('btn1').innerHTML = arr[0]; 6 | document.getElementById('btn2').innerHTML = arr[1]; 7 | document.getElementById('btn3').innerHTML = arr[2]; 8 | document.getElementById('btn6').innerHTML = arr[3]; 9 | document.getElementById('btn9').innerHTML = arr[4]; 10 | document.getElementById('btn8').innerHTML = arr[5]; 11 | document.getElementById('btn7').innerHTML = arr[6]; 12 | document.getElementById('btn4').innerHTML = arr[7]; 13 | 14 | } -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Day8CreateAButton/css/button.css: -------------------------------------------------------------------------------- 1 | .button { 2 | width: 96px; 3 | height: 48px; 4 | font-size: 24px; 5 | } 6 | -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Day8CreateAButton/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Button 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Day8CreateAButton/js/button.js: -------------------------------------------------------------------------------- 1 | var btn = document.getElementById("btn"); 2 | btn.addEventListener("click", function () { 3 | var current_value = this.innerHTML; 4 | this.innerHTML = parseInt(current_value) + 1; 5 | }); -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Day9BinaryCalculator/css/binaryCalculator.css: -------------------------------------------------------------------------------- 1 | body { 2 | width: 33%; 3 | } 4 | 5 | #res { 6 | background-color: lightgray; 7 | border: solid; 8 | height: 48px; 9 | font-size: 20px; 10 | } 11 | 12 | #btns button { 13 | width: 25%; 14 | height: 36px; 15 | font-size: 18px; 16 | margin: 0px; 17 | float: left; 18 | } 19 | 20 | #btn0, 21 | #btn1 { 22 | background-color: lightgreen; 23 | color: brown; 24 | } 25 | 26 | #btnEql, 27 | #btnClr { 28 | background-color: darkgreen; 29 | color: white; 30 | } 31 | 32 | #btnSum, 33 | #btnSub, 34 | #btnMul, 35 | #btnDiv { 36 | background-color: black; 37 | color: red; 38 | } -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Practise1/css/button.css: -------------------------------------------------------------------------------- 1 | #btn { 2 | width: 96px; 3 | height: 48px; 4 | font-size: 24px; 5 | } -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Practise1/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Button 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Practise1/js/button.js: -------------------------------------------------------------------------------- 1 | var btn = document.createElement('button'); 2 | 3 | // Button's id 4 | btn.id = 'btn'; 5 | 6 | 7 | // Button's innerHTML 8 | btn.innerHTML = 0; 9 | btn.onclick = function() { 10 | btn.innerHTML++; 11 | } 12 | 13 | document.body.appendChild(btn); -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Practise2/css/buttonsGrid.css: -------------------------------------------------------------------------------- 1 | #btns { 2 | width: 75%; 3 | position: relative; 4 | } 5 | 6 | .btn { 7 | width: 30%; 8 | height: 48px; 9 | font-size: 24px; 10 | } -------------------------------------------------------------------------------- /HackerRank/10DaysOfJavaScript/Practise2/js/buttonsGrid.js: -------------------------------------------------------------------------------- 1 | let nums = [1, 2, 3, 6, 9, 8, 7, 4]; 2 | const ids = [1, 2, 3, 6, 9, 8, 7, 4]; 3 | 4 | let btn5 = document.getElementById('btn5'); 5 | 6 | btn5.onclick = function() { 7 | nums.unshift(nums.pop()); 8 | for (i = 0; i <= 7; i++) { 9 | document.getElementById("btn" + ids[i]).innerHTML = nums[i]; 10 | } 11 | } -------------------------------------------------------------------------------- /HackerRank/30DaysOfCode/Day0HelloWorld.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | //-------------------------------------------------------------------- 10 | 11 | 12 | int main() 13 | { 14 | 15 | string input_string; 16 | 17 | getline(cin, input_string); 18 | 19 | cout << "Hello, World." << endl; 20 | 21 | cout << input_string << endl; 22 | 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /HackerRank/30DaysOfCode/Day1DataTypes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | int i = 4; 9 | double d = 4.0; 10 | string s = "HackerRank "; 11 | 12 | //----------------------------------------------------------------- 13 | 14 | 15 | int lo; 16 | string lo2; 17 | double lo3; 18 | cin >> lo >> lo3 >> lo2; 19 | 20 | cout << lo + i << endl; 21 | cout << lo3 + d << endl; 22 | cout << s << lo2 << endl; 23 | 24 | //--------------------------------------------------------------------- 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /HackerRank/30DaysOfCode/Day2Operators.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main() { 6 | double x, y, z; 7 | cin >> x >> y >> z; 8 | double tip = x * y / 100; 9 | double tax = x * z / 100; 10 | double total = x + tip + tax; 11 | int total2 = total; 12 | cout << "The total meal cost is " << total2 << " dollars."; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /HackerRank/30DaysOfCode/Day3Conditionalstatements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int main(){ 6 | int N; 7 | cin >> N; 8 | if(N%2 != 0 || (N%2 == 0) && N >= 6 && N <= 20){ 9 | cout << "Weird" << endl; 10 | }else cout << "Not Weird" << endl; 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /HackerRank/C/FunctionsInC.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | Add `int max_of_four(int a, int b, int c, int d)` here. 6 | */ 7 | 8 | int main() 9 | { 10 | int a, b, c, d; 11 | scanf("%d %d %d %d", &a, &b, &c, &d); 12 | int ans = max_of_four(a, b, c, d); 13 | printf("%d", ans); 14 | 15 | return 0; 16 | } -------------------------------------------------------------------------------- /HackerRank/C/Pointers_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | void increment(int *v) 3 | { 4 | (*v)++; 5 | } 6 | int main() 7 | { 8 | int a; 9 | scanf("%d", &a); 10 | increment(&a); 11 | printf("%d", a); 12 | return 0; 13 | } 14 | 15 | // Input: 16 | // 12 17 | 18 | // Output: 19 | // 13 -------------------------------------------------------------------------------- /HackerRank/C/PrintingPatternUsingLoops.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define min(a, b) ((a) < (b) ? (a) : (b)) 6 | 7 | int main() { 8 | int n; 9 | scanf("%d", &n); 10 | int len = ((2*n)-1); 11 | int m; 12 | for (int row = 0; row< len; row++) { 13 | for (int col = 0; col< len; col++) { 14 | m = min(row, col); 15 | m = min(m, len-row-1); 16 | m = min(len-col-1, m); 17 | printf("%d ", n-m); 18 | } 19 | printf("\n"); 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /HackerRank/C/SumAndDifferenceOfTwoNumbers.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | int a, b; 9 | scanf("%d", &a); 10 | scanf("%d", &b); 11 | int s = a + b; 12 | int d = a - b; 13 | float a1, b1; 14 | scanf("%f", &a1); 15 | scanf("%f", &b1); 16 | float s1 = a1 + b1; 17 | float d1 = a1 - b1; 18 | printf("%d", s); 19 | printf("%s", " "); 20 | printf("%d\n", d); 21 | printf("%.1f", s1); 22 | printf("%s", " "); 23 | printf("%.1f", d1); 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /HackerRank/FunctionalProgramming/HelloWorld.scala: -------------------------------------------------------------------------------- 1 | def f() = println("Hello World") -------------------------------------------------------------------------------- /HackerRank/Java/Java1DArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner scan = new Scanner(System.in); 8 | int n = scan.nextInt(); 9 | int[] a = new int[n]; 10 | for(int i=0; i 0: 17 | return 'not pangram' 18 | else: 19 | return 'pangram' 20 | 21 | if __name__ == '__main__': 22 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 23 | 24 | s = input() 25 | 26 | result = pangrams(s) 27 | 28 | fptr.write(result + '\n') 29 | 30 | fptr.close() 31 | -------------------------------------------------------------------------------- /HackerRank/Problem-Solving/Plusminus.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the plusMinus function below. 10 | def plusMinus(arr): 11 | pos = 0 12 | nega = 0 13 | zero = 0 14 | for x in arr: 15 | if x > 0 : 16 | pos += 1 17 | elif x < 0 : 18 | nega += 1 19 | else : 20 | zero +=1 21 | print("%.6f"%(pos/len(arr))) 22 | print("%.6f"%(nega/len(arr))) 23 | print("%.6f"%(zero/ len(arr)), end ='') 24 | 25 | if __name__ == '__main__': 26 | n = int(input()) 27 | 28 | arr = list(map(int, input().rstrip().split())) 29 | 30 | plusMinus(arr) 31 | -------------------------------------------------------------------------------- /HackerRank/Problem-Solving/RepeatedString.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the repeatedString function below. 10 | def repeatedString(s, n): 11 | sum = (s.count('a')* (n//len(s))) 12 | return (sum) + (s[:(n % len(s))].count('a')) 13 | 14 | if __name__ == '__main__': 15 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 16 | 17 | s = input() 18 | 19 | n = int(input()) 20 | 21 | result = repeatedString(s, n) 22 | 23 | fptr.write(str(result) + '\n') 24 | 25 | fptr.close() 26 | 27 | -------------------------------------------------------------------------------- /HackerRank/Problem-Solving/SolveMeFirst.py: -------------------------------------------------------------------------------- 1 | # Complete the function solveMeFirst to compute the sum of two integers. 2 | # Function prototype: 3 | 4 | # int solveMeFirst(int a, int b); 5 | # where, 6 | # a is the first integer input. 7 | # b is the second integer input 8 | 9 | 10 | def solveMeFirst(a,b): 11 | # Hint: Type return a+b below 12 | return a + b 13 | 14 | if __name__ == '__main__': 15 | num1 = input() 16 | num2 = input() 17 | res = solveMeFirst(num1,num2) 18 | print res 19 | 20 | # Sample Input 21 | 22 | # a = 2 23 | # b = 3 24 | 25 | # Sample Output 26 | 27 | # 5 28 | 29 | -------------------------------------------------------------------------------- /HackerRank/Problem-Solving/Staircase.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the staircase function below. 10 | def staircase(n): 11 | for i in range(n): 12 | print(' '*(n-i-1),end='') 13 | print("#"* (1+i)) 14 | 15 | if __name__ == '__main__': 16 | n = int(input()) 17 | 18 | staircase(n) 19 | 20 | # Staircase to return 21 | 22 | # 23 | ## 24 | ### 25 | #### 26 | -------------------------------------------------------------------------------- /HackerRank/Python/Arrays.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | def arrays(arr): 4 | # complete this function 5 | # use numpy.array 6 | arr.reverse() 7 | return numpy.array(arr, float) 8 | 9 | arr = input().strip().split(' ') 10 | result = arrays(arr) 11 | print(result) -------------------------------------------------------------------------------- /HackerRank/Python/CheckSubset.py: -------------------------------------------------------------------------------- 1 | def subset(A, B): 2 | return A.issubset(B) 3 | 4 | if __name__ == '__main__': 5 | no_T = int(input()) # no. of test cases 6 | 7 | for i in range(no_T): 8 | no_A = int(input()) # no. of elements in A 9 | A = set(map(int, input().split())) # elements of A 10 | no_B = int(input()) # no. of elements in B 11 | B = set(map(int, input().split())) # elements of B 12 | print(subset(A, B)) -------------------------------------------------------------------------------- /HackerRank/Python/FindTheRunnerupScore.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | arr = map(int, input().split()) 4 | arr = list(arr) 5 | arr.sort(reverse = True) 6 | maximum = max(arr) # maximum value of arr 7 | l = [x for x in arr if x != maximum] 8 | print(l[0]) -------------------------------------------------------------------------------- /HackerRank/Python/FindingThePercentage.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | student_marks = {} 4 | for _ in range(n): 5 | name, *line = input().split() 6 | scores = list(map(float, line)) 7 | student_marks[name] = scores 8 | query_name = str(input()) 9 | if query_name in student_marks: 10 | l=list(student_marks[query_name]) 11 | sum=0 12 | for i in range(len(l)): 13 | sum= l[i]+sum 14 | print("{:.2f}".format(sum/3)) 15 | 16 | -------------------------------------------------------------------------------- /HackerRank/Python/Input.py: -------------------------------------------------------------------------------- 1 | # Run in Python 2.7 2 | 3 | # >>> input() 4 | # 1+2 5 | # 3 6 | # >>> company = 'HackerRank' 7 | # >>> website = 'www.hackerrank.com' 8 | # >>> input() 9 | # 'The company name: '+company+' and website: '+website 10 | # 'The company name: HackerRank and website: www.hackerrank.com' 11 | 12 | x, k = list(map(int, raw_input().split())) 13 | # P(x) = k 14 | 15 | if input() == k: 16 | print(True) 17 | else: 18 | print(False) 19 | 20 | 21 | # Input: 22 | # 1 4 23 | # x**3 + x**2 + x + 1 24 | 25 | # Output: 26 | # True -------------------------------------------------------------------------------- /HackerRank/Python/IntroductionToSets.py: -------------------------------------------------------------------------------- 1 | def average(array): 2 | # your code goes here 3 | array = set(array) 4 | return sum(array)/ len(array) 5 | 6 | if __name__ == '__main__': 7 | n = int(input()) 8 | arr = list(map(int, input().split())) 9 | result = average(arr) 10 | print(result) -------------------------------------------------------------------------------- /HackerRank/Python/ListStringComprehensions.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | x = int(input()) 3 | y = int(input()) 4 | z = int(input()) 5 | n = int(input()) 6 | print([[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k) != n]) 7 | -------------------------------------------------------------------------------- /HackerRank/Python/MinAndMax.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | l = [] 4 | n, m = list(map(int, input().split())) 5 | for i in range(n): 6 | j = list(map(int, input().split())) 7 | l.append(j) 8 | l = np.array(l) 9 | # print(l) 10 | print(np.max(np.min(l, axis=1))) 11 | -------------------------------------------------------------------------------- /HackerRank/Python/NestedLists.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | student = [[input(), float(input())] for i in range(n)] 4 | student.sort(key = lambda x:x[1]) # sorts in ascending order 5 | minimum = student[0][1] # Takes the minimum value 6 | l = [[student[i][0],student[i][1]] for i in range(n) if student[i][1] != minimum] 7 | j = [l[i][0] for i in range(len(l)) if l[i][1] == l[0][1]] # It takes only minimum values 8 | j.sort() 9 | for i in range(len(j)): 10 | print(j[i], end = '\n') 11 | -------------------------------------------------------------------------------- /HackerRank/Python/Prime.py: -------------------------------------------------------------------------------- 1 | # Program to generate all the prime numbers till 1000 2 | # with amp '&' sign between them 3 | 4 | n = 1000 5 | for i in range(2, n+1): 6 | for j in range(2, n): 7 | if(i%j) == 0 and (i != j): 8 | break 9 | else: 10 | print(i,end = "&") -------------------------------------------------------------------------------- /HackerRank/Python/PythonEvaluation.py: -------------------------------------------------------------------------------- 1 | # It helps in evaluating an expression. 2 | # The expression can be a Python statement, or a code object. ---> 3 | 4 | # >>> eval("9 + 5") 5 | # 14 6 | # >>> x = 2 7 | # >>> eval("x + 3") 8 | # 5 9 | 10 | # eval() can also be used to work with Python keywords or defined 11 | # functions and variables. These would normally be stored as strings. --> 12 | 13 | # >>> type(eval("len")) 14 | # 15 | 16 | # Without eval() -- > 17 | 18 | # >>> type("len") 19 | # 20 | 21 | A = input() 22 | eval(A) # Don't use print() function since it prints None as well -------------------------------------------------------------------------------- /HackerRank/Python/ReduceFunction.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | from functools import reduce 3 | 4 | def product(fracs): 5 | # complete this line with a reduce statement 6 | # t = reduce(lambda x,y: Fraction(x, y)) 7 | t = reduce(lambda x, y: Fraction(x * y), fracs) 8 | return t.numerator, t.denominator 9 | 10 | if __name__ == '__main__': 11 | fracs = [] 12 | for _ in range(int(input())): 13 | fracs.append(Fraction(*map(int, input().split()))) 14 | result = product(fracs) 15 | print(*result) -------------------------------------------------------------------------------- /HackerRank/Python/ReverseWordAndSwapCases.py: -------------------------------------------------------------------------------- 1 | def reverce(sentence): 2 | arr = sentence.split() 3 | reversedArr = arr[:: -1] 4 | reversedSentence = " ".join(reversedArr) 5 | 6 | return reversedSentence.swapcase() 7 | 8 | 9 | sentence = "rUns dOg" 10 | print(reverce(sentence)) 11 | -------------------------------------------------------------------------------- /HackerRank/Python/SetAdd.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | s = set() 4 | for _ in range(n): 5 | s.add(input()) 6 | print(s.__len__(), end = '') -------------------------------------------------------------------------------- /HackerRank/Python/SetIntersection.py: -------------------------------------------------------------------------------- 1 | # >>> s = set("Hacker") 2 | # >>> print s.intersection("Rank") 3 | # set(['a', 'k']) 4 | 5 | # >>> print s.intersection(set(['R', 'a', 'n', 'k'])) 6 | # set(['a', 'k']) 7 | 8 | # >>> print s.intersection(['R', 'a', 'n', 'k']) 9 | # set(['a', 'k']) 10 | 11 | # >>> print s.intersection(enumerate(['R', 'a', 'n', 'k'])) 12 | # set([]) 13 | 14 | # >>> print s.intersection({"Rank":1}) 15 | # set([]) 16 | 17 | # >>> s & set("Rank") 18 | # set(['a', 'k']) 19 | 20 | eng = input() 21 | eng_stu = set(map(int, input().split())) 22 | fren = input() 23 | fren_stu = set(map(int, input().split())) 24 | 25 | both = eng_stu.intersection(fren_stu) 26 | 27 | print(len(both)) -------------------------------------------------------------------------------- /HackerRank/Python/SumAndProd.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | list_append = [] 4 | 5 | num, m = list(map(int, input().split())) 6 | import pdb; pdb.set_trace() 7 | for i in range(num): 8 | a_a = list(map(int, input().split())) 9 | list_append.append(a_a) 10 | print(np.prod(np.sum(list_append,axis = 0), axis = None)) 11 | 12 | 13 | # n - next line 14 | # c - full execute 15 | # l - whole code execute -------------------------------------------------------------------------------- /HackerRank/Python/TheCaptainsRoom.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | K = int(input()) 4 | list_elements = list(map(int, input().split())) 5 | set_elements = set(list_elements) 6 | captains_roomno = (((sum(set_elements)* K - sum(list_elements))// (K - 1))) 7 | print(captains_roomno, end = '') 8 | 9 | # Input 10 | # 5 11 | # 1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2 12 | 13 | # Ouput (find the unique element from it) 14 | # 8 -------------------------------------------------------------------------------- /HackerRank/Python/Tuples.py: -------------------------------------------------------------------------------- 1 | # Task 2 | # Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers. Then compute and print the result of hash(t). 3 | # Note: hash() is one of the functions in the __builtins__ module, so it need not be imported. 4 | 5 | if __name__ == '__main__': 6 | n = int(input()) 7 | integer_list = map(int, input().split()) 8 | t = tuple(integer_list) 9 | print(hash(t)) 10 | 11 | # Output Format 12 | 13 | # Print the result of hash(t). 14 | 15 | # Sample Input 0 16 | 17 | # 2 18 | # 1 2 19 | 20 | # Sample Output 0 21 | 22 | # 3713081631934410656 23 | 24 | 25 | -------------------------------------------------------------------------------- /HackerRank/Python/WordsScore.py: -------------------------------------------------------------------------------- 1 | def is_vowel(letter): 2 | return letter in ['a', 'e', 'i', 'o', 'u', 'y'] 3 | 4 | def score_words(words): 5 | score = 0 6 | l = [] 7 | for word in words: 8 | num_vowels = 0 9 | for letter in word: 10 | if is_vowel(letter): 11 | num_vowels += 1 12 | if num_vowels % 2 == 0: 13 | l.append(2) 14 | else: 15 | l.append(1) 16 | return sum(l) 17 | # return score 18 | 19 | n = int(input()) 20 | words = input().split() 21 | print(score_words(words)) -------------------------------------------------------------------------------- /HackerRank/Python/WriteAFunction.py: -------------------------------------------------------------------------------- 1 | def is_leap(year): 2 | y=year 3 | leap = False 4 | if (y%400==0 or y%4==0 and y%100!=0) : 5 | leap=True 6 | return leap 7 | else: 8 | return False 9 | 10 | year = int(input()) 11 | print(is_leap(year)) 12 | -------------------------------------------------------------------------------- /HackerRank/Sql/AfricanCities.sql: -------------------------------------------------------------------------------- 1 | -- Given the CITY and COUNTRY tables, query the names of all cities where the CONTINENT is 'Africa'. 2 | -- Note: CITY.CountryCode and COUNTRY.Code are matching key columns. 3 | 4 | SELECT CITY.NAME FROM CITY, COUNTRY WHERE CITY.COUNTRYCODE = COUNTRY.CODE AND COUNTRY.CONTINENT = 'AFRICA'; -------------------------------------------------------------------------------- /HackerRank/Sql/AsianPopulation.sql: -------------------------------------------------------------------------------- 1 | -- Given the CITY and COUNTRY tables, query the sum of the populations of all cities where the CONTINENT is 'Asia'. 2 | -- Note: CITY.CountryCode and COUNTRY.Code are matching key columns. 3 | 4 | SELECT SUM(CITY.POPULATION) FROM CITY, COUNTRY WHERE COUNTRY.CONTINENT = 'ASIA' AND CITY.COUNTRYCODE = COUNTRY.CODE;SELECT SUM(CITY.POPULATION) FROM CITY, COUNTRY WHERE COUNTRY.CONTINENT = 'ASIA' AND CITY.COUNTRYCODE = COUNTRY.CODE; -------------------------------------------------------------------------------- /HackerRank/Sql/AveragePopulation.sql: -------------------------------------------------------------------------------- 1 | -- Query the average population for all cities in CITY, rounded down to the nearest integer. 2 | 3 | SELECT ROUND(AVG(POPULATION)) FROM CITY; -------------------------------------------------------------------------------- /HackerRank/Sql/AveragePopulationOfEachContinent.sql: -------------------------------------------------------------------------------- 1 | -- Given the CITY and COUNTRY tables, query the names of all the continents (COUNTRY.Continent) 2 | -- and their respective average city populations (CITY.Population) rounded 'down' to the nearest integer. 3 | -- Note: CITY.CountryCode and COUNTRY.Code are matching key columns. 4 | 5 | SELECT COUNTRY.CONTINENT, FLOOR(AVG(CITY.POPULATION)) 6 | FROM CITY, COUNTRY 7 | WHERE CITY.COUNTRYCODE = COUNTRY.CODE 8 | GROUP BY COUNTRY.CONTINENT ; -------------------------------------------------------------------------------- /HackerRank/Sql/BinaryTreeNodes.sql: -------------------------------------------------------------------------------- 1 | -- You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N. 2 | 3 | -- Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node: 4 | 5 | -- Root: If node is root node. 6 | -- Leaf: If node is leaf node. 7 | -- Inner: If node is neither root nor leaf node. 8 | 9 | 10 | SELECT N, IF(P IS NULL, 'Root',IF((SELECT COUNT(*) FROM BST WHERE P = B.N) > 0, 11 | 'Inner', 'Leaf')) FROM BST as B ORDER BY N; 12 | 13 | -- Sample Output 14 | 15 | -- 1 Leaf 16 | -- 2 Inner 17 | -- 3 Leaf 18 | -- 5 Root 19 | -- 6 Leaf 20 | -- 8 Inner 21 | -- 9 Leaf 22 | -------------------------------------------------------------------------------- /HackerRank/Sql/DrawTheTriangle1.sql: -------------------------------------------------------------------------------- 1 | -- P(R) represents a pattern drawn by Julia in R rows. 2 | -- The following pattern represents P(5): 3 | 4 | -- * * * * * 5 | -- * * * * 6 | -- * * * 7 | -- * * 8 | -- * 9 | 10 | -- Write a query to print the pattern P(20). 11 | 12 | SET @number = 21; 13 | SELECT REPEAT('* ',@number := @number - 1) from information_schema.tables; -------------------------------------------------------------------------------- /HackerRank/Sql/DrawTheTriangle2.sql: -------------------------------------------------------------------------------- 1 | -- P(R) represents a pattern drawn by Julia in R rows. The following pattern represents P(5): 2 | 3 | -- * 4 | -- * * 5 | -- * * * 6 | -- * * * * 7 | -- * * * * * 8 | 9 | -- Write a query to print the pattern P(20). 10 | 11 | SET @number = 0; 12 | SELECT REPEAT('* ', @number := @number + 1) from information_schema.tables where @number < 20; -------------------------------------------------------------------------------- /HackerRank/Sql/HigherThan75Marks.sql: -------------------------------------------------------------------------------- 1 | -- Query the Name of any student in STUDENTS who scored higher than 75 Marks. 2 | -- Order your output by the last three characters of each name. 3 | -- If two or more students both have names ending in the same 4 | -- last three characters (i.e.: Bobby, Robby, etc.), secondary sort them by ascending ID. 5 | 6 | SELECT NAME FROM STUDENTS 7 | WHERE MARKS > 75 8 | ORDER BY RIGHT(NAME, 3), ID ASC; 9 | 10 | 11 | -------------------------------------------------------------------------------- /HackerRank/Sql/JapanPopulation.sql: -------------------------------------------------------------------------------- 1 | -- Query the sum of the populations for all Japanese cities in CITY. The COUNTRYCODE for Japan is JPN. 2 | 3 | SELECT SUM(POPULATION) FROM CITY WHERE COUNTRYCODE = 'JPN'; -------------------------------------------------------------------------------- /HackerRank/Sql/Placements.sql: -------------------------------------------------------------------------------- 1 | SELECT S.NAME FROM 2 | (STUDENTS S JOIN FRIENDS F USING(ID) 3 | JOIN PACKAGES P1 ON S.ID = P1.ID 4 | JOIN PACKAGES P2 ON F.FRIEND_ID = P2.ID) 5 | WHERE P2.SALARY > P1.SALARY 6 | ORDER BY P2.SALARY -------------------------------------------------------------------------------- /HackerRank/Sql/PopulationDensityDifference.sql: -------------------------------------------------------------------------------- 1 | -- Query the difference between the maximum and minimum populations in CITY. 2 | 3 | SELECT MAX(POPULATION) - MIN(POPULATION) FROM CITY; -------------------------------------------------------------------------------- /HackerRank/Sql/RevisingAggregationsAverages.sql: -------------------------------------------------------------------------------- 1 | -- Query the average population of all cities in CITY where District is California 2 | 3 | SELECT AVG(POPULATION) FROM CITY WHERE DISTRICT = 'CALIFORNIA'; -------------------------------------------------------------------------------- /HackerRank/Sql/RevisingAggregationsTheCountFunction.sql: -------------------------------------------------------------------------------- 1 | -- Query a count of the number of cities in CITY having a Population larger than 100,000. 2 | 3 | SELECT COUNT(ID) FROM CITY WHERE POPULATION > 100000; -------------------------------------------------------------------------------- /HackerRank/Sql/RevisingAggregationsTheSumFunction.sql: -------------------------------------------------------------------------------- 1 | -- Query the total population of all cities in CITY where District is California. 2 | 3 | SELECT SUM(POPULATION) FROM CITY WHERE DISTRICT = 'CALIFORNIA'; -------------------------------------------------------------------------------- /HackerRank/Sql/SelectSecondMax.sql: -------------------------------------------------------------------------------- 1 | SELECT MAX(COLUMN_NAME) FROM TABLE_NAME WHERE COLUMN_NAME NOT IN (SELECT MAX(COLUMN_NAME FROM TABLE_NAME); 2 | -------------------------------------------------------------------------------- /HackerRank/Sql/TheBlunder.sql: -------------------------------------------------------------------------------- 1 | -- Samantha was tasked with calculating the average monthly salaries for all employees in the EMPLOYEES table, but did not realize her keyboard's 2 | -- 0 key was broken until after completing the calculation. She wants your help finding the difference between her miscalculation (using salaries with any zeroes removed), and the actual average salary. 3 | -- Write a query calculating the amount of error (i.e.: actual - miscalculated 4 | -- average monthly salaries), and round it up to the next integer. 5 | 6 | SELECT CEIL(AVG(SALARY) - AVG(REPLACE(SALARY,'0', ''))) FROM EMPLOYEES; -------------------------------------------------------------------------------- /HackerRank/Sql/TopEarners.sql: -------------------------------------------------------------------------------- 1 | -- We define an employee's total earnings to be their monthly salary * months worked, 2 | -- and the maximum total earnings to be the maximum total earnings for any employee in 3 | -- the Employee table. Write a query to find the maximum total earnings for all employees 4 | -- as well as the total number of employees who have maximum total earnings. 5 | -- Then print these values as 2 space-separated integers. 6 | 7 | SELECT SALARY * MONTHS AS EARNINGS, COUNT(*) FROM EMPLOYEE 8 | GROUP BY 1 9 | ORDER BY EARNINGS DESC LIMIT 1; 10 | 11 | -------------------------------------------------------------------------------- /HackerRank/Sql/WeaTherObservationStation2.sql: -------------------------------------------------------------------------------- 1 | -- Query the following two values from the STATION table: 2 | -- 1. The sum of all values in LAT_N rounded to a scale of 2 decimal places. 3 | -- 2. The sum of all values in LONG_W rounded to a scale of 2 decimal places. 4 | 5 | SELECT ROUND(SUM(LAT_N),2), ROUND(SUM(LONG_W), 2) FROM STATION; -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation10.sql: -------------------------------------------------------------------------------- 1 | -- Query the list of CITY names from STATION that do not end with vowels. 2 | -- Your result cannot contain duplicates. 3 | 4 | SELECT distinct(CITY) FROM STATION 5 | WHERE CITY NOT RLIKE '^.*[AEIOUaeiou]$' -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation11.sql: -------------------------------------------------------------------------------- 1 | -- Query the list of CITY names from STATION that either do not start with vowels or do not end with vowels. 2 | -- Your result cannot contain duplicates. 3 | 4 | SELECT distinct(CITY) FROM STATION 5 | WHERE CITY NOT RLIKE '^[AEIOUaeiou].*[AEIOUaeiou]$'; -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation12.sql: -------------------------------------------------------------------------------- 1 | -- http://www.tutorialspoint.com/mysql/mysql-regexps.htm 2 | 3 | -- '.' is to specify a character and '*' is to mention zero or more of the preceding character 4 | -- [...] --> Any character listed between the square brackets 5 | -- [^...] --> Any character not listed between the square brackets 6 | 7 | SELECT distinct(CITY) FROM STATION 8 | WHERE CITY RLIKE '^[^aeiouAEIOU].*[^AEIOUaeiou]$'; 9 | 10 | -- SELECT distinct(CITY) FROM STATION 11 | -- WHERE CITY REGEXP '^[^aeiouAEIOU].*[^AEIOUaeiou]$' -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation13.sql: -------------------------------------------------------------------------------- 1 | -- Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than 38.7880 and less than 137.2345. 2 | -- Truncate your answer to decimal places. 3 | 4 | SELECT ROUND(SUM(LAT_N), 4) FROM STATION WHERE LAT_N BETWEEN 38.788 and 137.2345; -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation14.sql: -------------------------------------------------------------------------------- 1 | -- Query the greatest value of the Northern Latitudes (LAT_N) from STATION that is less than 137.2345. 2 | -- Truncate your answer to 4 decimal places. 3 | 4 | SELECT ROUND(MAX(LAT_N), 4) FROM STATION WHERE LAT_N < 137.2345; -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation15.sql: -------------------------------------------------------------------------------- 1 | -- Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in STATION that is less than 137.2345. 2 | -- Round your answer to 4 decimal places. 3 | 4 | SELECT ROUND(LONG_W, 4) FROM STATION WHERE LAT_N = (SELECT MAX(LAT_N) FROM STATION WHERE LAT_N < 137.2345); -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation16.sql: -------------------------------------------------------------------------------- 1 | -- Query the smallest Northern Latitude (LAT_N) from STATION that is greater than 38.7780. 2 | -- Round your answer to 4 decimal places. 3 | 4 | SELECT ROUND(LAT_N, 4) FROM STATION WHERE LAT_N = (SELECT MIN(LAT_N) FROM STATION WHERE LAT_N > 38.7780); -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation17.sql: -------------------------------------------------------------------------------- 1 | -- Query the Western Longitude (LONG_W)where the smallest Northern Latitude (LAT_N) in STATION is greater than 38.7780. 2 | -- Round your answer to 4 decimal places. 3 | 4 | SELECT ROUND(LONG_W, 4) FROM STATION WHERE LAT_N = (SELECT MIN(LAT_N) FROM STATION WHERE LAT_N > 38.7780); -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation18.sql: -------------------------------------------------------------------------------- 1 | -- Consider P1(a,b) and P2(c,d) to be two points on a 2D plane. 2 | 3 | -- a happens to equal the minimum value in Northern Latitude (LAT_N in STATION). 4 | -- b happens to equal the minimum value in Western Longitude (LONG_W in STATION). 5 | -- c happens to equal the maximum value in Northern Latitude (LAT_N in STATION). 6 | -- d happens to equal the maximum value in Western Longitude (LONG_W in STATION). 7 | 8 | -- Query the Manhattan Distance between points P1 9 | -- and P2 and round it to a scale of 4 decimal places. 10 | 11 | SELECT ROUND((MAX(LAT_N) - MIN(LAT_N)) + (MAX(LONG_W) - MIN(LONG_W)), 4) FROM STATION; -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation19.sql: -------------------------------------------------------------------------------- 1 | -- Consider P1(a, c) and P2(b, d) to be two points on a 2D plane where (a, b) are the respective minimum and maximum values of Northern Latitude (LAT_N) and 2 | -- (c, d) are the respective minimum and maximum values of Western Longitude (LONG_W) in STATION. 3 | 4 | -- Query the Euclidean Distance between points P1 5 | -- and P2 and format your answer to display decimal digits. 6 | 7 | SELECT ROUND(POWER(POWER(MAX(LAT_N) - MIN(LAT_N), 2) + POWER(MAX(LONG_W) - MIN(LONG_W), 2), 0.5), 4) FROM STATION; -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation7.sql: -------------------------------------------------------------------------------- 1 | -- Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. 2 | -- Your result cannot contain duplicates. 3 | 4 | select DISTINCT(CITY) from STATION 5 | where CITY LIKE '%A' 6 | or CITY LIKE '%E' 7 | or CITY LIKE '%I' 8 | or CITY LIKE '%O' 9 | or CITY LIKE '%U'; -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation8.sql: -------------------------------------------------------------------------------- 1 | -- Query the list of CITY names from STATION which 2 | -- have vowels (i.e., a, e, i, o, and u) as both their first and last characters. 3 | -- Your result cannot contain duplicates. 4 | 5 | --^ and $ anchor the match to the beginning and end of the value. 6 | 7 | select DISTINCT(CITY) FROM STATION WHERE 8 | CITY RLIKE '^[aeiouAEIOU].*[aeiouAEIOU]$' -------------------------------------------------------------------------------- /HackerRank/Sql/WeatherObservationStation9.sql: -------------------------------------------------------------------------------- 1 | -- Query the list of CITY names from STATION that do not start with vowels. 2 | -- Your result cannot contain duplicates. 3 | 4 | select distinct(CITY) FROM STATION 5 | WHERE CITY NOT RLIKE '^[AEIOUaeiou].*$' -------------------------------------------------------------------------------- /JavaFiles/Applet/HelloJava.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /JavaFiles/Applet/HelloWorld.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/JavaFiles/Applet/HelloWorld.class -------------------------------------------------------------------------------- /JavaFiles/Applet/HelloWorld.java: -------------------------------------------------------------------------------- 1 | import java.applet.Applet; 2 | import java.awt.Graphics; 3 | 4 | public class HelloWorld extends Applet{ 5 | public void paint(Graphics g) 6 | { 7 | g.drawString("Hello World!", 150, 150); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /JavaFiles/Constructors/Constructor Overloading/ABCCollege.java: -------------------------------------------------------------------------------- 1 | public class ABCCollege{ 2 | public static void main(String[] args) 3 | { 4 | Student studentObj = new Student(101, "Tina", "ECE"); 5 | 6 | studentObj.display(); 7 | studentObj.setScore(9.5f); 8 | System.out.println(studentObj.getScore()); 9 | 10 | // You can access a static variable using the class Name itself 11 | System.out.println(Student.collegeName); 12 | } 13 | } -------------------------------------------------------------------------------- /JavaFiles/Constructors/Non Argument Constructors/ConsDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/JavaFiles/Constructors/Non Argument Constructors/ConsDemo.class -------------------------------------------------------------------------------- /JavaFiles/Constructors/Non Argument Constructors/MyClass.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/JavaFiles/Constructors/Non Argument Constructors/MyClass.class -------------------------------------------------------------------------------- /JavaFiles/Constructors/Non Argument Constructors/MyClass.java: -------------------------------------------------------------------------------- 1 | public class MyClass { 2 | int num; 3 | 4 | MyClass() { 5 | num = 100; 6 | } 7 | } 8 | 9 | class ConsDemo { 10 | public static void main(String args[]) { 11 | MyClass t1 = new MyClass(); 12 | MyClass t2 = new MyClass(); 13 | 14 | System.out.println(t1.num + " " + t2.num); 15 | } 16 | } -------------------------------------------------------------------------------- /JavaFiles/Constructors/Parameterized Constructors/ConsDemo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/JavaFiles/Constructors/Parameterized Constructors/ConsDemo.class -------------------------------------------------------------------------------- /JavaFiles/Constructors/Parameterized Constructors/ConsDemo.java: -------------------------------------------------------------------------------- 1 | class MyClass { 2 | int num; 3 | 4 | MyClass(int num) { 5 | this.num = num; 6 | } 7 | } 8 | 9 | public class ConsDemo { 10 | public static void main(String args[]) { 11 | MyClass t1 = new MyClass(12); 12 | MyClass t2 = new MyClass(16); 13 | System.out.println(t1.num + " " + t2.num); 14 | } 15 | } -------------------------------------------------------------------------------- /JavaFiles/Constructors/Parameterized Constructors/MyClass.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/JavaFiles/Constructors/Parameterized Constructors/MyClass.class -------------------------------------------------------------------------------- /JavaFiles/ObjectsAndClasses/Employee.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/JavaFiles/ObjectsAndClasses/Employee.class -------------------------------------------------------------------------------- /JavaFiles/ObjectsAndClasses/EmployeeTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/JavaFiles/ObjectsAndClasses/EmployeeTest.class -------------------------------------------------------------------------------- /JavaFiles/ObjectsAndClasses/EmployeeTest.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class EmployeeTest { 4 | public static void main(String args[]) { 5 | Employee empOne = new Employee("Tom Boy"); 6 | Employee empTwo = new Employee("Good Boy"); 7 | 8 | empOne.setAge(20); 9 | empOne.setDes("Associate"); 10 | empOne.setSalary(20000); 11 | 12 | empTwo.setAge(50); 13 | empTwo.setDes("Boss"); 14 | empTwo.setSalary(20000000); 15 | 16 | empOne.printEmployee(); 17 | System.out.println(); 18 | empTwo.printEmployee(); 19 | 20 | } 21 | } -------------------------------------------------------------------------------- /LeetCode/.directory: -------------------------------------------------------------------------------- 1 | [Dolphin] 2 | Timestamp=2020,12,20,20,17,41 3 | Version=4 4 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "map": "cpp", 4 | "array": "cpp", 5 | "deque": "cpp", 6 | "forward_list": "cpp", 7 | "list": "cpp", 8 | "string": "cpp", 9 | "unordered_map": "cpp", 10 | "unordered_set": "cpp", 11 | "vector": "cpp", 12 | "string_view": "cpp", 13 | "initializer_list": "cpp", 14 | "regex": "cpp", 15 | "valarray": "cpp", 16 | "ostream": "cpp", 17 | "xstring": "cpp", 18 | "xlocale": "cpp" 19 | } 20 | } -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "xlocale": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/1bitAnd2bitCharacters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | bool isOneBitCharacter(vector &bits) 9 | { 10 | int i = 0; 11 | while (i < bits.size() - 1) 12 | { 13 | i += (bits[i] + 1); 14 | } 15 | 16 | return i == (bits.size() - 1); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ArrayPartition1.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int arrayPairSum(vector &nums) 5 | { 6 | int sum = 0; 7 | sort(nums.begin(), nums.end()); 8 | // As we have sorted it, we can directly 9 | // grab the 1st element in each of the pairs 10 | for (int i = 0; i < nums.size(); i += 2) 11 | { 12 | sum += nums[i]; 13 | } 14 | return sum; 15 | } 16 | }; 17 | 18 | // Time Complexity - O(nlogn), Sorting take O(nlog(n)) time 19 | // Space Complexity - O(1), constant extra space used -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/BestTimeToBuyAndSellStock/BestTimeToBuyAndSellStockM1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& nums) { 4 | int maxPro = 0; 5 | int min_val = INT_MAX; 6 | for(int i=0; i& nums) { 4 | int max_profit = 0; 5 | int min_value = INT_MAX; 6 | for(int i=0; i& nums){ 4 | int sum = 0; 5 | int n = nums.size(); 6 | for(int i=0; i nums[i]) 8 | sum += nums[i+1] - nums[i]; 9 | } 10 | return sum; 11 | } 12 | }; 13 | 14 | // Time Complexity - O(N) 15 | // Space Complexity - O(1) 16 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/BigCountries.sql: -------------------------------------------------------------------------------- 1 | -- Write your MySQL query statement below 2 | SELECT name, population, area 3 | FROM World 4 | WHERE area > 3000000 or population > 25000000; 5 | 6 | 7 | -- / Other Solution 8 | -- Write your MySQL query statement below 9 | SELECT name, population, area 10 | from World 11 | WHERE area > 3000000 12 | UNION 13 | SELECT name, population, area 14 | FROM World 15 | WHERE 16 | population > 25000000; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/BuddyStrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buddyStrings(self, A: str, B: str) -> bool: 3 | if len(A)!=len(B): 4 | return False 5 | elif sorted(A)!=sorted(B): 6 | return False 7 | elif A==B and len(set(A))==len(A): 8 | return False 9 | else: 10 | count=0 11 | for i in range(len(A)): 12 | if A[i]!=B[i]: 13 | count+=1 14 | if count==3: 15 | return False 16 | return True 17 | 18 | # Time Complexity : O(nlogn) 19 | # Space Complextiy : O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/CanPlaceFlowers.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool canPlaceFlowers(vector &flowerbed, int n) 5 | { 6 | int size = flowerbed.size(); 7 | 8 | int count = 0; 9 | for (int i = 0; i < size; i++) 10 | { 11 | if (flowerbed[i] != 1 && (i == 0 || flowerbed[i - 1] != 1) && (i == size - 1 || flowerbed[i + 1] != 1)) 12 | { 13 | count++; 14 | flowerbed[i] = 1; 15 | } 16 | } 17 | 18 | return count >= n; 19 | } 20 | }; 21 | 22 | // Time Complexity - O(N) 23 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ClassesMoreThan5Students.sql: -------------------------------------------------------------------------------- 1 | SELECT class FROM courses GROUP BY class 2 | HAVING COUNT(DISTINCT student) >= 5; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/Contains_Duplicate/ContainsDuplicateM1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution 3 | { 4 | public: 5 | bool containsDuplicate(vector &nums) 6 | { 7 | if (nums.size() == 0) 8 | return false; 9 | sort(nums.begin(), nums.end()); // 4 10 | for (int i = 0; i < nums.size() - 1; i++) // 0, 1, 2 11 | if (nums[i] == nums[i + 1]) 12 | return true; 13 | return false; 14 | } 15 | }; 16 | 17 | // Time Complexity - O(nlogn) 18 | // Space Complexity - O(1) 19 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/Contains_Duplicate/ContainsDuplicateM2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution 3 | { 4 | public: 5 | bool containsDuplicate(vector &nums) 6 | { 7 | set s; 8 | for (int i = 0; i < nums.size(); i++) 9 | { 10 | // To check if element is already present in set 11 | if (s.find(nums[i]) != s.end()) 12 | return true; 13 | s.insert(nums[i]); 14 | } 15 | return false; 16 | } 17 | }; 18 | 19 | // Space Complexity - O(N) 20 | // Time Complexiy - O(N) 21 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/CountNumberOfHomogenousSubstrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int countHomogenous(string s) 5 | { 6 | int count = 0; 7 | int result = 0; 8 | int n = s.size(); 9 | for (int i = 0; i < n; i++) 10 | { 11 | if (i > 0 && s[i - 1] == s[i]) 12 | { 13 | count++; 14 | } 15 | else 16 | { 17 | count = 1; 18 | } 19 | result = (result + count) % (1000000007); 20 | } 21 | return result; 22 | } 23 | }; 24 | 25 | // Time Complexity - O(N) 26 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/CountOfMatchesInTournament.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int numberOfMatches(int n) 5 | { 6 | int advance = 0; 7 | int matches = 0; 8 | while (n != 1) 9 | { 10 | if (n % 2 == 0) 11 | { 12 | matches += n / 2; 13 | n = n / 2; 14 | } 15 | else if (n % 2 == 1) 16 | { 17 | matches += (n - 1) / 2; 18 | n = (n - 1) / 2 + 1; 19 | } 20 | } 21 | return matches; 22 | } 23 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/CountSquareSumTriples.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countTriples(int n) { 4 | int count = 0; 5 | for(int a=1; a<=n-2; a++) 6 | { 7 | for(int b=a+1; b<=n-1; b++) 8 | { 9 | for(int c=b+1; c<=n; c++) 10 | { 11 | int LHS = a * a + b * b; 12 | int RHS = c*c; 13 | 14 | if(LHS == RHS) 15 | count +=2; 16 | } 17 | } 18 | } 19 | return count; 20 | } 21 | }; 22 | 23 | // Time Complexity - O(N**3) 24 | // Space Complexity - O(1) 25 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/DefangingAnIPAddress/DefangingAnIPAddress.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | class Solution { 5 | public: 6 | string defangIPaddr(string address) { 7 | string solution; 8 | for(char &itr: address) 9 | { 10 | if(itr == '.') 11 | solution += "[.]"; 12 | else 13 | solution += itr; 14 | } 15 | return solution; 16 | } 17 | }; 18 | 19 | // Space complexity - O(n) --> Storing in a string 20 | // Time Complexity - O(n) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/DefangingAnIPAddress/DefangingAnIPAddress.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | a = "" 4 | for i in range(len(address)): 5 | if address[i] == '.': 6 | a += '[.]' 7 | elif address[i] != '.': 8 | a += address[i] 9 | return a 10 | 11 | # Time Complexity - O(n) 12 | # Space Complexity - O(n) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/DeleteCharactersToMakeFancyString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string makeFancyString(string s) { 4 | string result = ""; 5 | 6 | int count = 1; 7 | 8 | for(int i=0; i records; 5 | int counter = 1; 6 | OrderedStream(int n) 7 | { 8 | } 9 | 10 | vector insert(int id, string value) 11 | { 12 | records[id] = value; 13 | vector result; 14 | 15 | while (records.count(counter)) 16 | { 17 | result.push_back(records[ptr]); 18 | counter++; 19 | } 20 | return result; 21 | } 22 | }; 23 | 24 | /** 25 | * Your OrderedStream object will be instantiated and called as such: 26 | * OrderedStream* obj = new OrderedStream(n); 27 | * vector param_1 = obj->insert(id,value); 28 | */ -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/DetermineIfStringHalvesAreAlike.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | n = len(s) 4 | half_n = int(n/2) 5 | # print(half_n) 6 | first = s[:half_n] 7 | second = s[half_n:] 8 | 9 | count_first = 0 10 | count_second = 0 11 | s = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] 12 | for i in first: 13 | if(i in s): 14 | count_first += 1 15 | for i in second: 16 | if(i in s): 17 | count_second += 1 18 | 19 | if(count_first == count_second): 20 | return True 21 | return False 22 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/DistributeCandies/DistributeCandies.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def distributeCandies(self, candyType: List[int]) -> int: 3 | set_candy = set(candyType) 4 | len_set_candy = len(set_candy) 5 | 6 | candy_len = len(candyType) 7 | 8 | num_candies = candy_len / 2 9 | 10 | if(len_set_candy < num_candies): 11 | return int(len_set_candy) 12 | else: 13 | return int(num_candies) 14 | # Time Complexity - O(N), since iterating over a list is O(N) and adding each element to the hast set is O(1), so the total operation is O(N). 15 | # Space Complexity - O(N), using set 16 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/DistributeMoneyToMaximumChildren.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int distMoney(int money, int children) { 4 | money = money - children; 5 | 6 | if(money < 0) { 7 | return -1; 8 | } 9 | 10 | if(money / 7 == children && money % 7 == 0) { 11 | return children 12 | } 13 | 14 | if(money / 7 == children - 1 && money % 7 == 3) { 15 | return children - 2; 16 | } 17 | 18 | return min(children - 1, money / 7); 19 | } 20 | }; 21 | 22 | // money = 20, children = 3 23 | // Output: 1 24 | 25 | // money = 16, children = 2 26 | // Output: 2 27 | 28 | // 20 - 3 = 17 29 | // 17 / 7 = 2... 30 | // 17 % 7 == 3 -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ExcelSheetColumnNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string s) { 4 | long result = 0; 5 | int N = s.size(); 6 | for(int i=0; i 2 | using namespace std; 3 | #define MAX 100 4 | #define NIL -1 5 | 6 | int lookup[MAX]; 7 | 8 | void initialize() 9 | { 10 | for(int i=0; i>n; 30 | 31 | 32 | initialize(); 33 | cout< &nums) 5 | { 6 | int count_even = 0; 7 | for (int &n : nums) 8 | { 9 | if (to_string(n).size() % 2 == 0) 10 | count_even += 1; 11 | } 12 | return count_even; 13 | } 14 | }; 15 | 16 | // Converting the each number into a string and checking if the size 17 | // of the string is even or not -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/FindTheDifference.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | char findTheDifference(string s, string t) 5 | { 6 | char r = 0; 7 | for (char &c : s) 8 | r ^= c; 9 | for (char &c : t) 10 | r ^= c; 11 | return r; 12 | } 13 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/FindTheDuplicateNumber/FindTheDuplicateNumberExtraSpace.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution { 3 | public: 4 | int findDuplicate(vector& nums) { 5 | int n = nums.size(); 6 | unordered_set s; 7 | for(int i=0; i& gain) { 4 | int sum = 0; 5 | int result = 0; 6 | 7 | for(int i=0; i intersect(vector& nums1, vector& nums2) { 4 | unordered_map s; 5 | for(int x: nums1) 6 | s[x]++; 7 | vector result; 8 | for(int y: nums2) 9 | if(s.find(y) != s.end()) 10 | { 11 | s[y]--; 12 | if(s[y] == 0) s.erase(y); 13 | result.push_back(y); 14 | } 15 | return result; 16 | } 17 | }; 18 | 19 | // Time Complexity - O(N) 20 | // Space Complexity - O(N), since we're using unordered_map and vector to store the result 21 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/JewelsAndStones/JewelsAndStones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numJewelsInStones(string J, string S) { 4 | // J - Jewels 5 | // S - Stones you have 6 | int count = 0; 7 | vector word(128, 0); 8 | for(char& c: J) word[c]++; 9 | for(char& c: S) if(word[c]) count+= 1; 10 | return count; 11 | } 12 | }; 13 | 14 | // Time Complexity - O(J+S) -- Since we are iterating for J and S 15 | // Space Complexity - O(1) -- Since we are using a hashmap 16 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/JewelsAndStones/JewelsAndStones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, J: str, S: str) -> int: 3 | count = 0 4 | for i in S: 5 | if i in J: 6 | count += 1 7 | return count 8 | 9 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/LengthOfLastWord.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int lengthOfLastWord(string s) 5 | { 6 | int left = s.size() - 1; 7 | int result = 0; 8 | 9 | // The loop will contine till will find the first NonSpace Character 10 | while (left >= 0 && s[left] == ' ') 11 | left--; 12 | 13 | // This will continue till we find the next space character 14 | // 15 | while (left >= 0 && s[left] != ' ') 16 | { 17 | result++; 18 | left--; 19 | } 20 | return result; 21 | } 22 | }; 23 | 24 | // Time Complexity - O(n), if all the characters are ' ' spaces 25 | // Space Complexity - O(1), constant space -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/LongestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | if (strs.empty()) 5 | return ""; 6 | 7 | for (int i = 0; i < strs[0].length(); ++i) 8 | for (int j = 1; j < strs.size(); ++j) 9 | if (i == strs[j].length() || strs[j][i] != strs[0][i]) 10 | return strs[0].substr(0, i); 11 | 12 | return strs[0]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/MatrixDiagonalSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int diagonalSum(vector> &mat) 5 | { 6 | int start = 0; 7 | int end = mat.size() - 1; 8 | int sum = 0; 9 | for (int i = 0; i < mat.size(); i++) 10 | { 11 | if (start > (mat.size() - 1) && end < 0) 12 | break; 13 | sum += mat[start++][i]; 14 | sum += mat[end--][i]; 15 | } 16 | if (mat.size() % 2 != 0) 17 | { 18 | int mid = (mat.size() - 1) / 2; 19 | sum -= mat[mid][mid]; 20 | } 21 | 22 | return sum; 23 | } 24 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/MaxConsecutiveOnes.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findMaxConsecutiveOnes(vector &nums) 5 | { 6 | int count = 0; 7 | int max_count = 0; 8 | for (int i = 0; i < nums.size(); i++) 9 | { 10 | if (nums[i] == 1) 11 | { 12 | count++; 13 | max_count = max(max_count, count); 14 | } 15 | else 16 | count = 0; 17 | } 18 | return max_count; 19 | } 20 | }; 21 | 22 | // Time Complexity - O(n) 23 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/MaximumProductDifferenceBetweeTwoPairs/MaximumProductDifferenceBetweenTwoPairs.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProductDifference(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | n = len(nums) 9 | a, b, c, d = nums[n-1], nums[n-2], nums[0], nums[1] 10 | 11 | return (a*b) - (c*d) 12 | 13 | # Time Complexity - O(nlogn) 14 | # Space Complexity - O(1) 15 | 16 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/MaximumRepeatingSubstring.cpp: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxRepeating(self, sequence: str, word: str) -> int: 3 | 4 | result = sequence.count(word) 5 | 6 | check_word = word*result 7 | while(check_word not in sequence): 8 | result-=1 9 | check_word = word * result 10 | 11 | return result 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/MergeSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | int i = m - 1; 5 | int j = n - 1; 6 | int k = m + n - 1; 7 | while(i >= 0 && j >= 0) 8 | { 9 | if(nums1[i] > nums2[j]) 10 | { 11 | nums1[k--] = nums1[i--]; 12 | } 13 | else{ 14 | nums1[k--] = nums2[j--]; 15 | } 16 | } 17 | while(j >= 0) 18 | { 19 | nums1[k--] = nums2[j--]; 20 | } 21 | 22 | } 23 | }; 24 | 25 | // Time Complexity - O(m + n) 26 | // Space Complexity - O(m) 27 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/MinimumChangesToMakeAlternatingBinaryString.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, s: str) -> int: 3 | ans = 0 4 | for i in range(len(s)): 5 | if(i % 2 == 0 and s[i] == '1'): 6 | ans += 1 7 | if(i % 2 == 1 and s[i] == '0'): 8 | ans += 1 9 | return min(ans, len(s) - ans) 10 | 11 | # Time Complexity - O(N) 12 | # Space Complexity - O(1) 13 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/NthTribonacciNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tribonacci(int n) { 4 | int t0 = 0, t1 = 1, t2 = 1; 5 | 6 | if(n == 0) 7 | return t0; 8 | if(n == 1) 9 | return t1; 10 | if(n == 2) 11 | return t2; 12 | 13 | for(int i=3; i<=n; i++) 14 | { 15 | int temp = t0 + t1 + t2; 16 | t0 = t1; 17 | t1 = t2; 18 | t2 = temp; 19 | } 20 | 21 | return t2; 22 | } 23 | }; 24 | 25 | // Time Complexity - O(N) 26 | // Space Complexity - O(1) 27 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/NumberOfRecentCalls.cpp: -------------------------------------------------------------------------------- 1 | class RecentCounter 2 | { 3 | public: 4 | queue q; 5 | RecentCounter() 6 | { 7 | } 8 | 9 | int ping(int t) 10 | { 11 | q.push(t); 12 | while (q.front() < (t - 3000)) 13 | q.pop(); 14 | 15 | return q.size(); 16 | } 17 | }; 18 | 19 | // Time Complexity - O(1) 20 | // Space Complexity -O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/Number_of_1_Bits/NumberOf1Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int count = 0; 5 | while(n != 0) 6 | { 7 | n &= (n-1); 8 | count++; 9 | } 10 | return count; 11 | } 12 | }; 13 | 14 | // Time Complexity - O(n) // n is no. of 1 in the number 15 | // Space Complexity - O(1) 16 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/Number_of_1_Bits/NumberOf1Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | n = bin(n)[2:] 4 | str_n = str(n) 5 | return str_n.count('1') 6 | 7 | 8 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/NumberofStepsReduceNumbertoZero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfSteps (int num, int count = 0) { 4 | while(num > 0){ 5 | if(num%2 == 0) 6 | { 7 | count++; 8 | num = num / 2; 9 | } 10 | else 11 | { 12 | count++; 13 | num -= 1; 14 | } 15 | } 16 | return count; 17 | } 18 | }; 19 | 20 | // Time Complexity - O(logn) 21 | // Space Complexity - O(1) 22 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/PascalsTriangle/PascalsTriangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | result = [[1]] 4 | for i in range(1, numRows): 5 | temp1 = result[-1] + [0] 6 | temp2 = [0] + result[-1] 7 | result.append([temp1[i] + temp2[i] for i in range(len(temp1))]) 8 | return result[:numRows] 9 | 10 | 11 | # Time Complexity - O(n**2)\ 12 | # Space Complexity - O(n) 13 | 14 | """ 15 | explanation: Any row can be constructed using the offset sum of the previous row. Example: 16 | 17 | 1 3 3 1 0 18 | + 0 1 3 3 1 19 | = 1 4 6 4 1 20 | """ 21 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/RemoveDuplicatesFromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int n = nums.size(); 5 | 6 | int j=0; 7 | for(int i=0; i 0) 9 | { 10 | pop = x % 10; 11 | x = x / 10; 12 | reversed = reversed * 10 + pop; 13 | 14 | // Check whether reversed lies b/w INT_MAX && INT_MIN 15 | // if not return false 16 | if (!(reversed <= INT_MAX && reversed >= INT_MIN)) 17 | return 0; 18 | } 19 | return reversed; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ReverseString.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void reverseString(vector &s) 5 | { 6 | int n = s.size(); 7 | int start = 0; 8 | int end = n - 1; 9 | while (start < end) 10 | { 11 | char temp = s[start]; 12 | s[start] = s[end]; 13 | s[end] = temp; 14 | start++; 15 | end--; 16 | } 17 | } 18 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ReverseWordsInAString3.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | stringstream ss(s); 5 | 6 | string t; 7 | string result = ""; 8 | 9 | while(getline(ss, t, ' ')) { 10 | reverse(t.begin(), t.end()); 11 | result += t + ' '; 12 | } 13 | return result.substr(0, result.size() - 1); 14 | } 15 | 16 | }; 17 | 18 | // Time Complexity - O(N) 19 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/RichestCustomerWealth.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumWealth(vector>& accounts) { 4 | int max_money = 0; 5 | 6 | for(int i=0; i& nums, int target) { 4 | int l = 0; 5 | int r = nums.size(); 6 | 7 | while (l < r) { 8 | const int m = (l + r) / 2; 9 | if (nums[m] == target) 10 | return m; 11 | if (nums[m] < target) 12 | l = m + 1; 13 | else 14 | r = m; 15 | } 16 | 17 | return l; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ShuffleString.cpp: -------------------------------------------------------------------------------- 1 | // Simple Character replacement in the string 2 | class Solution 3 | { 4 | public: 5 | string restoreString(string s, vector &indices) 6 | { 7 | string result = s; 8 | for (int i = 0; i < s.size(); i++) 9 | { 10 | result[indices[i]] = s[i]; 11 | } 12 | return result; 13 | } 14 | }; 15 | 16 | // Time Complexity - O(n), n is the number of characters in the string 17 | // Space Complexity- O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ShuffleTheArray.cpp: -------------------------------------------------------------------------------- 1 | // Method - 1 2 | #include 3 | class Solution { 4 | public: 5 | vector shuffle(vector& nums, int n) { 6 | vector result; 7 | for(int i=0; i 0){ 7 | sum += (n%10); 8 | product *= (n%10); 9 | n = n/10; 10 | } 11 | return (product - sum); 12 | } 13 | }; 14 | 15 | // Time Complexity - O(n) 16 | // Space Complexity - O(1) 17 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ValidMountainArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool validMountainArray(vector &arr) 5 | { 6 | int i = 0; 7 | 8 | int N = arr.size(); 9 | while (i + 1 < N && arr[i] < arr[i + 1]) 10 | i++; 11 | 12 | if (i == 0 || i == N - 1) 13 | return false; 14 | 15 | while (i + 1 < N && arr[i] > arr[i + 1]) 16 | i++; 17 | if (i == N - 1) 18 | return true; 19 | 20 | return false; 21 | } 22 | }; 23 | 24 | // Time Complexity - O(N) 25 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/ValidPhoneNumbers.sh: -------------------------------------------------------------------------------- 1 | # Read from the file file.txt and output all valid phone numbers to stdout. 2 | 3 | grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt -------------------------------------------------------------------------------- /LeetCode/Algorithms/Easy/VerifyingAnAlienDictionary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAlienSorted(vector& words, string order) { 4 | int mappings[26]; 5 | 6 | for(int i=0; i nums(n, 0); 7 | int result = start; 8 | for (int i = 1; i < n; i++) 9 | { 10 | nums[i] = start + (2 * i); 11 | // cout << nums[i] << " " << result << endl; 12 | 13 | result ^= nums[i]; 14 | } 15 | return result; 16 | } 17 | }; 18 | 19 | // Time Complexity - O(n) 20 | // Space Complexity - O(1), we're using constant space -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/BinaryTreeMaximumPathSum.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int maxPathSum(TreeNode* root) { 5 | int maxi = INT_MIN; 6 | maxPathDown(root, maxi); 7 | return maxi; 8 | } 9 | 10 | int maxPathDown(TreeNode *root, int &maxi) { 11 | if(node == NULL) return 0; 12 | 13 | int left = max(0, maxPathDown(node->left, maxi)); 14 | int right = max(0, maxPathDown(node->right, maxi)); 15 | 16 | maxi = max(maxi, left + right + node->val); 17 | return max(left, right) + node->val; 18 | } 19 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/CourseSchedule3.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scheduleCourse(vector>& courses) { 4 | sort(courses.begin(), courses.end(), [](vector a, vector b) { return a[1] < b[1]; }); 5 | priority_queue heap; 6 | 7 | int now = 0; 8 | for(int i=0; i courses[i][1]) { 12 | now -= heap.top(); 13 | heap.pop(); 14 | } 15 | } 16 | return heap.size(); 17 | } 18 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/ErectTheFence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> outerTrees(vector>& trees) { 4 | 5 | } 6 | }; 7 | 8 | // Find outer fence which is convex in nature 9 | 10 | // Properties of Convex Polygon 11 | 12 | // Upper hull -> CA -- AB > anti-clock wise direction 13 | // lower hull -> CD -> DE > clock wise direction 14 | 15 | // when in lower hull, slope in anti-clock wise direction 16 | // ignore that particular edge, look for more possiblities 17 | 18 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/KInversePairsArray.cpp: -------------------------------------------------------------------------------- 1 | // Bottom-Up DP 2 | class Solution { 3 | public: 4 | int kInversePairs(int n, int k) { 5 | int dp[1001][1001] = {1}; 6 | for(int N=1; N<=n; N++) { 7 | for(int K=0; K<=k; K++) { 8 | for(int i=0; i<= min(K, N-1); ++i){ 9 | dp[N][K] = (dp[N][K] + dp[N-1][K-i]) % 1000000007; 10 | } 11 | } 12 | } 13 | return dp[n][k]; 14 | } 15 | }; 16 | 17 | 18 | // Time: O(n * k * k) 19 | // Memory: O(n * k) 20 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/LongestValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int longestValidParentheses(string s) 5 | { 6 | stack stack; 7 | 8 | int max_count = 0; 9 | 10 | stack.push(-1); 11 | 12 | for (int i = 0; i < s.size(); i++) 13 | { 14 | if (stack.top() != -1 && s[i] == ')' && s[stack.top()] == '(') 15 | { 16 | stack.pop(); 17 | max_count = max(max_count, i - stack.top()); 18 | } 19 | else 20 | { 21 | stack.push(i); 22 | } 23 | } 24 | return max_count; 25 | } 26 | }; 27 | 28 | // Time Complexity - O(N) 29 | // Space Complexity - O(N), uses stack -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/MinimumNumberOfKConsecutiveBitFlips.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minKBitFlips(vector& nums, int k) { 4 | // 1. Start window at 0, has to be size k 5 | // 2. flip, some might turn into 0's 6 | // 3. start window there 7 | 8 | deque q; 9 | int result = 0; 10 | 11 | for(int i=0; i nums.size()) { 14 | return -1; 15 | } 16 | result += 1; 17 | q.push_back(i); 18 | } 19 | } 20 | 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/NearestExitFromEntranceInMaze.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/LeetCode/Algorithms/Hard/NearestExitFromEntranceInMaze.cpp -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/NumberOfWaysToFormATargetStringGivenADictionary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numWays(vector& words, string target) { 4 | int n = target.size(); 5 | 6 | int mod = 1e9 + 7; 7 | vector res(n + 1); 8 | res[0] = 1; 9 | for(int i=0; i count(26); 11 | 12 | for(auto &w: words) { 13 | count[w[i] - 'a']++; 14 | } 15 | 16 | for(int j=n-1; j>=0; j--) { 17 | res[j+1] += res[j] * count[target[j] - 'a'] % mod; 18 | } 19 | } 20 | 21 | return res[n] % mod; 22 | } 23 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/PaintingTheWalls.cpp: -------------------------------------------------------------------------------- 1 | // Memoization 2 | // Time Complexity - O(N^2) 3 | // Space Complexity - O(N^2) 4 | 5 | class Solution { 6 | public: 7 | int paintWalls(vector& cost, vector& time) { 8 | 9 | return dfs(cost, time, cost.size(), 0); 10 | } 11 | 12 | int dfs(vector &cost, vector &time, int remain, int i) { 13 | if(remain <= 0) { 14 | return 0; 15 | } 16 | 17 | if(i == cost.size()) { 18 | return INT_MAX; 19 | } 20 | 21 | int pain = dfs(cost, time, remain - 1 - time[i], i + 1); 22 | int skip = dfs(cost, time, remain, i+1); 23 | return min(pain, skip); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/PoorPigs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 4 | if(buckets-- == 1) { 5 | return 0; 6 | } 7 | 8 | // 60 / 15 + 1 = 5 9 | int base = minutesToTest / minutesToDie + 1; 10 | 11 | // buckets = 5 12 | // buckets = 25, take 5 13 | // buckets = buckets>25 and buckets < 125 14 | int res = 0; 15 | while(buckets > 0) { 16 | buckets = buckets / base; 17 | res += 1; 18 | } 19 | return res; 20 | } 21 | }; 22 | 23 | // Time Complexity - O(log(1000)) ~ O(1) 24 | // Space Complexity - O(1) 25 | // Refer to solution from Suchit Dedeja for it -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/ProfitableSchemes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int profitableSchemes(int n, int minProfit, vector& group, vector& profit) { 4 | vector> dp(P + 1, vector(G + 1, 0)); 5 | dp[0][0] = 1; 6 | int res = 0, mod = 1e9 + 7; 7 | 8 | for(int k=0; k=0; i--) { 11 | for(int j=G - g; j>=0; j--) { 12 | dp[min(i + p, P)][j + g] = (dp[min(i + p, P)][j + g] + dp[i][j]) % mod; 13 | } 14 | } 15 | } 16 | 17 | for(int x: dp[P]) res = (res + x) % mod; 18 | return res; 19 | } 20 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/RestoreTheArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArrays(string s, int k) { 4 | vector dp(s.size(), -1); 5 | 6 | } 7 | }; 8 | 9 | 10 | arr = [1,3,4,2], 11 | 12 | mat = 13 | 0 1 14 | 0 [[1,4], 15 | 1 [2,3]] 16 | 17 | mpr 18 | 19 | 1 0 20 | 4 0 21 | 2 1 22 | 3 1 23 | 24 | mpc 25 | 1 0 26 | 4 1 27 | 2 0 28 | 3 1 29 | 30 | mpr[1] = 0 31 | mprc[mpr[1]] = 1 32 | mpcc[mpc[1]] = 1 33 | 34 | mpr[3] = 1 35 | mpc[3] = 1 36 | 37 | mprc[mpr[1]] = 2 38 | mpcc[mpc[1]] = 2 39 | 40 | mpr[4] = 1 41 | mpc[4] = 1 42 | 43 | mprc[mpr[1]] = 3 44 | mpcc[mpc[1]] = 3; 45 | 46 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/RussianDollEnvelops.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxEnvelopes(vector>& envelopes) { 4 | int n = envelopes.size(); 5 | 6 | sort(envelopes.begin(), envelopes.end()); 7 | 8 | vector dp(n+1, 1); 9 | 10 | int max = 1; 11 | 12 | for(int i=1; i envelopes[j][0] && envelopes[i][1] > envelopes[j][1] && 1 + dp[j] > dp[i]) { 15 | dp[i] = 1 + dp[j]; 16 | } 17 | if(max < dp[i]) { 18 | max = dp[i]; 19 | } 20 | } 21 | } 22 | return max; 23 | } 24 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Hard/UniquePathsIII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePathsIII(vector>& grid) { 4 | // 1 -> starting square 5 | // 2 -> ending square 6 | // 0 -> empty squares we can walk over 7 | // -1 -> obstacles we cannot walk over 8 | 9 | 10 | 11 | } 12 | }; 13 | 14 | // 1. Count zeros that exist in the matrix 15 | // 2. If you see 0, reduce CountZero, update 0 with -1 16 | // 3. Make sure you have taken care of Visited condition 17 | // 4. Check the entire path again to see if all zero've been marked 18 | // as -1. 19 | 20 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "ios": "cpp", 4 | "xiosbase": "cpp", 5 | "algorithm": "cpp", 6 | "limits": "cpp", 7 | "utility": "cpp", 8 | "xstring": "cpp", 9 | "deque": "cpp", 10 | "list": "cpp", 11 | "vector": "cpp", 12 | "initializer_list": "cpp", 13 | "queue": "cpp", 14 | "stack": "cpp", 15 | "type_traits": "cpp", 16 | "xhash": "cpp", 17 | "xtree": "cpp", 18 | "xutility": "cpp", 19 | "xlocinfo": "cpp", 20 | "xlocale": "cpp", 21 | "iterator": "cpp" 22 | } 23 | } -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/BeautifulArray.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/LeetCode/Algorithms/Medium/BeautifulArray.cpp -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/BreakAPalindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string breakPalindrome(string palindrome) { 4 | 5 | } 6 | }; 7 | 8 | // x a b y b a x 9 | // a a b y b a x 10 | 11 | 12 | // a b b y b b a 13 | // a a b y b b a 14 | 15 | // a a a y a a a 16 | // a a a y a a b // change the last element 17 | 18 | // a a a a a a 19 | // a a a a a b // change the last element 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/ConcatenationOfConsecutiveBinaryNumbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def concatenatedBinary(self, n: int) -> int: 3 | result = "" 4 | for i in range(1, n+1): 5 | result = result + bin(i)[2:] 6 | return int(result , 2) % (10**9 + 7) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/ConcatenationOfConsecutiveBinaryNumbers/ConcatenationOfConsecutiveBinaryNumbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def concatenatedBinary(self, n: int) -> int: 3 | result = "" 4 | for i in range(1, n+1): 5 | result = result + bin(i)[2:] 6 | return int(result, 2) % (10**9 + 7) 7 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/DecodedStringAtIndex.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string decodeAtIndex(string s, int k) { 4 | long size = 0; 5 | 6 | for(auto &ch: s) { 7 | if(isdigit(ch)) { 8 | size *= (ch - '0'); 9 | } else { 10 | size++; 11 | } 12 | } 13 | 14 | 15 | for(auto &ch: s) { 16 | k %= size; 17 | if(ch.isdigit()) { 18 | size /= (ch - '0'); 19 | } 20 | 21 | if(k == 0 || k == size) { 22 | return string(1, s[k]); 23 | } else { 24 | size--; 25 | } 26 | } 27 | } 28 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/DominoAndTrominoTiling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTilings(int n) { 4 | 5 | } 6 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/EarliestPossibleDayOfFullBloom.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int earliestFullBloom(vector& plantTime, vector& growTime) { 4 | 5 | } 6 | }; 7 | 8 | // plantTme = [1,4,3] 9 | // growTime = [2,3,1] 10 | 11 | // 1st approach -> sort by growtime -> 1 < 0 < 2 -> follow largest growth time approach 12 | // 2nd approach -> sort by planttime -> 1 < 2 < 0 13 | 14 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/FindDuplicateFileInSystem.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> findDuplicate(vector& paths) { 4 | unordered_map> files; 5 | vector> result; 6 | for(string &path: paths) { 7 | stringstream ss(path); 8 | string root; 9 | string s; 10 | getline(ss, root, ' '); 11 | while(geline(ss, )) 12 | } 13 | 14 | return result; 15 | } 16 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/FindTheMostCompetitiveSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution 3 | { 4 | public: 5 | vector mostCompetitive(vector &nums, int k) 6 | { 7 | vector result; 8 | 9 | int n = nums.size(); 10 | for (int i = 0; i < n; i++) 11 | { 12 | while (!result.empty() && result.back() > nums[i] && (result.size() - 1 + nums.size() - i >= k)) 13 | result.pop_back(); 14 | if (result.size() < k) 15 | result.push_back(nums[i]); 16 | } 17 | return result; 18 | } 19 | }; 20 | 21 | // Time Complexity - O(N) 22 | // Space Complexity - O(N) 23 | 24 | // See lee's solution -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/GlobalAndLocalInversion/GlobalAndLocalInversion.java: -------------------------------------------------------------------------------- 1 | public class GlobalAndLocalInversions { 2 | public boolean isIdealPermutation(int[] nums) { 3 | int max = -1; 4 | for (int i = 0; i < nums.length - 2; i++) { 5 | max = Math.max(nums[i], max); 6 | if (max > nums[i + 2]) 7 | return false; // found global inversion which is not a local inversion 8 | } 9 | return true; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/GlobalAndLocalInversion/GlobalAndLocalInversions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #include 5 | class Solution 6 | { 7 | public: 8 | bool isIdealPermutation(vector &A) 9 | { 10 | for (int i = 0; i < A.size(); i++) 11 | { 12 | if (abs(i - A[i]) > 1) 13 | return false; 14 | } 15 | return true; 16 | } 17 | }; 18 | 19 | // Time Complexity - O(N) 20 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/HandOfStraights.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/LeetCode/Algorithms/Medium/HandOfStraights.cpp -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/HouseRobber/HouseRobber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int rob1 = 0, rob2 = 0; 5 | 6 | // [1, 2, 3, 1] 7 | // [rob1, rob2, n, n+1....] 8 | 9 | for(int &element: nums) 10 | { 11 | int temp = max(rob1 + element, rob2); 12 | rob1 = rob2; 13 | rob2 = temp; 14 | } 15 | 16 | return rob2; 17 | } 18 | }; 19 | 20 | // Time Complexity - O(N) 21 | // Space Complexity - O(1), Dynamic programming 22 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/HouseRobber/HouseRobber.java: -------------------------------------------------------------------------------- 1 | public class HouseRobberI { 2 | public int rob(int[] nums) { 3 | if (nums.length == 0) return 0; 4 | 5 | int[] dp = new int[nums.length + 1]; 6 | dp[0] = 0; 7 | dp[1] = nums[0]; 8 | 9 | for (int i = 1; i < nums.length; i++) { 10 | dp[i + 1] = Math.max(dp[i], dp[i - 1] + nums[i]); 11 | } 12 | 13 | return dp[nums.length]; 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/InsertDeleteGetRandom.cpp: -------------------------------------------------------------------------------- 1 | class RandomizedSet { 2 | public: 3 | unordered_set set; 4 | RandomizedSet() { 5 | 6 | } 7 | 8 | bool insert(int val) { 9 | set.insert(val); 10 | } 11 | 12 | bool remove(int val) { 13 | set.erase(set.find(val)); 14 | } 15 | 16 | int getRandom() { 17 | int n = set.size(); 18 | 19 | } 20 | }; 21 | 22 | /** 23 | * Your RandomizedSet object will be instantiated and called as such: 24 | * RandomizedSet* obj = new RandomizedSet(); 25 | * bool param_1 = obj->insert(val); 26 | * bool param_2 = obj->remove(val); 27 | * int param_3 = obj->getRandom(); 28 | */ -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/JumpGame.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int n = nums.size(); 5 | vector dp(n, false); 6 | dp[0] = true; 7 | 8 | for(int i=1; i=0; j--) { 10 | if(dp[j] && j + nums[j] >= i) { 11 | dp[i] = true; 12 | break; 13 | } 14 | } 15 | } 16 | 17 | return dp[n-1]; 18 | } 19 | }; 20 | 21 | // DP - O(N**2) 22 | // Greedy - O(N) 23 | 24 | // [2, 3, 1, 1, 4] 25 | // 0, 1, 2, 3, 4 26 | 27 | 28 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/JumpGame2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | int result = 0; 5 | 6 | int left = 0; 7 | int right = 0; 8 | 9 | while(right < nums.size() - 1) { 10 | int farthest = 0; 11 | for(int i=left; i<=right; i++) { 12 | farthest = max(farthest, nums[i] + i); 13 | } 14 | left = right + 1; 15 | right = farthest; 16 | result += 1; 17 | } 18 | 19 | return result; 20 | } 21 | }; 22 | 23 | // Time Complexity - o(N) 24 | // Space complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/JumpGame4.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxResult(vector& nums, int k) { 4 | /* 5 | - For every index starting from 1: --- n 6 | - Find out the max sum from all {i-1} to {i - k} index --- klogk 7 | - sum[index] = value[index] + maxFound 8 | - Result is sum[length - 1] 9 | */ 10 | 11 | int n = nums.size(); 12 | int max = nums[0]; 13 | priority_queue pq; 14 | for(int i=1; ihead = head; 6 | } 7 | 8 | int getRandom() { 9 | int ans = 0, i = 1; 10 | 11 | ListNode *p = this->head; 12 | 13 | while(p) { 14 | if(rand() % i == 0) { 15 | ans = p->val; // replace ans with i-th 16 | } 17 | i++; 18 | p = p->next; 19 | } 20 | return ans; 21 | } 22 | }; 23 | 24 | // Time Complexity - O(N) 25 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/MaxNumberOfKSumPairs/MaxNumberOfKSumPairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxOperations(self, nums: List[int], k: int) -> int: 3 | nums.sort() 4 | count = 0 5 | start = 0 6 | end = len(nums) - 1 7 | while(start < end): 8 | val = nums[start] + nums[end] 9 | if(val == k): 10 | count += 1 11 | nums.pop(start) 12 | end -= 1 13 | nums.pop(end) 14 | end -= 1 15 | elif(val > k): 16 | end-=1 17 | elif(val < k): 18 | start+=1 19 | 20 | return count -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/MaximumLengthOfSubarrayWithPositiveProduct.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getMaxLen(vector& nums) { 4 | int posLen = 0, neglen = 0, maxLen = 0; 5 | 6 | for(int &i: nums) { 7 | if(i == 0) posLen = 0, negLen = 0; 8 | else { 9 | if(i < 0) swap(posLen, negLen); 10 | if(posLen > 0 || i > 0) ++posLen; 11 | if(negLen > 0 || i < 0) ++negLen; 12 | } 13 | } 14 | return maxLen; 15 | } 16 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/MaximumProfitInJobScheduling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jobScheduling(vector& startTime, vector& endTime, vector& profit) { 4 | 5 | } 6 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/Minimum SwapstoGroupAll1sTogetherII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSwaps(vector& nums) { 4 | int n = nums.size(); 5 | int total_ones = count(begin(nums), end(nums), 1); 6 | int max_window_ones = 0, window_ones = 0; 7 | 8 | int l = 0; 9 | for(int r=0; r<2*n; r++) { 10 | if(nums[r]) { 11 | window_ones++; 12 | } 13 | if(r - l + 1 > total_ones) { 14 | window_ones--; 15 | l++; 16 | } 17 | max_window_ones = max(max_window_ones, window_ones) 18 | } 19 | 20 | return total_ones - max_window_ones; 21 | } 22 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/MinimumNumberOfRungs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addRungs(vector& rungs, int dist) { 4 | int previous = 0; 5 | int result = 0; 6 | for(int &rung: rungs) 7 | { 8 | result += (rung - previous - 1) / dist; 9 | previous = rung; 10 | } 11 | return result; 12 | } 13 | }; 14 | 15 | // Time Complexity - O(N), N is the number of elements in rungs 16 | // Space Complexity - O(1) 17 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/MonotonicArray/MonotonicArray.java: -------------------------------------------------------------------------------- 1 | public class MonotonicArray { 2 | public boolean isMonotonic(int[] nums) { 3 | boolean up = true, down = true; 4 | for (int i = 0; i < nums.length - 1; i++) { 5 | if (nums[i] > nums[i + 1]) 6 | up = false; 7 | if (nums[i] < nums[i + 1]) 8 | down = false; 9 | } 10 | return up || down; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/PascalTriangleII/PascalTriangleII.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | 4 | public class PascalTriangleII { 5 | public List getRow(int rowIndex) { 6 | Integer[] result = new Integer[rowIndex + 1]; 7 | Arrays.fill(result, 0); 8 | result[0] = 1; 9 | for (int i = 1; i <= rowIndex; i++) { 10 | for (int j = i; j > 0; j--) { 11 | result[j] = result[j] + result[j - 1]; 12 | } 13 | } 14 | return Arrays.asList(result); 15 | } 16 | } 17 | /*Complexity : 18 | * TC: o(k*k) where k is rowIndex 19 | * SC: o(k) where k is rowIndex 20 | * */ 21 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/PerfectSquares.cpp: -------------------------------------------------------------------------------- 1 | // Method : Dynamic Programming 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution 7 | { 8 | public: 9 | int numSquares(int n) 10 | { 11 | if (n <= 0) 12 | return 0; 13 | 14 | vector cntPerfectSquares(n + 1, INT_MAX); 15 | cntPerfectSquares[0] = 0; 16 | for (int i = 1; i <= n; i++) 17 | { 18 | for (int j = 1; j * j <= i; j++) 19 | { 20 | cntPerfectSquares[i] = min(cntPerfectSquares[i], cntPerfectSquares[i - (j * j)] + 1); 21 | } 22 | } 23 | 24 | return cntPerfectSquares.back(); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/PrefixTreeOrTrie.notes.txt: -------------------------------------------------------------------------------- 1 | Prefix Trees are also called as Trie's. 2 | 3 | Prefix Trees is a lot more intuitive since they are mostly used for Prefix related problems. 4 | 5 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/RotateArray/RotateArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | k %= nums.size(); 5 | int size = nums.size(); 6 | int i = 0; 7 | reverse(nums, 0, size-1); 8 | reverse(nums, 0, k-1); 9 | reverse(nums, k, size-1); 10 | } 11 | void reverse(vector& nums, int start, int end){ 12 | while(start < end){ 13 | int temp = nums[start]; 14 | nums[start] = nums[end]; 15 | nums[end] = temp; 16 | start++; 17 | end--; 18 | } 19 | } 20 | }; 21 | 22 | // Time Complexity - O(N) 23 | // Space Complexity - O(1) 24 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/RotateArray/RotateArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[] nums, int k) { 3 | int n = nums.length; 4 | 5 | k = k % n; 6 | 7 | reverse(nums, 0, n-1); 8 | reverse(nums, 0, k-1); 9 | reverse(nums, k, n-1); 10 | } 11 | 12 | public void reverse(int[] nums, int start, int end) 13 | { 14 | while(start < end) 15 | { 16 | int temp = nums[start]; 17 | nums[start] = nums[end]; 18 | nums[end] = temp; 19 | start++; 20 | end--; 21 | } 22 | } 23 | } 24 | 25 | // Time Complexity - O(N) 26 | // Space Complexity - O(1), no additional space required -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/ScoreOfParentheses/ScoreOfParentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class ScoreOfParanthesis { 4 | public int scoreOfParentheses(String s) { 5 | Stack stack = new Stack<>(); 6 | 7 | int score = 0; 8 | 9 | for (char c : s.toCharArray()) { 10 | if (c == '(') { 11 | stack.push(score); 12 | score = 0; 13 | } else { 14 | score = stack.pop() + Math.max(score * 2, 1); 15 | } 16 | } 17 | return score; 18 | } 19 | /* 20 | ((()())) = 8 21 | 22 | stack = 2 * (2 * (1 + 1)) 23 | */ 24 | } 25 | 26 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/ShortestPathWithAlternatingColors.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/LeetCode/Algorithms/Medium/ShortestPathWithAlternatingColors.cpp -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/SmallestIntegerDivisiblebyK.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int smallestRepunitDivByK(int K) 5 | { 6 | if (K % 2 == 0 || K % 5 == 0) 7 | return -1; 8 | 9 | int prev_rem = 0; 10 | 11 | for (int i = 1; i <= K; i++) 12 | { 13 | prev_rem = ((prev_rem * 10) + 1) % K; 14 | 15 | if (prev_rem == 0) 16 | return i; 17 | } 18 | 19 | return -1; 20 | } 21 | }; 22 | 23 | // Time Complexity - O(K) 24 | // Space Complexity - O(1) 25 | 26 | // 111 = 110 + 1 27 | // 111 % 6 = 110 % 6 + 1; 28 | 29 | // 111 % 6 = 11%6 * 10 + 1%6; 30 | // next_rem = (prev_rem * 10 + 1) % 6 -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/SnakesAndLadders.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int snakesAndLadders(vector>& board) { 4 | int length = board.size(); 5 | 6 | queue> q; // [square, moves] 7 | q.push(make_pair(1, 0)); 8 | unordered_set visit; 9 | while(!q.empty()) { 10 | int square, moves; 11 | square, moves = visit.front(); 12 | visit.pop(); 13 | 14 | 15 | } 16 | 17 | 18 | } 19 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/SubarrayProductLessThanK/SubarrayProductLessThanK.java: -------------------------------------------------------------------------------- 1 | public class SubarrayProductLessThanK { 2 | public int numSubarrayProductLessThanK(int[] nums, int k) { 3 | if (k <= 1) return 0; 4 | 5 | int count = 0; 6 | int prod = 1; 7 | 8 | // sliding window; 9 | int left = 0, right = 0; 10 | 11 | while (right < nums.length) { 12 | prod *= nums[right]; 13 | while (prod >= k) { 14 | prod /= nums[left]; 15 | left++; 16 | } 17 | 18 | count += right - left + 1; // + 1 for individual numbers also 19 | right++; 20 | } 21 | 22 | return count; 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/SubarraySumEqualsK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | class Solution 6 | { 7 | public: 8 | int subarraySum(vector &nums, int k) 9 | { 10 | int count = 0; 11 | int sum = 0; 12 | unordered_map map = {{0, 1}}; 13 | 14 | for (int i = 0; i < nums.size(); i++) 15 | { 16 | sum += nums[i]; 17 | 18 | if (map.find(sum - k) != map.end()) 19 | count += map[sum - k]; 20 | map[sum]++; 21 | } 22 | return count; 23 | } 24 | }; 25 | 26 | // Time Complexity - O(N) 27 | // Space Complexity - O(N) -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/TaskSchedular/TaskSchedular.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class TaskSchedular { 4 | public int leastInterval(char[] tasks, int n) { 5 | int[] char_map = new int[26]; 6 | for (char c : tasks) { 7 | char_map[c - 'A']++; 8 | } 9 | Arrays.sort(char_map); 10 | 11 | int partCount = char_map[25] - 1; 12 | int idle_slots = partCount * n; 13 | for (int i = 24; i >= 0; i--) { 14 | idle_slots -= Math.min(char_map[i], partCount); 15 | } 16 | return idle_slots > 0 ? idle_slots + tasks.length : tasks.length; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/TheKthFactorOfN.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int kthFactor(int n, int k) 5 | { 6 | vector factors; 7 | 8 | for (int i = 1; i <= n; i++) 9 | { 10 | if (n % i == 0) 11 | factors.push_back(i); 12 | if (factors.size() == k) 13 | return factors.back(); 14 | } 15 | return -1; 16 | } 17 | }; 18 | 19 | // Time Complexity - O(N) 20 | // Space Complexity - O(N), A is the number of factors of N -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/UncrossedLines.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxUncrossedLines(vector& nums1, vector& nums2) { 4 | int m = nums1.size(), n = nums2.size(), dp[m + 1][n + 1]; 5 | 6 | memset(dp, 0, sizeof(dp)); 7 | 8 | for(int i=1; i<=m; i++) { 9 | for(int j=1; j<=n; j++) { 10 | dp[i][j] = A[i-1] == B[j-1] ? dp[i-1][j-1] + 1 : max(dp[i][j-1], dp[i-1][j]); 11 | } 12 | } 13 | return dp[m][n]; 14 | } 15 | }; -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/ValidateStackSequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validateStackSequences(vector& pushed, vector& popped) { 4 | stack stack; 5 | 6 | int n = pushed.size(); 7 | int j = 0; 8 | 9 | for(int &x: pushed) 10 | { 11 | stack.push(x); 12 | 13 | while(stack.empty() != true && stack.top() == popped[j]) 14 | { 15 | stack.pop(); 16 | j++; 17 | } 18 | } 19 | 20 | return j == n; 21 | } 22 | }; 23 | 24 | // Time Complexity - O(N), N is the length of pushed and popped 25 | // Space Complexity - O(N), since we are using a stack 26 | -------------------------------------------------------------------------------- /LeetCode/Algorithms/Medium/ZigzagConversion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convert(string s, int numRows) { 4 | if(numRows == 1) return s; 5 | 6 | string result = ""; 7 | for(int r=0; r 0 && r < (numRows - 1) && ((i + increment) - (2 * r)) < s.size()) { 12 | result += s[(i + increment) - (2 * r)]; 13 | } 14 | } 15 | } 16 | return result; 17 | } 18 | }; 19 | 20 | // Time Complexity - O(N) 21 | // Space Complexity - O(1) -------------------------------------------------------------------------------- /LeetCode/Database/DuplicateSalary.sql: -------------------------------------------------------------------------------- 1 | # Method 1 2 | 3 | SELECT EMAIL FROM (SELECT EMAIL, COUNT(EMAIL) AS NUM FROM PERSON GROUP BY EMAIL) AS STATISTICS WHERE NUM > 1; 4 | 5 | 6 | # Method 2 7 | 8 | SELECT EMAIL FROM PERSON GROUP BY EMAIL HAVING COUNT(EMAIL) > 1; 9 | -------------------------------------------------------------------------------- /LeetCode/Database/EmployeesEarningMoreThanTheirManagers.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | 3 | 4 | SELECT E1.NAME AS EMPLOYEE FROM EMPLOYEE E1 JOIN EMPLOYEE E2 ON E1.MANAGERID = E2.ID WHERE E1.SALARY > E2.SALARY; -------------------------------------------------------------------------------- /LeetCode/Database/SecondHighestSalary.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | 3 | SELECT MAX(SALARY) AS SecondHighestSalary FROM EMPLOYEE WHERE SALARY < (SELECT MAX(SALARY) FROM EMPLOYEE); 4 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/2022_Challenges/JanuaryChallenge/PairsOfSongsWithTotalDurationDivisibleBy60.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numPairsDivisibleBy60(vector& time) { 4 | int count = 0; 5 | map mp; 6 | 7 | for(int &t: time) 8 | { 9 | count += mp[(60 - t%60) % 60]; 10 | mp[t % 60] += 1; 11 | } 12 | return count; 13 | } 14 | }; 15 | 16 | // Time Complexity - O(n) 17 | // Space Complexity - O(60) // constant time complexity 18 | // It gets converted into a two-sum problem once we work with the modulo part --> refer notebook for details or lee's solution 19 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/November_LeetCoding_Challenge/ConsecutiveCharacters/ConsecutiveCharacters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPower(string s) { 4 | if(s.size() == 1) 5 | return 1; 6 | 7 | int max_count = 1; 8 | int count = 1; 9 | for(int i=0; i max_count) 14 | max_count = count; 15 | if(s[i] != s[i+1]) 16 | count = 1; 17 | } 18 | return max_count; 19 | } 20 | }; 21 | // Time Complexity - O(N), N is the number of characters in the string 22 | // Space Complexity - O(1), constant space 23 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/November_LeetCoding_Challenge/ConsecutiveCharacters/ConsecutiveCharacters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPower(self, s: str) -> int: 3 | max_count = 1 4 | count = 1 5 | for i in range(len(s)-1): 6 | if(s[i] == s[i+1]): 7 | count += 1 8 | if(count > max_count): 9 | max_count = count 10 | if(s[i] != s[i+1]): 11 | count = 1 12 | return max_count 13 | 14 | # Time Complexity - O(n) 15 | # Space Complexity - O(1) -> Linear Space 16 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day11_Remove_Duplicate_Letters/Day11RemoveDuplicateLetters.cpp: -------------------------------------------------------------------------------- 1 | // Empty 2 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day15_Rotate_Array/Day15RotateArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | int n = nums.size(); 5 | k = k % n; 6 | reverse(nums.begin(), nums.end()); 7 | reverse(nums.begin(), nums.begin()+ k); 8 | reverse(nums.begin() + k, nums.end()); 9 | 10 | } 11 | }; 12 | 13 | // Array : 1 2 3 4 5 , k = 2, Output : 4 5 1 2 3 14 | // Reverse array : 5 4 3 2 1 15 | 16 | // Reverse 5 4 --> 4 5 17 | // Now Reverse 1 2 3 --> 3 2 1 18 | 19 | // Final Answer - 4 5 1 2 3 20 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day15_Rotate_Array/Day15RotateArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[] nums, int k) { 3 | k %= nums.length; 4 | reverse(nums, 0, nums.length - 1); 5 | reverse(nums, 0, k- 1); 6 | reverse(nums, k, nums.length - 1); 7 | 8 | } 9 | void reverse(int[] a, int start, int end){ 10 | 11 | while(start < end){ 12 | int temp = a[start]; 13 | a[start] = a[end]; 14 | a[end] = temp; 15 | start++;end--; 16 | } 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day1_Number_of_Recent_Calls/Day1NumberOfRecentCalls.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class RecentCounter { 4 | public: 5 | queue q; 6 | RecentCounter() { 7 | 8 | } 9 | 10 | int ping(int t) { 11 | q.push(t); 12 | while(q.front() < t - 3000) // If q.front() is beyond lower limit -> pop it out 13 | { 14 | q.pop(); 15 | } 16 | return q.size(); 17 | 18 | } 19 | }; 20 | 21 | /** 22 | * Your RecentCounter object will be instantiated and called as such: 23 | * RecentCounter* obj = new RecentCounter(); 24 | * int param_1 = obj->ping(t); 25 | */ 26 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day1_Number_of_Recent_Calls/Day1NumberOfRecentCalls.java: -------------------------------------------------------------------------------- 1 | class RecentCounter { 2 | Queue queue; 3 | 4 | public RecentCounter() { 5 | queue = new LinkedList<>(); 6 | 7 | } 8 | 9 | public int ping(int t) { 10 | queue.add(t); 11 | while (queue.peek() < t - 3000) 12 | queue.poll(); 13 | return queue.size(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day4_Remove_Covered_Intervals/Day4RemoveCoveredIntervals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeCoveredIntervals(int[][] intervals) { 3 | Arrays.sort(intervals, (x,y) -> x[0] - y[0]); 4 | int l = -1; 5 | int r = -1; 6 | int count = 0; 7 | for(int[] interval:intervals){ 8 | if(interval[0] > l && interval[1] > r){ 9 | l = interval[0]; 10 | count++; 11 | } 12 | r = Math.max(r, interval[1]); 13 | } 14 | return count; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day5_Complement_of_Base_10_Integer/Day5ComplementOfBase10Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int bitwiseComplement(int N) { 3 | if(N ==0) 4 | return 1; 5 | int ans = 0; 6 | int mul = 1; 7 | while(N > 0){ 8 | int curBit = N & 1; 9 | N >>= 1; 10 | ans += mul * (1 - curBit); // flipping zero and 1 11 | mul *= 2; 12 | } 13 | // O(LOG2(N)) 14 | return ans; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day5_Complement_of_Base_10_Integer/Day5ComplementOfBase10Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bitwiseComplement(self, N: int) -> int: 3 | bin_N = bin(N)[2:] 4 | result = "" 5 | for i in str(bin_N): 6 | if i == "0": 7 | result += "1" 8 | if i == "1" : 9 | result += "0" 10 | return int(result, 2) 11 | 12 | # Time Complexity - O(n) 13 | # Space Complexity - O(1) 14 | 15 | # Time Complexity of bin() function in python is O(logn) 16 | -------------------------------------------------------------------------------- /LeetCode/Monthly Challenges/October_LeetCoding_Challenge/Day8_Binary_Search/Day8BinarySearch.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | 4 | int i = 0; 5 | int j = nums.length - 1; 6 | while(i <= j){ 7 | int mid = (i+j)/2; 8 | if(nums[mid] == target) 9 | return mid; 10 | else if(nums[mid] > target){ 11 | j--; 12 | } 13 | else 14 | i++; 15 | } 16 | return -1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/PreparationGuide.md: -------------------------------------------------------------------------------- 1 | Notes Making DSA 2 | 3 | 1. Code 4 | 2. Comments 5 | 3. *Examples (example : For Prims Algorithm mark tthe questions which asked that algorithm) 6 | 7 | Make notes in 8 | 1. Notebook 9 | 2. PC -------------------------------------------------------------------------------- /LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Array/BestTimetoBuyAndSellStock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int n = nums.size(); // 3 5 | int j = 0; 6 | for(int i=0; ival = node->next->val; 13 | node->next = node->next->next; 14 | 15 | } 16 | }; 17 | 18 | 19 | // Only the node to be deleted is provided, hence change 20 | // the node location and value to the next node in sequence 21 | -------------------------------------------------------------------------------- /LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Array/IntersectionOfTwoArrays2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector& nums1, vector& nums2) { 4 | unordered_map s; 5 | for(int i=0; i result; 8 | for(int i=0; i& nums) { 4 | int n = nums.size(); // 3 5 | int j = 0; 6 | for(int i=0; i& nums, int k) { 4 | k %= nums.size(); 5 | int size = nums.size(); 6 | reverse(nums, 0, size-1); 7 | reverse(nums, 0, k-1); 8 | reverse(nums, k, size-1); 9 | } 10 | void reverse(vector& nums, int start, int end){ 11 | while(start < end){ 12 | int temp = nums[start]; 13 | nums[start] = nums[end]; 14 | nums[end] = temp; 15 | start++; 16 | end--; 17 | } 18 | } 19 | }; 20 | 21 | // O(1) - Space Complexity 22 | // O(n) - Time Complexity // Elements reversed a total of 3 times 23 | -------------------------------------------------------------------------------- /LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Array/intersectionOfTwoArrays2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | if len(nums1) < len(nums2): 4 | nums1, nums2 = nums2, nums1 5 | seen = {} 6 | for i in nums1: 7 | if i not in seen: 8 | seen[i] = 1 9 | else: 10 | seen[i] += 1 11 | nums1 = [] 12 | for j in nums2: 13 | if j in seen and seen[j] > 0: 14 | nums1.append(j) 15 | seen[j] -= 1 16 | 17 | return nums1 18 | 19 | # Time Complexity - O(m + n) 20 | # Space Complexity - O(max(m, n)) 21 | -------------------------------------------------------------------------------- /LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Strings/First Unique Character in a String/FirstUniqueCharacterInString.py: -------------------------------------------------------------------------------- 1 | # Method - 1 2 | from collections import Counter 3 | class Solution: 4 | def firstUniqChar(self, s: str) -> int: 5 | charCount = Counter(s) 6 | for i in s: 7 | if charCount[i] == 1: 8 | return s.index(i) 9 | return -1 10 | 11 | # Time Complexity - O(n) 12 | # Space Complexity - O(1) 13 | 14 | # Method - 2 15 | class Solution: 16 | def firstUniqChar(self, s: str) -> int: 17 | for i in s: 18 | if s.count(i) == 1: 19 | return s.index(i) 20 | return -1 21 | 22 | # Time Complexity - O(n**2) 23 | # Space Complexity - O(n) -------------------------------------------------------------------------------- /LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Strings/ReverseInteger: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Strings/ReverseInteger -------------------------------------------------------------------------------- /LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Strings/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Strings/a.out -------------------------------------------------------------------------------- /LeetCode/Top Interview Questions/Top_Interview_Questions_Easy/Strings/reverseString/reverseString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | int n = s.size(); 5 | int start = 0, end = n-1; 6 | int repeat = n/2; 7 | while(start None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | start = 0 7 | end = len(s) - 1 8 | while start < end: 9 | s[start], s[end] = s[end], s[start] 10 | start += 1 11 | end -= 1 12 | 13 | # Time Complexity - O(n/2) 14 | # Space Complexity - O(1) -------------------------------------------------------------------------------- /MSLearn/MissingPersons.py: -------------------------------------------------------------------------------- 1 | from sklearn.datasets import fetch_olivetti_faces 2 | import datetime 3 | 4 | # Load the dataset 5 | faces = fetch_olivetti_faces() 6 | 7 | # Prove the dataset was loaded 8 | # print(faces.data.shape) 9 | 10 | class Person: 11 | def __init__(self, name, photo, date_of_birth): 12 | self.name = name # Each argument is copied into the correspoding instance attribute 13 | self.photo = photo 14 | self.dob = date_of_birth 15 | 16 | aPerson = Person("Adam", faces.images[0], datetime.datetime(1990, 9, 16)) 17 | print(aPerson.name) -------------------------------------------------------------------------------- /Practice/codeSnippets.cpp: -------------------------------------------------------------------------------- 1 | void printUnorderedPairs(int[] arrayA, int[] arrayB){ 2 | for(int i = 0; i< arrayA.length; i++) 3 | for(int j = 0; j< arrayB.length; j++) 4 | for(int k = 0; k<10000; k++) 5 | System.out.println(arrayA[i] + "," + arrayB[j]) 6 | } 7 | -------------------------------------------------------------------------------- /Practice/codeSnippets.cpp~: -------------------------------------------------------------------------------- 1 | void printUnorderedPairs(int[] arrayA, int[] arrayB){ 2 | for(int i = 0; i< arrayA.length; i++) 3 | for(int j = 0; j< arrayB.length; j++) 4 | for(int k = 0; k<10000; k++) 5 | System.out.println(arrayA[i] + "," + arrayB[j]) 6 | } 7 | -------------------------------------------------------------------------------- /Practice/isPrime.java: -------------------------------------------------------------------------------- 1 | boolean isPrime(int n){ 2 | for(int x = 2; x ** x <= n; x++) 3 | if(n%x == 0){ 4 | return false; 5 | } 6 | } 7 | return true; 8 | -------------------------------------------------------------------------------- /Practice/printUnorderedPairs.java: -------------------------------------------------------------------------------- 1 | void printUnorderedPairs(int[] arrayA, int[] arrayB){ 2 | for(int i = 0; i< arrayA.length; i++) 3 | for(int j = 0; j< 4 | } -------------------------------------------------------------------------------- /StarredProblems/CheckIfPrimeNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n; 6 | 7 | cin>>n; 8 | int flag = 0; 9 | if(n == 1 || n == 0) flag = 1; 10 | 11 | for(int i=2; i 2 | #include 3 | using namespace std; 4 | 5 | int binarytodecimal(int num) 6 | { 7 | int sum = 0; 8 | int counter = 0; 9 | while (num > 0) 10 | { 11 | int remainder = num % 10; 12 | sum += (remainder * pow(2, counter)); 13 | num = num / 10; 14 | // cout << sum << " "; 15 | counter++; 16 | } 17 | return sum; 18 | } 19 | int main() 20 | { 21 | int num; 22 | scanf("%d", &num); 23 | printf("%d", binarytodecimal(num)); 24 | } 25 | -------------------------------------------------------------------------------- /StarredProblems/Cognizant/PrintDoubleQuotes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(void) 5 | { 6 | printf("This is a \"buggy\" program"); 7 | return 0; 8 | } -------------------------------------------------------------------------------- /StarredProblems/Cognizant/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/StarredProblems/Cognizant/a.out -------------------------------------------------------------------------------- /StarredProblems/GivenPointerDeleteNode.cpp: -------------------------------------------------------------------------------- 1 | void deleteNode(Node *node_ptr) 2 | { 3 | if(node_ptr == NULL) 4 | { 5 | free(node_ptr); 6 | return; 7 | } 8 | 9 | Node *temp = node_ptr->next; 10 | node_ptr->data = temp->data; 11 | node_ptr->next = temp->next; 12 | free(temp); 13 | } 14 | 15 | // Create a temporary node temp and store the value of node_ptr->next in it; 16 | // then change the value of node_ptr->data and node_ptr->next to temp->data and temp->next 17 | -------------------------------------------------------------------------------- /StarredProblems/TopEarners.sql: -------------------------------------------------------------------------------- 1 | -- We define an employee's total earnings to be their monthly salary * months worked, 2 | -- and the maximum total earnings to be the maximum total earnings for any employee in 3 | -- the Employee table. Write a query to find the maximum total earnings for all employees 4 | -- as well as the total number of employees who have maximum total earnings. 5 | -- Then print these values as 2 space-separated integers. 6 | 7 | SELECT SALARY * MONTHS AS EARNINGS, COUNT(*) FROM EMPLOYEE 8 | GROUP BY 1 9 | ORDER BY EARNINGS DESC LIMIT 1; 10 | 11 | -------------------------------------------------------------------------------- /StarredProblems/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afrozchakure/Competitive-Programming-Solutions/181309a808f692b08a8e77fa63ff878e2ceacf02/StarredProblems/a.out -------------------------------------------------------------------------------- /Worktech/Hard/InsertMinimumToMakePalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int minCharactersToBeInserted (String s) { 3 | StringBuilder rev = new StringBuilder(); 4 | rev.append(s); 5 | rev.reverse(); 6 | s += '#'; 7 | s += rev; 8 | int n = s.length(), palindromeLength = 0; 9 | int[] lps = new int[n]; 10 | lps[0] = 0; 11 | int i = 1; 12 | while(i < n) { 13 | if (s.charAt(i) == s.charAt(palindromeLength)) { 14 | palindromeLength++; 15 | lps[i++] = palindromeLength; 16 | } else { 17 | if (palindromeLength == 0) 18 | lps[i++] = 0; 19 | else 20 | palindromeLength = lps[palindromeLength - 1]; 21 | } 22 | } 23 | int ans = n / 2 - lps[n - 1]; 24 | return ans; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Worktech/Medium/SearchRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | class SearchRotatedSortedArray { 2 | int getElementIndex(int[] A, int target) { 3 | int low = 0, high = A.length - 1; 4 | while(low < high){ 5 | int mid = low + (high - low ) / 2; 6 | if(A[mid] == target) return mid; 7 | 8 | // sorted 9 | if(A[low] <= A[mid]){ 10 | // sorted low, target, mid 11 | if(target >= A[low] && target < A[mid]){ 12 | high = mid - 1; 13 | }else{ // target is beyond mid 14 | low = mid + 1; 15 | } 16 | }else{ 17 | if(target > A[mid] && target <= A[high]){ 18 | low = mid + 1; 19 | }else{ 20 | high = mid -1; 21 | } 22 | } 23 | 24 | } 25 | return A[low] == target ? low : -1; 26 | } 27 | } 28 | --------------------------------------------------------------------------------