├── .gitignore ├── DBMS ├── actor_and_their_movies.sql ├── employee_salary.sql ├── here_in_india.sql ├── highly_paid.sql ├── more_avg_salary_in_dept.sql ├── movie_char.sql ├── neutral_reviewers.sql ├── not_alone.sql ├── short_films.sql ├── special_test.sql ├── sql_question_1.sql ├── sql_question_2.sql ├── sql_question_3.sql ├── sql_u3.sql ├── the_classic.sql ├── the_short_straw.sql └── third_max_salary.sql ├── DistinctNumberCountInWindow.java ├── Practice ├── Arrays │ ├── 2D_Matrix_2.pdf │ ├── A&BPermutation.js │ ├── AddOneToNumber.js │ ├── AddThemUp.java │ ├── AnagramsWithInBuiltSorting.js │ ├── AnagramsWithOurOwnSorting.js │ ├── AntiDiagonals.java │ ├── Arrays_Intro_1.pdf │ ├── AthMagicalNumber.java │ ├── BClosestPointToOrigin.cs │ ├── CheckAP.java │ ├── ColumnSum.java │ ├── CommonElements.java │ ├── CountOfDivisors.java │ ├── CountTotalSetBits.java │ ├── DifferentBitsSumPairWise.java │ ├── DivideIntegerWithoutDivOrMulOrMod.java │ ├── EnumeratingGCD.java │ ├── EquilibriumIndex.java │ ├── FindRangeUsingBinarySearch.java │ ├── FindSumPair.java │ ├── FirstMissingPositiveInteger.js │ ├── FirstRepeatingElement.java │ ├── FizzBuzz.java │ ├── Flip.java │ ├── GCD.java │ ├── GenerateSpiralMatrix.java │ ├── InterestingArray.java │ ├── InversionCountInAnArray.java │ ├── KthPriceBinarySearch.java │ ├── KthPriceUsingSorting.java │ ├── LargestContinuousSequenceZeroSum │ ├── LargestContinuousSequenceZeroSum.java │ ├── LeaderInArray.java │ ├── LittlePonyAndMaximumElement.cs │ ├── LittlePonySubsequence.js │ ├── LongestConsecutiveSequence.java │ ├── LowestAverageSubarray.java │ ├── LuckyNumbers.java │ ├── MatMultiplication.java │ ├── MatrixMedianBinarySearch.java │ ├── MatrixSearch.java │ ├── MaxAbsoluteDifference.js │ ├── MaxAndMinMagic.java │ ├── MaxDistance.js │ ├── MaxSumContiguousArray.java │ ├── MaxSumSubsquareMatrix.java │ ├── MaximumDifference.java │ ├── MaximumNonNegativeSubarraySum.js │ ├── MaximumUnsortedSubarraySol1.java │ ├── MinXORValue.java │ ├── MinimumSwaps.js │ ├── MinimumSwapsII.js │ ├── MultOfPrevAndNext.java │ ├── MultipleLeftRotation.java │ ├── NoOfOpenDoors.java │ ├── NoOfOpenDoorsSolution2.java │ ├── NobleInteger.java │ ├── OperationsInArray.java │ ├── PairSumDivisibleByM.java │ ├── PeakElementUsingBinarySearch.java │ ├── Prefix_Sum_Intro_1.pdf │ ├── Prefix_Sum_Intro_2.pdf │ ├── PrimalPower.java │ ├── PrimeModuloInverse.java │ ├── PrimeSubsequences.java │ ├── PrimeSum.java │ ├── ProductExcludingCurrent.js │ ├── Pubg.java │ ├── Python │ │ ├── IsDictionaryWithRandomLexicographyOrder.py │ │ └── ValidSudoku.py │ ├── QuickSort.java │ ├── RainWaterTrapped.js │ ├── RearrangeArraysUsingModulus.java │ ├── RepeatAndMissingElementUsingXOR.java │ ├── RepeatingAndMissingNumbers.java │ ├── ReplicateSubstrings.js │ ├── ReversePairs.java │ ├── RotateArray.java │ ├── RotateMatrix90Degree.java │ ├── RotatedSortedArraySearch.java │ ├── SearchInBitonicArrayLinearSolution.java │ ├── SearchInBitonicArrayUsingBinarySearch.java │ ├── SearchInSortedRowAndColumns.java │ ├── ShaggyAndDistances.java │ ├── SortedInsertPositionUsingBinarySearch.java │ ├── SpecialInteger.java │ ├── SpecialSubsequence.java │ ├── SqrtOfInteger.java │ ├── SubArrayORSum.js │ ├── SubArrayWith0Sum.java │ ├── SubMatrixSumQueries.java │ ├── SubarrayWithGivenSum.java │ ├── Subarrays_Intro_1.pdf │ ├── SumOfAllSubMatrices.java │ ├── SumOfAllSubarrays.java │ ├── SumOfPrimes.java │ ├── SumofDifference.java │ ├── Teams.js │ ├── TimeToEquality.java │ ├── TransposeMatrix.java │ ├── ValidSudoku.py │ ├── VeryLargePower.java │ ├── XORandUnsetBits.java │ ├── findSubsequence.js │ ├── isDictionary.js │ ├── isPermutation.js │ └── removeOddsfromMatrix.js ├── Backtraking │ ├── AllUniquePermutations.java │ ├── CombinationSum.js │ ├── CombinationSumII.java │ ├── LetterPhone.java │ ├── NQueens.js │ ├── NumberOfSquareFullArrays.java │ ├── Permutations.js │ ├── RatInAMaze.js │ ├── SixLets.js │ ├── Subsets.js │ └── SudokuSolver.cs ├── BinarySearch │ ├── AggressiveCows.java │ └── FoodPacketDistribution.js ├── Bit Manipulation │ ├── C# │ │ ├── CountsetBitsFrom1toN.cs │ │ └── Reverse32BitUnsignedInteger.cs │ ├── Intro_Bits_1.pdf │ ├── Intro_Bits_2.pdf │ ├── Java │ │ ├── AddBinaryStrings.java │ │ ├── CountTotalSetBits.java │ │ ├── DifferentBitSumPairwise.java │ │ ├── DivideInteger.java │ │ ├── FindReverseBitUnsigned.java │ │ ├── InterestingArray.java │ │ ├── LonelyInteger.java │ │ ├── MinimumXORValue.java │ │ ├── NumberofOneBits.java │ │ ├── ReverseBits.java │ │ ├── SingleNumber.java │ │ ├── SingleNumberII.java │ │ ├── SingleNumberIII.java │ │ ├── SmallestXOR.java │ │ └── StrangeEquality.java │ └── Javascript │ │ ├── FindReverseBitUnsigned.js │ │ ├── FindXOR.js │ │ └── NoOf1Bits.js ├── CalculateRunningTime.js ├── Dynamic Programming │ ├── 01Knapsack.js │ ├── CuttinARod.js │ ├── DungeonPrincess.java │ ├── EditDistance.js │ ├── FibonacciNumber.js │ ├── InfiniteKnapsack.js │ ├── LetsParty.js │ ├── LongestCommonSubsequence.js │ ├── MinSumPath.java │ ├── MinimumNumberOfSquares.js │ ├── RegularExpressionMatch(Recursive Approach).js │ ├── Stairs.js │ ├── UniquePathsInAGrid.js │ ├── WaysToDecode.java │ └── WaysToEnjoyDay.java ├── Graphs │ ├── CheckBipartiteGraph.cs │ ├── ColoringACycleGraph.js │ ├── CycleInDirectedGraph.java │ ├── CycleInUndirectedGraph.js │ ├── Dijkstra.java │ ├── FirstDepthFirstSearch.js │ ├── NumberOfIslands.js │ ├── PathInDirectedGraph.js │ ├── RottenOranges.js │ └── TopologicalSorting.java ├── Greedy Alogirthm │ ├── AnotherCoinProblem.java │ ├── AssignMiceToHole.js │ ├── DistrubuteCandy.js │ ├── FinishMaximumJobs.js │ ├── FreeCars.js │ └── TheShipCompany.java ├── Hashing │ ├── .prettierrc │ ├── CheckPalindrome.js │ ├── ColorfulNumber.js │ ├── CommonElements.js │ ├── CountRectangle.js │ ├── CountRightTriangles.js │ ├── DistinctNumberOfWindows.js │ ├── LargestContinuousSequenceZeroSum.js │ ├── LongestConsecutiveSequence.js │ ├── MinimumDistance.js │ ├── PointsOnSameLine.js │ ├── ReplicateSubstring.js │ ├── SortArrayInGivenOrder.js │ └── SubArrayWithZeroSum.js ├── Heap │ ├── .prettierrc │ ├── AthLargestElement.js │ ├── ConnectRopes.js │ ├── KPlacesApart.js │ ├── MagicianAndChocolates.js │ ├── MaximumSumArrayAfterBNegations.js │ ├── MergeKSortedLinkedList.java │ ├── ProductOf3.js │ └── RunningMedian.js ├── LinkedList │ ├── AddTwoNumbersAsList.java │ ├── CopyLinkedListWithRandomPointer.java │ ├── DeepCopyList.js │ ├── DeleteMiddleNodeOfLinkedList.js │ ├── DesignLinkedList.js │ ├── KreverseLinkedList.js │ ├── LRUCache.js │ ├── LinkedListTestEnv.js │ ├── ListCycles.js │ ├── MergeKSortedLinkedListUsingPriorityQueue.java │ ├── MergeKSortedListsWithoutPriorityQueue.java │ ├── MergeKSortedListsWithoutPriorityQueueUsingMid.java │ ├── MergeTwoSortedList.java │ ├── PalindromeList.java │ ├── RemoveDuplicatesFromSortedList.java │ ├── RemoveLoopFromLinkedList.js │ ├── RemoveNthNodeFromEnd.java │ ├── ReorderList.js │ ├── ReverseLinkedList.js │ ├── ReverseLinkedListII.js │ ├── SortLinkedList.java │ └── Test.js ├── Maths │ ├── AandBModulo.java │ ├── AllGCDPairs.js │ ├── DistinctPrime.js │ ├── DivisorGame.js │ ├── ExcelColumnToNumber.java │ ├── LargestCoPrimeDivisor.js │ ├── MagicNumberBase2.java │ ├── MagicNumberBase3.java │ ├── ModString.java │ └── SortedPermutationRank.js ├── Patterns.js ├── PracticeProblems3rdOct │ └── RemoveDuplicates.java ├── ProblemSolving1stClass │ ├── Javascript │ │ ├── AtLeastTwoGreaterElements.js │ │ ├── OddEvenDifference.js │ │ ├── PatternPrinting.js │ │ └── StrictlySmallerAndGreater.js │ └── Lecture 1.pdf ├── Queues │ ├── FirstNonRepeatingCharacter.js │ ├── NIntegersContaining123.js │ ├── PerfectNumbers.js │ ├── SlidingWindowMaximum.js │ ├── SumOfMinOrMax.js │ └── TaskScheduler.js ├── RandomPractice │ └── HCF.java ├── Recursion │ ├── CheckPalindrome.py │ ├── FindFactorial.py │ ├── FindFibonacci.py │ ├── GrayCode.java │ ├── GrayCode.py │ ├── ImplementingPowerFunction.java │ ├── IsMagic.java │ ├── K Occurences.py │ ├── KthSymbol.py │ ├── OptimizedPowerFunction.java │ ├── PowerFunction.java │ ├── PrintReverseString.py │ ├── SequenceProblem.java │ ├── SumOfDigits.java │ └── Test.java ├── Revision2ndOctober │ ├── .cph │ │ └── .CheckForAdjacentArray.java_266f6232751edec91a589a18a092fb2e.prob │ ├── AdjacendDifferenceArray.java │ ├── BinarySum.java │ ├── CheckForAdjacentArray.java │ ├── FindDuplicates.java │ ├── MaxEvenMinOddDiff.java │ ├── NumberOfBits.java │ ├── Pattern1.java │ ├── StrictlySmallerAndGreater.java │ └── TwoGreaterElement.java ├── RockPaperScissor.js ├── Stack │ ├── BalancedParanthesis.js │ ├── DivisibilityTest.js │ ├── DoubleCharacterTrouble.java │ ├── DoubleCharacterTrouble.js │ ├── EvaluateExpression.js │ ├── InfixToPostFix.java │ ├── LargestRectangleInHistogram.js │ ├── MAXandMIN.js │ ├── MaxFrequencyStack.java │ ├── MinStack.java │ ├── NearestSmallestElement.js │ ├── PassingGame.java │ ├── SimplifyDirectoryPath.js │ ├── SortStackUsingAnotherStack.java │ └── Stacks2_02_02_22.pdf ├── String Pattern Matching │ ├── CyclicPermutation.js │ └── PeriodOfAString.js ├── Strings │ ├── ColorFulNumber.java │ ├── ConcatenatingNumbers.java │ ├── ConvertToLower.py │ ├── CountUniqueXORPairs.py │ ├── IsAlpha.py │ ├── IsPalindromeByRearranging.py │ ├── LongestPalindrome.py │ ├── ReverseSingleString.py │ └── ReverseString.py ├── Test.js ├── Trees │ ├── BSTNodeInARange.js │ ├── BalancedBinaryTree.cs │ ├── BinaryTreeFromInorderAndPostOrder.js │ ├── BinaryTreeFromInorderAndPreorder.js │ ├── BoundaryTraversalOfBinaryTree.java │ ├── CheckForBSTWithOneChild.js │ ├── CommonNodesInTwoBST.js │ ├── DeserializeBinaryTree.js │ ├── DiameterOfATree.js │ ├── DistanceBetweenNodesInBST.js │ ├── EqualTreePartition.js │ ├── FloorAndCeilInBST.js │ ├── InvertBinaryTree.cs │ ├── KthSmallestElementInBst.js │ ├── LeastCommonAncestor.js │ ├── LeftViewOfBinaryTree.js │ ├── LevelOrder.js │ ├── MaxPathSum.java │ ├── MaxValue.js │ ├── NextPointerBinaryTree.js │ ├── NodeDistanceCInBinaryTree.js │ ├── NodesCount.js │ ├── NodesSum.js │ ├── OddAndEvenLevel.js │ ├── PathSum.js │ ├── PostOrderTraversal.js │ ├── RecoverBinarySearchTree.js │ ├── RegularExpressionMatching.cs │ ├── ReverseLevelOrder.cs │ ├── RightViewOfBinaryTree.js │ ├── SerializeBinaryTree.js │ ├── SortedArrayToBST.js │ ├── SymmetricBinaryTree.cs │ ├── TreeHeight.js │ ├── TreeNode.java │ ├── Trees1_09_Feb_2022.pdf │ ├── ValidBinarySearchTree.js │ ├── VerticalOrderTraversal.js │ └── ZigZagLevelOrderTraversal.cs ├── Trie │ ├── Program.cs │ ├── Trie.js │ ├── backend-node │ │ ├── .prettierrc │ │ ├── Trie.js │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── store.json │ │ └── trieController.js │ └── frontend │ │ ├── .browserslistrc │ │ ├── .editorconfig │ │ ├── .gitignore │ │ ├── .prettierrc │ │ ├── README.md │ │ ├── angular.json │ │ ├── karma.conf.js │ │ ├── package-lock.json │ │ ├── package.json │ │ ├── src │ │ ├── app │ │ │ ├── app-routing.module.ts │ │ │ ├── app.component.css │ │ │ ├── app.component.html │ │ │ ├── app.component.spec.ts │ │ │ ├── app.component.ts │ │ │ ├── app.module.ts │ │ │ ├── components │ │ │ │ ├── auto-complete │ │ │ │ │ ├── auto-complete.component.css │ │ │ │ │ ├── auto-complete.component.html │ │ │ │ │ ├── auto-complete.component.spec.ts │ │ │ │ │ └── auto-complete.component.ts │ │ │ │ └── navbar │ │ │ │ │ ├── navbar.component.css │ │ │ │ │ ├── navbar.component.html │ │ │ │ │ ├── navbar.component.spec.ts │ │ │ │ │ └── navbar.component.ts │ │ │ └── services │ │ │ │ ├── wikipedia.service.spec.ts │ │ │ │ └── wikipedia.service.ts │ │ ├── assets │ │ │ └── .gitkeep │ │ ├── environments │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── main.ts │ │ ├── polyfills.ts │ │ ├── styles.css │ │ └── test.ts │ │ ├── tsconfig.app.json │ │ ├── tsconfig.json │ │ └── tsconfig.spec.json ├── TrieDSA │ ├── AutoComplete.js │ ├── ContactFinder.js │ ├── MaximumXOR.js │ ├── MaximumXORSubarray.js │ ├── ModifiedSearch.js │ ├── ShortestUniquePrefix.js │ └── SpellingChecker.js ├── TwoPointers │ ├── AnotherCountRectangle.js │ ├── ArrayThreePointers.java │ ├── ContainerWithMostWater.js │ ├── MinimizeTheAbsoluteDifference.java │ ├── PairWithGivenSumII.js │ ├── PairsWithDifference.js │ ├── PairsWithDifferenceSolution2.js │ ├── PairsWithSum.js │ ├── SortStringarraywithoutinbuiltfunctions.js │ ├── SubarrayWithGivenSum.js │ ├── SumZero.js │ └── ThreeSum.java └── leetcode │ ├── 15.3-sum.java │ ├── 1bit2bit.js │ ├── 9.palindrome-number.java │ ├── BuildArrayFromPermutation.js │ ├── ContainerWithMoreWater.java │ ├── DecodeXORedArray.java │ ├── DecompressRunLengthEncodedList.java │ ├── DifferenceBetweenProductandSum.java │ ├── FindTargetIndicesAfterSorting.java │ ├── RomanToInteger.java │ ├── ShuffleString.java │ ├── countofSmallNumberThanCurrent.java │ └── goodpair.java ├── README.md └── Revision ├── Arrays ├── AllocateBooks.java ├── ArrayWithConsecutiveElement.java ├── BeggarsOutsideTemple.cs ├── ClosestMinMax.cs ├── CopyTheArray.java ├── CountDuplicates.java ├── EvenOddElements.java ├── FizzBuzz.java ├── GoodPairBruteForce.java ├── GoodPairUsingHashSet.java ├── LeadersInAnArray.java ├── LowerTriangularMatrix.java ├── MAXMIN.java ├── Main.java ├── MaxAndMinOfAnArray.java ├── MaxMinWithMinimumComparison.java ├── MaxMod.java ├── MaxNonNegativeSubarray.cs ├── MaxSumContiguousArray.java ├── MultipleLeftRotationsOfArray.java ├── MultiplicationOfPreviousAndNext.java ├── NobleInteger.java ├── PrimalPower.java ├── ReverseTheArray.java ├── RockPaperScissor.java ├── RotationGame.java ├── RotationGameReversingTheArray.java ├── SubArrayWithLeastAverage.java ├── SumOfAllSubArrays.cs └── TimeToEquality.java ├── Backtracking ├── Main.java ├── RatInAMaze.java ├── Sudoku.java └── TestCases │ ├── SudokuTest.java │ └── Test.java ├── BitManipulation ├── AddBinaryStrings.java ├── CountTotalSetBits.java ├── DifferentBitSumPairwise.java ├── DivideInteger.java ├── FindReverseBitUnsigned.java ├── InterestingArray.java ├── LonelyInteger.java ├── MinimumXORValue.java ├── NumberofOneBits.java ├── ReverseBits.java ├── SingleNumber.java ├── SingleNumberII.java ├── SingleNumberIII.java ├── SmallestXOR.java └── StrangeEquality.java ├── Dynamic Programming ├── FibonacciSeries.java ├── LetsParty.java ├── MaxSumWithoutAdjacentElements.java ├── MinimumNumberOfSquare.java └── Stairs.java ├── Graphs ├── CheckBipartiteGraph.java ├── ConstructRoads.java ├── FirstDepthFirstSearch.java └── PathInDirectedGraph.java ├── Greedy ├── DistributeCandies.java └── FinishMaximumJobs.java ├── LeetCode Random Problems ├── ConvertSortedArrayToBinarySearchTree.cs ├── Factorial_Trailing_Zeroes.cs ├── IntersectionOfTwoArrays.js ├── LongestCommonPrefix.js ├── Move_Zeroes.cs ├── Pairs_of_Songs_With_Total_Durations_Divisible_by_60.cs ├── RegularExpressionMatching.js ├── SlidingWindowMaximum.cs ├── ValidParenthesis.cs └── ValidParenthesis.js ├── LinkedList ├── AddTwoNumbersAsList.java ├── CopyLinkedListWithRandomPointer.java ├── DeleteMiddleNodeOfLinkedList.java ├── FlattenALinkedListUsingMerging.java ├── FlattenALinkedListUsingPriorityQueue.java ├── KReverseLinkedlist.java ├── ListCycle.java ├── MergeKSortedLinkedList.java ├── MergeTwoSortedList.java ├── MiddleElementOfLinkedlist.java ├── PalindromeList.java ├── RemoveLoopFromLinkedlist.java ├── ReorderLinkedList.java ├── ReverseALinkedList.java ├── ReverseLinkedListII.java └── SortLinkedList.java ├── Recursion ├── AnotherSequenceProblem.java ├── EvaluateExpression.java ├── FindFactorial.java ├── FindFibonacciII.java ├── IsMagic.java ├── PowerFunction.java ├── ReverseString.java └── SumOfDigits.java ├── Sorting ├── ArrayWithConsecutiveElements.java ├── KthSmallestElement.java ├── PowerOfTwo.java └── Test.java └── Trees └── LevelOrderTraversal.java /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /DBMS/actor_and_their_movies.sql: -------------------------------------------------------------------------------- 1 | Select movie_title from movies where movie_id IN (Select mc.movie_id from 2 | (Select COUNT(movie_id) as cnt, actor_id from movies_cast group by actor_id) as c 3 | JOIN movies_cast mc 4 | ON mc.actor_id = c.actor_id 5 | WHERE c.cnt > 1); -------------------------------------------------------------------------------- /DBMS/employee_salary.sql: -------------------------------------------------------------------------------- 1 | select * from employeesalary where dept = 'HR' AND salary < 500 OR salary > 1000; -------------------------------------------------------------------------------- /DBMS/here_in_india.sql: -------------------------------------------------------------------------------- 1 | Select e.employee_name, s.salary, d.department_name from employees e 2 | JOIN salaries s 3 | ON s.employee_id = e.employee_id 4 | JOIN departments d 5 | ON s.department_id = d.department_id 6 | Where s.salary > 10000 7 | AND department_location = 'India'; -------------------------------------------------------------------------------- /DBMS/highly_paid.sql: -------------------------------------------------------------------------------- 1 | Select employee_name from employees where employee_id IN (Select employee_id from (Select * from salaries order by salary desc) t group by department_id) order by employee_id; -------------------------------------------------------------------------------- /DBMS/more_avg_salary_in_dept.sql: -------------------------------------------------------------------------------- 1 | SELECT e.ename, e.sal, e.deptno from 2 | (SELECT deptno, AVG(sal) as avgs from emp group by deptno) as t 3 | JOIN emp e 4 | ON e.deptno = t.deptno 5 | WHERE sal > avgs; -------------------------------------------------------------------------------- /DBMS/movie_char.sql: -------------------------------------------------------------------------------- 1 | Select CONCAT(d.director_first_name,d.director_last_name) as director_name, m.movie_title from 2 | 3 | 4 | (Select * from movies_directors where movie_id IN(Select movie_id from movies_cast where role = 'SeanMaguire')) as cte 5 | JOIN movies m 6 | ON cte.movie_id = m.movie_id 7 | JOIN directors d 8 | ON d.director_id = cte.director_id; 9 | -------------------------------------------------------------------------------- /DBMS/neutral_reviewers.sql: -------------------------------------------------------------------------------- 1 | Select reviewer_name from reviewers where reviewer_id IN (Select reviewer_id from ratings where reviewer_stars is NULL); -------------------------------------------------------------------------------- /DBMS/not_alone.sql: -------------------------------------------------------------------------------- 1 | Select e.employee_name from employees e JOIN 2 | salaries s 3 | ON s.employee_id = e.employee_id 4 | where department_id IN (Select department_id from salaries where employee_id IN (Select employee_id from employees where employee_name like '%q%')) -------------------------------------------------------------------------------- /DBMS/short_films.sql: -------------------------------------------------------------------------------- 1 | select m.movie_title, m.movie_year, CONCAT(d.director_first_name,d.director_last_name) as director_name, CONCAT(a.actor_first_name,a.actor_last_name) as actor_name, mc.role 2 | from movies m join 3 | movies_directors md 4 | ON md.movie_id = m.movie_id 5 | join directors d 6 | ON d.director_id = md.director_id 7 | join movies_cast mc 8 | ON mc.movie_id = m.movie_id 9 | join actors a 10 | ON a.actor_id = mc.actor_id 11 | where m.movie_time < 100; -------------------------------------------------------------------------------- /DBMS/special_test.sql: -------------------------------------------------------------------------------- 1 | Select s.student_name, t.test_score, d.department_name from 2 | (Select * from test_stats where test_id IN (Select test_id from tests where test_type = 'hiring')) as t 3 | JOIN students s 4 | ON s.student_id = t.student_id 5 | JOIN departments d 6 | ON d.test_id = t.test_id 7 | Where t.test_score >= 90; -------------------------------------------------------------------------------- /DBMS/sql_question_1.sql: -------------------------------------------------------------------------------- 1 | Select d.deptname as department_name, ROUND(AVG(e.salary),2) as average_salary from employee e 2 | JOIN department d 3 | ON d.deptid = e.deptid 4 | group by e.deptid; -------------------------------------------------------------------------------- /DBMS/sql_question_2.sql: -------------------------------------------------------------------------------- 1 | Select e.empname as oldest_employee_name, d.deptname as department_name from 2 | 3 | ((Select deptid, MIN(dob) as dateOfBirth from employee group by deptid) as t 4 | JOIN employee e 5 | ON e.deptid = t.deptid AND e.dob = t.dateOfBirth 6 | JOIN department d 7 | ON d.deptid = t.deptid); -------------------------------------------------------------------------------- /DBMS/sql_question_3.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM employee; -------------------------------------------------------------------------------- /DBMS/sql_u3.sql: -------------------------------------------------------------------------------- 1 | Select Name from q3_employees where PanId = (Select PanId from q3_salaries order by Salary desc LIMIT 1); -------------------------------------------------------------------------------- /DBMS/the_classic.sql: -------------------------------------------------------------------------------- 1 | Select movie_name from movies where movie_id IN 2 | 3 | (Select m.movie_id from (Select SUM(times_played) as tp, movie_id, AVG(rating) as r from statistics group by movie_id) as t 4 | JOIN movies m 5 | ON m.movie_id = t.movie_id 6 | Where t.tp > 1000 and t.r > 3) 7 | 8 | and release_year < 2000; 9 | -------------------------------------------------------------------------------- /DBMS/the_short_straw.sql: -------------------------------------------------------------------------------- 1 | Select d.department_location, s.salary as min_sal from departments d 2 | JOIN salaries s 3 | ON s.department_id = d.department_id 4 | HAVING s.salary = (Select MIN(salary) from salaries); -------------------------------------------------------------------------------- /DBMS/third_max_salary.sql: -------------------------------------------------------------------------------- 1 | Select SAL as 'MAX(Sal)' from emp LIMIT 1 OFFSET 3; -------------------------------------------------------------------------------- /Practice/Arrays/2D_Matrix_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Arrays/2D_Matrix_2.pdf -------------------------------------------------------------------------------- /Practice/Arrays/AddOneToNumber.js: -------------------------------------------------------------------------------- 1 | A = [ 0, 6, 0, 6, 4, 8, 8, 1] 2 | output = [] 3 | let val = Math.floor((A[A.length - 1] + 1)%10) 4 | let carry = Math.floor((A[A.length - 1]+1)/10) 5 | let s = val.toString() 6 | for(let i=A.length-2;i>=0;i--){ 7 | curr_val = Math.floor((A[i] + carry)%10) 8 | carry = Math.floor((A[i] + carry)/10) 9 | s = curr_val.toString() + s 10 | } 11 | if(carry == 1){ 12 | s = carry.toString() + s 13 | } 14 | 15 | for(let j=0;j output = AddThemUp.solve(A); 6 | System.out.println(output.toString()); 7 | 8 | } 9 | public static ArrayList solve(int A) { 10 | ArrayList output = new ArrayList(); 11 | 12 | for(int i=1;i 0){ 16 | digitSum += numValue%10; 17 | numValue = numValue/10; 18 | } 19 | 20 | if((digitSum + i) == A){ 21 | output.add(i); 22 | } 23 | } 24 | if(output.size() == 0){ 25 | output.add(-1); 26 | }; 27 | return output; 28 | } 29 | } -------------------------------------------------------------------------------- /Practice/Arrays/AnagramsWithInBuiltSorting.js: -------------------------------------------------------------------------------- 1 | A = [cat, dog, god, tca] 2 | console.log(findAnagrams(A)) 3 | function findAnagrams(A){ 4 | 5 | let Output = [] 6 | let HashMap = new Map() 7 | let Array_index = 0 8 | for(let i=0;i 0) { 8 | pow++; 9 | X = X >> 1; 10 | } 11 | int val = (int) Math.pow(2, pow); 12 | long total_bits = (long) (val / 2) * pow + (A - val + 1) + solve(A - val); 13 | 14 | return (int) (total_bits % 1000000007); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Practice/Arrays/DifferentBitsSumPairWise.java: -------------------------------------------------------------------------------- 1 | public class DifferentBitsSumPairWise { 2 | public int cntBits(int[] A) { 3 | 4 | long ans = 0; 5 | int mod = 1000000007; 6 | for (int i = 0; i < 32; i++) { 7 | long count = 0; 8 | for (int j = 0; j < A.length; j++) { 9 | if ((A[j] & (1 << i)) >= 1) { 10 | count++; 11 | } 12 | } 13 | ans += 2 * count * (A.length - count); 14 | ans = ans % mod; 15 | } 16 | 17 | return (int) ans; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Practice/Arrays/DivideIntegerWithoutDivOrMulOrMod.java: -------------------------------------------------------------------------------- 1 | public class DivideIntegerWithoutDivOrMulOrMod { 2 | public int divide(int A, int B) { 3 | 4 | long absA = Math.abs((long) A); 5 | long absB = Math.abs((long) B); 6 | long ans = 0; 7 | for (int i = 31; i >= 0; i--) { 8 | int val = (int) Math.pow(2, i); 9 | if (absB * val <= absA) { 10 | ans += val; 11 | absA -= absB * val; 12 | } 13 | } 14 | 15 | if (A < 0) { 16 | ans *= -1; 17 | } 18 | if (B < 0) { 19 | ans *= -1; 20 | } 21 | 22 | if (ans > Integer.MAX_VALUE) 23 | return Integer.MAX_VALUE; 24 | return (int) ans; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Practice/Arrays/EnumeratingGCD.java: -------------------------------------------------------------------------------- 1 | public class EnumeratingGCD { 2 | public String solve(String A, String B) { 3 | if (A.equals(B)) 4 | return A; 5 | return "1"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Practice/Arrays/EquilibriumIndex.java: -------------------------------------------------------------------------------- 1 | 2 | class EquilibriumIndex { 3 | 4 | public static int EqulibriumInArray() { 5 | int[] A = {1, 2, 3}; 6 | int total_sum = 0; 7 | for (int i : A) { 8 | total_sum += i; 9 | } 10 | 11 | int left_sum = 0; 12 | int right_sum; 13 | 14 | for (int j = 0; j < A.length; j++) { 15 | left_sum += A[j]; 16 | right_sum = total_sum - left_sum + A[j]; 17 | 18 | if (left_sum == right_sum) { 19 | return j; 20 | } 21 | } 22 | 23 | return -1; 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /Practice/Arrays/FindSumPair.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class FindSumPair { 4 | public static int FindSum(ArrayList A, int B) { 5 | for (int i = 0; i < A.size(); i++) { 6 | for (int j = i + 1; j < A.size(); j++) { 7 | if (A.get(i) + A.get(j) == B) { 8 | return 1; 9 | } 10 | } 11 | } 12 | return 0; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Practice/Arrays/FirstMissingPositiveInteger.js: -------------------------------------------------------------------------------- 1 | A = [2, 3, 1, 2] 2 | 3 | let N = A.length 4 | console.log(MissingFirstInteger(A,N)) 5 | function MissingFirstInteger(A,N){ 6 | 7 | for(let i=0;i N) || (val < 1) || A[val-1] == val){ 12 | isSwap = false 13 | } 14 | else{ 15 | A[i] = A[val - 1] 16 | A[val - 1] = val 17 | } 18 | } 19 | } 20 | 21 | for(let i=0;i hm = new HashMap(); 6 | 7 | for (int i = 0; i < A.length; i++) { 8 | int val = hm.getOrDefault(A[i], 0); 9 | 10 | hm.put(A[i], val + 1); 11 | } 12 | 13 | for (int j = 0; j < A.length; j++) { 14 | if (hm.containsKey(A[j])) { 15 | if (hm.get(A[j]) > 1) 16 | return A[j]; 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | } -------------------------------------------------------------------------------- /Practice/Arrays/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class FizzBuzz { 4 | 5 | public static ArrayList FizzBuzzArray(int A) { 6 | ArrayList arr = new ArrayList<>(); 7 | for (int i = 1; i <= A; i++) { 8 | if (i % 3 == 0 && i % 5 == 0) { 9 | arr.add("FizzBuzz"); 10 | } else if (i % 3 == 0) { 11 | arr.add("Fizz"); 12 | } else if (i % 5 == 0) { 13 | arr.add("Buzz"); 14 | } else { 15 | arr.add(Integer.toString(i)); 16 | } 17 | } 18 | return arr; 19 | } 20 | } -------------------------------------------------------------------------------- /Practice/Arrays/Flip.java: -------------------------------------------------------------------------------- 1 | public class Flip { 2 | public int[] flip(String A) { 3 | int curr_sum = 0; 4 | int max_sum = 0; 5 | int L = 1; 6 | int R = 1; 7 | int curr_left = 1; 8 | 9 | for (int i = 0; i < A.length(); i++) { 10 | if (A.charAt(i) == '0') { 11 | curr_sum += 1; 12 | } else { 13 | curr_sum -= 1; 14 | } 15 | if (curr_sum < 0) { 16 | curr_left = i + 2; 17 | 18 | curr_sum = 0; 19 | } 20 | 21 | if (max_sum < curr_sum) { 22 | max_sum = curr_sum; 23 | R = i + 1; 24 | L = curr_left; 25 | } 26 | } 27 | 28 | if (max_sum == 0) 29 | return new int[] {}; 30 | return new int[] { L, R }; 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Practice/Arrays/GCD.java: -------------------------------------------------------------------------------- 1 | public class GCD { 2 | public int GetGCD(int A, int B) { 3 | int min = Math.min(A, B); 4 | int max = Math.max(A, B); 5 | while (min > 0 && max > 0) { 6 | max = max % min; 7 | int temp = min; 8 | min = max; 9 | max = temp; 10 | } 11 | 12 | return max; 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Practice/Arrays/InterestingArray.java: -------------------------------------------------------------------------------- 1 | public class InterestingArray { 2 | public String solve(int[] A) { 3 | if (A.length == 1) { 4 | if (A[0] == 0) 5 | return "Yes"; 6 | return "No"; 7 | } 8 | int xor = 0; 9 | for (int i = 0; i < A.length; i++) { 10 | xor ^= A[i]; 11 | } 12 | 13 | if (xor % 2 == 0) 14 | return "Yes"; 15 | return "No"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Practice/Arrays/KthPriceBinarySearch.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class KthPriceBinarySearch { 4 | public int kthsmallest(final int[] A, int B) { 5 | int min = Integer.MAX_VALUE; 6 | int max = Integer.MIN_VALUE; 7 | 8 | for (int i = 0; i < A.length; i++) { 9 | if (A[i] < min) 10 | min = A[i]; 11 | if (A[i] > max) 12 | max = A[i]; 13 | } 14 | 15 | int mid = (min + max) / 2; 16 | 17 | while (min <= max) { 18 | int count = 0; 19 | for (int i = 0; i < A.length; i++) { 20 | if (A[i] <= mid) { 21 | count++; 22 | } 23 | } 24 | 25 | if (count < B) { 26 | min = mid + 1; 27 | } else 28 | max = mid - 1; 29 | mid = (min + max) / 2; 30 | } 31 | 32 | return min; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Practice/Arrays/KthPriceUsingSorting.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class KthPriceUsingSorting { 4 | public int kthsmallest(final int[] A, int B) { 5 | int[] X = new int[A.length]; 6 | 7 | for (int i = 0; i < A.length; i++) { 8 | X[i] = A[i]; 9 | } 10 | 11 | Arrays.sort(X); 12 | 13 | return X[B - 1]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Practice/Arrays/LeaderInArray.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class LeaderInArray { 4 | public ArrayList solve(ArrayList A) { 5 | ArrayList output = new ArrayList<>(); 6 | for (int i = 0; i < A.size(); i++) { 7 | 8 | boolean isLeader = true; 9 | for (int j = i; j < A.size(); j++) { 10 | 11 | if (A.get(j) > A.get(i)) { 12 | isLeader = false; 13 | break; 14 | } 15 | } 16 | if (isLeader) { 17 | output.add(A.get(i)); 18 | } 19 | } 20 | return output; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Practice/Arrays/LittlePonyAndMaximumElement.cs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int solve(List A, int B) { 3 | A.Sort(); 4 | 5 | int index = -1; 6 | for(int i=0;i= 0) { 7 | if (B == A[i][j]) 8 | return 1; 9 | else if (B < A[i][j]) 10 | j--; 11 | else 12 | i++; 13 | } 14 | 15 | return 0; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Practice/Arrays/MaxAbsoluteDifference.js: -------------------------------------------------------------------------------- 1 | A = [1, 3, -1] 2 | 3 | 4 | let sum1 = 0 5 | let sum2 = 0 6 | let min = A[0] 7 | let max = A[0] 8 | for(let i=1;i A) { 6 | if (A.size() == 0) { 7 | return 0; 8 | } 9 | 10 | int max_so_far = A.get(0); 11 | int max_ending_here = A.get(0); 12 | 13 | for (int i = 1; i < A.size(); i++) { 14 | 15 | max_ending_here += A.get(i); 16 | 17 | if (max_ending_here < A.get(i)) { 18 | max_ending_here = A.get(i); 19 | } 20 | 21 | if (max_so_far < max_ending_here) { 22 | max_so_far = max_ending_here; 23 | } 24 | 25 | } 26 | return max_so_far; 27 | } 28 | } -------------------------------------------------------------------------------- /Practice/Arrays/MaximumDifference.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class MaximumDifference { 4 | public int solve(int[] A, int B) { 5 | Arrays.sort(A); 6 | 7 | int min_s1 = 0, min_s2 = 0, max_s1 = 0, max_s2 = 0, total_sum = 0; 8 | 9 | for (int x : A) { 10 | total_sum += x; 11 | } 12 | 13 | for (int i = 0; i < B; i++) { 14 | min_s1 += A[i]; 15 | } 16 | 17 | min_s2 = total_sum - min_s1; 18 | 19 | for (int j = A.length - 1; j > A.length - 1 - B; j--) { 20 | max_s1 += A[j]; 21 | } 22 | 23 | max_s2 = total_sum - max_s1; 24 | return Math.max(Math.abs(max_s1 - max_s2), Math.abs(min_s1 - min_s2)); 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Practice/Arrays/MaximumUnsortedSubarraySol1.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class MaximumUnsortedSubarraySol1 { 4 | public int[] subUnsort(int[] A) { 5 | 6 | int[] B = new int[A.length]; 7 | for (int i = 0; i < A.length; i++) { 8 | B[i] = A[i]; 9 | } 10 | Arrays.sort(B); 11 | int[] output = new int[2]; 12 | boolean isEqual = true; 13 | for (int i = 0; i < A.length; i++) { 14 | if (A[i] != B[i]) { 15 | output[0] = i; 16 | isEqual = false; 17 | break; 18 | } 19 | } 20 | 21 | for (int i = 0; i < A.length; i++) { 22 | if (A[i] != B[i] && output[0] != i) { 23 | output[1] = i; 24 | } 25 | } 26 | 27 | if (isEqual) 28 | return new int[] { -1 }; 29 | return output; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Practice/Arrays/MinXORValue.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class MinXORValue { 4 | public int findMinXor(int[] A) { 5 | Arrays.sort(A); 6 | if (A.length == 1) { 7 | return A[0]; 8 | } 9 | int min = A[0] ^ A[1]; 10 | for (int i = 2; i < A.length; i++) { 11 | int xor = A[i] ^ A[i - 1]; 12 | if (xor < min) 13 | min = xor; 14 | } 15 | 16 | return min; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Practice/Arrays/MinimumSwaps.js: -------------------------------------------------------------------------------- 1 | function MinimumSwaps(A, B) { 2 | let LessOrEqualNumbers = 0; 3 | 4 | for (let i = 0; i < A.length; i++) { 5 | if (A[i] <= B) LessOrEqualNumbers++; 6 | } 7 | let badNumbers = 0; 8 | let goodNumbers = 0; 9 | 10 | for (let i = 0; i < LessOrEqualNumbers; i++) { 11 | if (A[i] <= B) goodNumbers++; 12 | else badNumbers++; 13 | } 14 | let ans = badNumbers; 15 | 16 | for (let i = LessOrEqualNumbers; i < A.length; i++) { 17 | if (A[i] <= B) goodNumbers++; 18 | else badNumbers++; 19 | if (A[i - LessOrEqualNumbers] <= B) goodNumbers--; 20 | else badNumbers--; 21 | 22 | ans = Math.min(ans, badNumbers); 23 | } 24 | 25 | return ans; 26 | } 27 | 28 | A = [1, 12, 10, 3, 14, 10, 5]; 29 | B = 8; 30 | 31 | console.log(MinimumSwaps(A, B)); 32 | -------------------------------------------------------------------------------- /Practice/Arrays/MinimumSwapsII.js: -------------------------------------------------------------------------------- 1 | function MinimumSwapsII(A) { 2 | let count = 0; 3 | for (let i = 0; i < A.length; i++) { 4 | while (A[i] != i) { 5 | count++; 6 | let temp = A[i]; 7 | A[i] = A[A[i]]; 8 | A[temp] = temp; 9 | } 10 | } 11 | console.log(A); 12 | return count; 13 | } 14 | 15 | let A = [2, 0, 1, 3]; 16 | console.log(MinimumSwapsII(A)); 17 | -------------------------------------------------------------------------------- /Practice/Arrays/MultOfPrevAndNext.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class MultOfPrevAndNext { 4 | public ArrayList solve(ArrayList A) { 5 | 6 | ArrayList output = new ArrayList<>(); 7 | 8 | if (A.size() == 1) { 9 | output.add(A.get(0)); 10 | return output; 11 | } 12 | for (int i = 0; i < A.size(); i++) { 13 | if (i == 0) { 14 | output.add(A.get(i) * A.get(i + 1)); 15 | } else if (i == A.size() - 1) { 16 | output.add(A.get(i) * A.get(i - 1)); 17 | 18 | } else { 19 | output.add(A.get(i - 1) * A.get(i + 1)); 20 | } 21 | 22 | } 23 | return output; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Practice/Arrays/NoOfOpenDoors.java: -------------------------------------------------------------------------------- 1 | public class NoOfOpenDoors { 2 | public int solve(int A) { 3 | 4 | return GetSqrt(0, A, A); 5 | 6 | } 7 | 8 | public int GetSqrt(long low, long high, int N) { 9 | 10 | if (low <= high) { 11 | 12 | long mid = (low + high) / 2; 13 | long val = mid * mid; 14 | long val1 = (mid + 1) * (mid + 1); 15 | 16 | if ((val <= N) 17 | && (val1 > N)) { 18 | return (int) mid; 19 | } 20 | 21 | else if (val < N) { 22 | return GetSqrt(mid + 1, high, N); 23 | } else { 24 | return GetSqrt(low, mid - 1, N); 25 | } 26 | } 27 | return (int) low; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Practice/Arrays/NoOfOpenDoorsSolution2.java: -------------------------------------------------------------------------------- 1 | public class NoOfOpenDoorsSolution2 { 2 | public int solve(int A) { 3 | return (int) Math.sqrt(A); 4 | 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Practice/Arrays/NobleInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | 4 | public class NobleInteger { 5 | public int solve(ArrayList A) { 6 | Collections.sort(A); 7 | int n = A.size() - 1; 8 | for (int i = 0; i <= n; i++) { 9 | int val = A.get(i); 10 | if (A.get(n) == 0) { 11 | return 1; 12 | } 13 | if (val == n - i) { 14 | if (A.get(i + 1) != val) { 15 | return 1; 16 | } 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Practice/Arrays/OperationsInArray.java: -------------------------------------------------------------------------------- 1 | public class OperationsInArray { 2 | public void StringOperations() { 3 | String[] operations = { "--X", "X++", "X++" }; 4 | int X = 0; 5 | 6 | for (String input : operations) { 7 | switch (input) { 8 | case ("--X"): 9 | --X; 10 | case ("++X"): 11 | ++X; 12 | case ("X--"): 13 | X--; 14 | case ("X++"): 15 | X++; 16 | } 17 | } 18 | 19 | System.out.println(X); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Practice/Arrays/PairSumDivisibleByM.java: -------------------------------------------------------------------------------- 1 | public class PairSumDivisibleByM { 2 | public int solve(int[] A, int B) { 3 | int[] freq = new int[B]; 4 | 5 | for (int i = 0; i < A.length; i++) { 6 | int val = A[i] % B; 7 | freq[val] += 1; 8 | } 9 | long ans = 0; 10 | int n = (B - 1) / 2; 11 | ans += (long) freq[0] * (freq[0] - 1) / 2; 12 | for (int i = 1; i <= n; i++) { 13 | ans += (long) freq[i] * freq[B - i]; 14 | } 15 | 16 | if (B % 2 == 0) { 17 | int left_index = (B / 2); 18 | ans += (long) freq[left_index] * (freq[left_index] - 1) / 2; 19 | } 20 | 21 | return (int) (ans % 1000000007); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Practice/Arrays/PeakElementUsingBinarySearch.java: -------------------------------------------------------------------------------- 1 | public class PeakElementUsingBinarySearch { 2 | public int solve(int[] A) { 3 | int n = A.length; 4 | if (n == 1) 5 | return A[0]; 6 | if (A[0] > A[1]) 7 | return A[0]; 8 | if (A[n - 1] > A[n - 2]) 9 | return A[n - 1]; 10 | 11 | int l = 0; 12 | int r = A.length - 1; 13 | int mid = (l + r) / 2; 14 | while (l <= r) { 15 | int curr_value = A[mid]; 16 | if (curr_value > A[mid - 1] && curr_value > A[mid + 1]) { 17 | return curr_value; 18 | } else if (A[mid - 1] > curr_value) 19 | r = mid - 1; 20 | else 21 | l = mid + 1; 22 | mid = (l + r) / 2; 23 | } 24 | 25 | return A[mid]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Practice/Arrays/Prefix_Sum_Intro_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Arrays/Prefix_Sum_Intro_1.pdf -------------------------------------------------------------------------------- /Practice/Arrays/Prefix_Sum_Intro_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Arrays/Prefix_Sum_Intro_2.pdf -------------------------------------------------------------------------------- /Practice/Arrays/PrimeModuloInverse.java: -------------------------------------------------------------------------------- 1 | public class PrimeModuloInverse { 2 | public int solve(int A, int B) { 3 | return PowerFunction(A, B - 2, B); 4 | } 5 | 6 | public int PowerFunction(int A, int B, int M) { 7 | if (A == 0) 8 | return 0; 9 | if (B == 0) 10 | return 1; 11 | 12 | long val = PowerFunction(A, B / 2, M); 13 | 14 | if (B % 2 == 0) { 15 | long curr_val = (val % M * val % M) % M; 16 | if (curr_val < 0) { 17 | curr_val += M; 18 | } 19 | return (int) curr_val; 20 | } else { 21 | long curr_val = (val % M * val % M * A % M) % M; 22 | if (curr_val < 0) { 23 | curr_val += M; 24 | } 25 | return (int) curr_val; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Practice/Arrays/PrimeSubsequences.java: -------------------------------------------------------------------------------- 1 | public class PrimeSubsequences { 2 | public int solve(int[] A) { 3 | int count = 0; 4 | int mod = 1000000007; 5 | int num = 1; 6 | for (int i = 0; i < A.length; i++) { 7 | if (isPrime(A[i])) { 8 | count = count % mod + num % mod; 9 | count = count % mod; 10 | num = num % mod + num % mod; 11 | num = num % mod; 12 | } 13 | } 14 | return count; 15 | 16 | } 17 | 18 | public boolean isPrime(int N) { 19 | if (N < 2) 20 | return false; 21 | for (int j = 2; j * j <= N; j++) { 22 | if (N % j == 0) 23 | return false; 24 | } 25 | return true; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Practice/Arrays/PrimeSum.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class PrimeSum { 4 | public int[] primesum(int A) { 5 | int val = A; 6 | 7 | // Creating a prime array 8 | int[] prime_array = new int[val + 1]; 9 | Arrays.fill(prime_array, 1); 10 | prime_array[0] = 0; 11 | prime_array[1] = 0; 12 | 13 | for (int i = 2; i * i <= val; i++) { 14 | if (prime_array[i] == 1) { 15 | for (int j = i * i; j <= val; j += i) { 16 | prime_array[j] = 0; 17 | } 18 | } 19 | } 20 | 21 | for (int k = 0; k < prime_array.length; k++) { 22 | if (prime_array[k] == 1) { 23 | int diff = A - k; 24 | if (prime_array[diff] == 1) 25 | return new int[] { k, diff }; 26 | } 27 | } 28 | 29 | return new int[] {}; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Practice/Arrays/ProductExcludingCurrent.js: -------------------------------------------------------------------------------- 1 | //Given array A, return an array with product of all elements except the current position 2 | //output = [] 3 | A = [1,2,3,4,5,6] 4 | D = [1,2,6,24,120,720] 5 | C = [720,720,360,120,30,6] 6 | output = [] 7 | for(i=0;i B.index(A[i][j]): 12 | return 0 13 | elif j == min_length -1 and len(A[i-1]) > len(A[i]): 14 | return 0 15 | 16 | 17 | return 1 -------------------------------------------------------------------------------- /Practice/Arrays/Python/ValidSudoku.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : tuple of strings 3 | # @return an integer 4 | def isValidSudoku(self, A): 5 | myset = set() 6 | 7 | for i in range(0,9): 8 | for j in range(0,9): 9 | curr_val = A[i][j] 10 | if(curr_val!= '.'): 11 | if (curr_val + " rows " + str(i)) in myset or (curr_val + " columns " + str(j)) in myset or (curr_val + " box " + str(i//3) + "-" + str(j//3)) in myset: 12 | return 0 13 | myset.add(curr_val + " rows " + str(i)) 14 | myset.add(curr_val + " columns " + str(j)) 15 | myset.add(curr_val + " box " + str(i//3) + "-" + str(j//3)) 16 | 17 | return 1 18 | -------------------------------------------------------------------------------- /Practice/Arrays/RainWaterTrapped.js: -------------------------------------------------------------------------------- 1 | A = [0, 1, 0, 2] 2 | 3 | Max_left_array = [A[0]] 4 | Max_right_array = [] 5 | Max_right_array[A.length-1] = A[A.length-1] 6 | Total_water = 0 7 | for(i=1;i=0;i--){ 12 | Max_right_array[i] = Math.max(A[i],Max_right_array[i+1]) 13 | } 14 | 15 | for(i=0;i A) { 5 | 6 | int n = A.size(); 7 | 8 | for (int i = 0; i < A.size(); i++) { 9 | A.set(i, A.get(i) * n); 10 | } 11 | 12 | for (int i = 0; i < A.size(); i++) { 13 | int index = A.get(i) / n; 14 | int val = A.get(index) / n; 15 | 16 | A.set(i, A.get(i) + val); 17 | } 18 | 19 | for (int i = 0; i < A.size(); i++) { 20 | A.set(i, A.get(i) % n); 21 | } 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /Practice/Arrays/RepeatingAndMissingNumbers.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Arrays/RepeatingAndMissingNumbers.java -------------------------------------------------------------------------------- /Practice/Arrays/ReplicateSubstrings.js: -------------------------------------------------------------------------------- 1 | function ReplicationSubstring(A,B){ 2 | if(B.length%A != 0) return -1 3 | Bmap = new Map() 4 | for(i=0;i= A[0]) { 11 | if (A[0] <= B && B < A[mid]) { 12 | r = mid - 1; 13 | } else 14 | l = mid + 1; 15 | } else if (B < A[mid]) 16 | r = mid - 1; 17 | else 18 | l = mid + 1; 19 | 20 | mid = (l + r) / 2; 21 | } 22 | 23 | return -1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Practice/Arrays/SearchInBitonicArrayLinearSolution.java: -------------------------------------------------------------------------------- 1 | public class SearchInBitonicArrayLinearSolution { 2 | public int solve(int[] A, int B) { 3 | for (int i = 0; i < A.length; i++) { 4 | if (A[i] == B) 5 | return i; 6 | } 7 | return -1; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Practice/Arrays/SearchInSortedRowAndColumns.java: -------------------------------------------------------------------------------- 1 | public class SearchInSortedRowAndColumns { 2 | public int solve(int[][] A, int B) { 3 | int N = A.length; 4 | int M = A[0].length; 5 | 6 | int i = 0; 7 | int j = M - 1; 8 | int ans = Integer.MAX_VALUE; 9 | while (i < N && j >= 0) { 10 | int val = A[i][j]; 11 | if (val == B) { 12 | int val1 = ((i + 1) * 1009 + (j + 1)); 13 | ans = Math.min(val1, ans); 14 | j--; 15 | } 16 | if (B > val) 17 | i++; 18 | else if (B < val) 19 | j--; 20 | } 21 | 22 | if (ans == Integer.MAX_VALUE) 23 | return -1; 24 | return ans; 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Practice/Arrays/SortedInsertPositionUsingBinarySearch.java: -------------------------------------------------------------------------------- 1 | public class SortedInsertPositionUsingBinarySearch { 2 | public int searchInsert(int[] A, int B) { 3 | int l = 0; 4 | int r = A.length - 1; 5 | if (A[r] < B) 6 | return r + 1; 7 | if (A[l] >= B) 8 | return 0; 9 | int index = 0; 10 | int mid = (l + r) / 2; 11 | while (l <= r) { 12 | 13 | int curr_val = A[mid]; 14 | if (curr_val == B) { 15 | return mid; 16 | } else if (curr_val > B) { 17 | r = mid - 1; 18 | } else { 19 | index = mid; 20 | l = mid + 1; 21 | } 22 | mid = (l + r) / 2; 23 | } 24 | return index + 1; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Practice/Arrays/SpecialSubsequence.java: -------------------------------------------------------------------------------- 1 | public class SpecialSubsequence { 2 | public int solve(String A) { 3 | int gCount = 0; 4 | int output = 0; 5 | 6 | for(int i=A.length() -1;i>=0;i--){ 7 | if(A.charAt(i) == 'G'){ 8 | gCount += 1; 9 | } 10 | else{ 11 | if(A.charAt(i) == 'A'){ 12 | output += gCount; 13 | } 14 | } 15 | } 16 | 17 | return output%1000000007; 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Practice/Arrays/SqrtOfInteger.java: -------------------------------------------------------------------------------- 1 | public class SqrtOfInteger { 2 | public int sqrt(int A) { 3 | int l = 0; 4 | int r = Math.min(A,1000000000); 5 | int mid = (l+r)/2; 6 | int output = 0; 7 | while(l<=r){ 8 | long prod = (long)mid*mid; 9 | if(prod == A){ 10 | return mid; 11 | } 12 | else if(prod>A){ 13 | r = mid-1; 14 | } 15 | else{ 16 | output = mid; 17 | l = mid+1; 18 | } 19 | mid = (l+r)/2; 20 | } 21 | 22 | return output; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Practice/Arrays/SubArrayWith0Sum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class SubArrayWith0Sum { 4 | public int solve(int[] A) { 5 | 6 | for (int c = 0; c < A.length; c++) { 7 | if (A[c] == 0) 8 | return 1; 9 | } 10 | 11 | long[] pf = new long[A.length]; 12 | pf[0] = A[0]; 13 | for (int i = 1; i < A.length; i++) { 14 | pf[i] = pf[i - 1] + A[i]; 15 | } 16 | 17 | HashMap hm = new HashMap(); 18 | 19 | for (int k = 0; k < pf.length; k++) { 20 | if (pf[k] == 0) 21 | return 1; 22 | 23 | int val = hm.getOrDefault(pf[k], 0); 24 | if (val == 1) 25 | return 1; 26 | hm.put(pf[k], val + 1); 27 | } 28 | 29 | return 0; 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Practice/Arrays/Subarrays_Intro_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Arrays/Subarrays_Intro_1.pdf -------------------------------------------------------------------------------- /Practice/Arrays/SumOfAllSubMatrices.java: -------------------------------------------------------------------------------- 1 | public class SumOfAllSubMatrices { 2 | public int solve(int[][] A) { 3 | int sum = 0; 4 | for (int row = 0; row < A.length; row++) { 5 | for (int col = 0; col < A[0].length; col++) { 6 | sum += A[row][col] * (row + 1) * (col + 1) * (A.length - row) * (A[0].length - col); 7 | } 8 | } 9 | 10 | return sum; 11 | } 12 | } -------------------------------------------------------------------------------- /Practice/Arrays/SumOfAllSubarrays.java: -------------------------------------------------------------------------------- 1 | public class SumOfAllSubarrays { 2 | public long subarraySum(int[] A) { 3 | 4 | long total_sum = 0; 5 | int N = A.length; 6 | for (int i = 0; i < A.length; i++) { 7 | total_sum += (long) A[i] * (i + 1) * (N - i); 8 | } 9 | 10 | return total_sum; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Practice/Arrays/SumOfPrimes.java: -------------------------------------------------------------------------------- 1 | public class SumOfPrimes { 2 | public int solve(int A) { 3 | if (A == 2) 4 | return 1; 5 | return 2; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Practice/Arrays/SumofDifference.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class SumofDifference { 4 | public int solve(int[] A) { 5 | Arrays.sort(A); 6 | long pow = 1; 7 | long mod = 1000000007; 8 | long output = 0; 9 | for (int i = 0; i < A.length; ++i) { 10 | output = (output + A[i] * pow - A[A.length - 1 - i] * pow) % mod; 11 | pow = pow * 2 % mod; 12 | } 13 | 14 | return (int) ((output + mod) % mod); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Practice/Arrays/Teams.js: -------------------------------------------------------------------------------- 1 | function Teams(A) { 2 | let zeroCount = 0; 3 | let oneCount = 0; 4 | let count = 0; 5 | for (let i = 0; i < A.length; i++) { 6 | if (A[i] == "0") { 7 | zeroCount++; 8 | } else if (A[i] == "1") { 9 | oneCount++; 10 | } 11 | if (zeroCount == oneCount && zeroCount != 0 && oneCount != 0) { 12 | count++; 13 | zeroCount = 0; 14 | oneCount = 0; 15 | } 16 | } 17 | 18 | return count; 19 | } 20 | 21 | A = "00100000100101111111"; 22 | 23 | console.log(Teams(A)); 24 | -------------------------------------------------------------------------------- /Practice/Arrays/TimeToEquality.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class TimeToEquality { 4 | public int solve(ArrayList A) { 5 | 6 | int max = A.get(0); 7 | for (int x : A) { 8 | if (max < x) { 9 | max = x; 10 | } 11 | } 12 | 13 | int output = 0; 14 | for (int i : A) { 15 | output = output + (max - i); 16 | } 17 | 18 | return output; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Practice/Arrays/TransposeMatrix.java: -------------------------------------------------------------------------------- 1 | public class TransposeMatrix { 2 | public int[][] solve(int[][] A) { 3 | 4 | int[][] transpose = new int[A[0].length][A.length]; 5 | 6 | for (int i = 0; i < A.length; i++) { 7 | for (int j = 0; j < A[0].length; j++) { 8 | transpose[j][i] = A[i][j]; 9 | } 10 | } 11 | 12 | return transpose; 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Practice/Arrays/ValidSudoku.py: -------------------------------------------------------------------------------- 1 | Sudoku = ['53..7....','6..195...','.98....6.','8...6...3','4..8.3..1','7...2...6','.6....28.','...419..5','....8..79'] 2 | 3 | def isValidSudoku(S): 4 | myset = set() 5 | for i in range(0,9): 6 | for j in range(0,9): 7 | if not set.add(S[i][j] + 'found in row' + i) or not set.add(S[i][j] + 'found in column' + j) or not set.add(S[i][j] + 'found in matrix' + i/3 + '-' + j/3): 8 | return 'invalid' 9 | 10 | return 'valid' 11 | 12 | print(isValidSudoku(Sudoku)) -------------------------------------------------------------------------------- /Practice/Arrays/findSubsequence.js: -------------------------------------------------------------------------------- 1 | A = "mcbzcsqvouyrsq" 2 | B = "wnqryjentzuptshyjvufcbhkcorfchzvhotqwctvgjjhmfcrsminuvabryqplqarmbsxewaumd" 3 | C = "" 4 | console.log(findSubsequence(A,B)) 5 | function findSubsequence(A,B){ 6 | i = 0 7 | ind = B.indexOf(A[0]) 8 | for(i=1;i0 && len2>0){ 13 | if(B.indexOf(str1[j]) < B.indexOf(str2[j])) break 14 | if(B.indexOf(str1[j]) > B.indexOf(str2[j])) return 0 15 | 16 | j += 1 17 | len1 -= 1 18 | len2 -= 1 19 | } 20 | 21 | if(len1 > len2 && str1.indexOf(str2) >=0){ 22 | return 0 23 | } 24 | } 25 | return 1 26 | } 27 | 28 | console.log(isDictionary(A,B)) 29 | 30 | -------------------------------------------------------------------------------- /Practice/Arrays/removeOddsfromMatrix.js: -------------------------------------------------------------------------------- 1 | A = [ [1, 2, 3, 4], 2 | [4, 5, 6, 7], 3 | [8, 9, 10, 11], 4 | [13, 15, 17, 19] ] 5 | 6 | output = [] 7 | for (i=0;i val)); 9 | return; 10 | } 11 | 12 | for (let k = i; k < n; k++) { 13 | swap(A, k, i); 14 | output.push(A[i]); 15 | findSixLets(A, i + 1, n); 16 | swap(A, k, i); 17 | output.pop(); 18 | } 19 | } 20 | 21 | function swap(A, i, j) { 22 | let temp = A[i]; 23 | A[i] = A[j]; 24 | A[j] = temp; 25 | } 26 | } 27 | 28 | A = [1, 2, 3]; 29 | 30 | console.log(Permutations(A)); 31 | -------------------------------------------------------------------------------- /Practice/Backtraking/SixLets.js: -------------------------------------------------------------------------------- 1 | function SixLets(A, B) { 2 | let count = 0; 3 | let output = []; 4 | findSixLets(A, 0, A.length); 5 | return count; 6 | function findSixLets(A, i, n) { 7 | if (i == n) { 8 | if (output.length == B) { 9 | let sum = 0; 10 | for (let i = 0; i < output.length; i++) { 11 | sum += output[i]; 12 | } 13 | if (sum <= 1000) count++; 14 | } 15 | return; 16 | } 17 | 18 | output.push(A[i]); 19 | findSixLets(A, i + 1, n); 20 | output.pop(); 21 | findSixLets(A, i + 1, n); 22 | } 23 | } 24 | 25 | A = [5, 17, 1000, 11]; 26 | B = 4; 27 | 28 | console.log(SixLets(A, B)); 29 | -------------------------------------------------------------------------------- /Practice/BinarySearch/FoodPacketDistribution.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | //param A : array of integers 3 | //param B : integer 4 | //return an integer 5 | solve: function (A, B) { 6 | let min = A[0]; 7 | let sum = A[0]; 8 | 9 | for (let i = 1; i < A.length; i++) { 10 | sum += A[i]; 11 | min = Math.min(min, A[i]); 12 | } 13 | if (sum < B) return 0; 14 | 15 | let l = 1, 16 | r = min, 17 | ans = 0; 18 | 19 | while (l <= r) { 20 | let mid = Math.floor((l + r) / 2); 21 | if (check(mid, B, A)) { 22 | ans = mid; 23 | l = mid + 1; 24 | } else r = mid - 1; 25 | } 26 | 27 | return ans; 28 | }, 29 | }; 30 | 31 | function check(mid, B, A) { 32 | let count = 0; 33 | for (let i = 0; i < A.length; i++) { 34 | count += Math.floor(A[i] / mid); 35 | } 36 | 37 | return count >= B; 38 | } 39 | -------------------------------------------------------------------------------- /Practice/Bit Manipulation/C#/Reverse32BitUnsignedInteger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Reverse32BitUnsignedInteger 5 | { 6 | class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | uint output = reverseBits(1); 11 | Console.WriteLine(output); 12 | Console.ReadKey(); 13 | } 14 | 15 | 16 | public static uint reverseBits(uint n) 17 | { 18 | uint output = 0; 19 | for (int i = 0; i < 32; i++) 20 | { 21 | var temp = (n >> i) & 1; 22 | output = output | (temp << (31 - i)); 23 | 24 | } 25 | 26 | return output; 27 | } 28 | 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Intro_Bits_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Bit Manipulation/Intro_Bits_1.pdf -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Intro_Bits_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Bit Manipulation/Intro_Bits_2.pdf -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Java/CountTotalSetBits.java: -------------------------------------------------------------------------------- 1 | public class CountTotalSetBits { 2 | public static void main(String[] args) { 3 | int A = 4; 4 | CountTotalSetBits countTotalSetBits = new CountTotalSetBits(); 5 | 6 | System.out.println(countTotalSetBits.TotalSetBits(A)); 7 | } 8 | 9 | public int TotalSetBits(int A){ 10 | if(A == 0) return 0; 11 | int pow = -1; 12 | int X = A; 13 | while(X>0){ 14 | pow++; 15 | X = X>>1; 16 | } 17 | 18 | int val = (int)Math.pow(2,pow); 19 | long totalSetBits = (long)(val/2)*pow + (A-val+1) + TotalSetBits(A-val); 20 | return (int)(totalSetBits%1000000007); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Java/FindReverseBitUnsigned.java: -------------------------------------------------------------------------------- 1 | public class FindReverseBitUnsigned{ 2 | 3 | public static void main(String[] args) { 4 | int A = 3; 5 | System.out.println(FindReverseBitUnsigned.FindReverse(A)); 6 | } 7 | 8 | public static long FindReverse(int A){ 9 | long reverse = 0; 10 | 11 | for(int i=0;i<32;i++){ 12 | if(A*(1< 0){ 13 | reverse += (long)1 << (31-i); 14 | } 15 | } 16 | 17 | return reverse; 18 | } 19 | } -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Java/InterestingArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class InterestingArray { 4 | public static void main(String[] args) { 5 | ArrayList A = new ArrayList<>(List.of(9,17)); 6 | InterestingArray ia = new InterestingArray(); 7 | System.out.println(ia.solve(A)); 8 | } 9 | public String solve(ArrayList A) { 10 | int xorValue = 0; 11 | 12 | for(int i=0;i a) { 6 | int output = 0; 7 | for (int x : a) { 8 | output = output ^ x; 9 | } 10 | return output; 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Java/MinimumXORValue.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class MinimumXORValue { 4 | public static void main(String[] args) { 5 | ArrayList A = new ArrayList<>(List.of(4,7,0,9)); 6 | MinimumXORValue mxv = new MinimumXORValue(); 7 | System.out.println(mxv.findMinXor(A)); 8 | } 9 | public int findMinXor(ArrayList A) { 10 | Collections.sort(A); 11 | 12 | int min = Integer.MAX_VALUE; 13 | 14 | for(int i=1;i0){ 13 | noOfSetBits++; 14 | A = A &(A-1); 15 | } 16 | 17 | return noOfSetBits; 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Java/ReverseBits.java: -------------------------------------------------------------------------------- 1 | public class ReverseBits { 2 | public static void main(String[] args) { 3 | ReverseBits reverseBits = new ReverseBits(); 4 | long A = 3; 5 | System.out.println(reverseBits.reverse(A)); 6 | } 7 | public long reverse(long a) { 8 | long reverseInt = 0; 9 | 10 | for(int i=0;i<32;i++){ 11 | if((a & (1< 0){ 12 | reverseInt |= (long)1<<(31-i); 13 | } 14 | 15 | } 16 | 17 | return reverseInt; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Java/SingleNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | public class SingleNumber { 4 | public static void main(String[] args) { 5 | List A = new ArrayList(List.of(1,1,2,2,3,3,4)); 6 | SingleNumber sn = new SingleNumber(); 7 | System.out.println(sn.singleNumber(A)); 8 | } 9 | public int singleNumber(final List A) { 10 | int ans = 0; 11 | for(int i=0;i A = new ArrayList(List.of(1,1,1,2,2,2,3,3,3,4)); 8 | SingleNumberII sn = new SingleNumberII(); 9 | System.out.println(sn.singleNumber(A)) ; 10 | } 11 | public int singleNumber(final List A) { 12 | int ans = 0; 13 | 14 | for(int i=0;i<32;i++){ 15 | int count = 0; 16 | for(int j=0;j 0){ 20 | count++; 21 | } 22 | } 23 | 24 | if(count%3!=0){ 25 | ans |= 1<=0;i--){ 12 | if((A & (1< 0){ 13 | ans |= 1<0){ 13 | if((A &(1<<0)) == 0){ 14 | smallNumber |= 1<>1; 18 | } 19 | 20 | largeNumber |= 1<<(i); 21 | return smallNumber^largeNumber; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Practice/Bit Manipulation/Javascript/NoOf1Bits.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | //param A : integer 3 | //return an integer 4 | numSetBits : function(A){ 5 | if(A == 0) 6 | return 0 7 | count = 0 8 | while(A>1){ 9 | 10 | if(Math.floor(A%2) == 1){ 11 | count++ 12 | } 13 | 14 | A = A/2 15 | } 16 | if(count == 0) 17 | return 1 18 | return count 19 | } 20 | } -------------------------------------------------------------------------------- /Practice/CalculateRunningTime.js: -------------------------------------------------------------------------------- 1 | function calculateRunningTime(A){ 2 | //Start time 3 | sit = new Date() 4 | st = sit.getMilliseconds() 5 | 6 | 7 | 8 | //End Time 9 | sit = new Date() 10 | et = sit.getMilliseconds(); 11 | console.log('Total time taken: ' + (et-st) + ' milliseconds') 12 | } -------------------------------------------------------------------------------- /Practice/Dynamic Programming/CuttinARod.js: -------------------------------------------------------------------------------- 1 | function CuttingARod(A) { 2 | let N = A.length; 3 | let hs = new Map(); 4 | let maxValue = 0; 5 | CalculateMaxValue(0, N); 6 | return maxValue; 7 | function CalculateMaxValue(i, N) { 8 | if (N == 0) { 9 | return 0; 10 | } 11 | if (hs.has(i + "" + N)) return hs.get(i + "" + N); 12 | 13 | hs.set( 14 | i + "" + N, 15 | Math.max( 16 | CalculateMaxValue(i, N - 1) + A[i], 17 | CalculateMaxValue(i + 1, N - 1) + A[i] 18 | ) 19 | ); 20 | maxValue = Math.max(maxValue, hs.get(i + "" + N)); 21 | return hs.get(i + "" + N); 22 | } 23 | } 24 | 25 | A = [3, 4, 1, 6, 2]; 26 | 27 | console.log(CuttingARod(A)); 28 | -------------------------------------------------------------------------------- /Practice/Dynamic Programming/FibonacciNumber.js: -------------------------------------------------------------------------------- 1 | function FibonacciNumber(A) { 2 | let arr = []; 3 | arr.push(0); 4 | arr.push(1); 5 | for (let i = 2; i <= A; i++) { 6 | arr.push(-1); 7 | } 8 | return findAthNum(A); 9 | function findAthNum(A) { 10 | if (arr[A] != -1) return arr[A]; 11 | 12 | arr[A] = findAthNum(A - 1) + findAthNum(A - 2); 13 | return arr[A]; 14 | } 15 | } 16 | 17 | A = 4; 18 | 19 | console.log(FibonacciNumber(A)); 20 | -------------------------------------------------------------------------------- /Practice/Dynamic Programming/InfiniteKnapsack.js: -------------------------------------------------------------------------------- 1 | function InfiniteKnapsack(A, B, C) { 2 | let dpMap = new Map(); 3 | MaxAmount(B.length, A); 4 | 5 | return dpMap.get(B.length + " " + A); 6 | function MaxAmount(N, W) { 7 | if (N == 0 || W == 0) return 0; 8 | if (dpMap.has(N + " " + W)) return dpMap.has(N + " " + W); 9 | if (C[N - 1] <= W) { 10 | dpMap.set( 11 | N + " " + W, 12 | Math.max(MaxAmount(N - 1, W), MaxAmount(N, W - C[N - 1]) + B[N - 1]) 13 | ); 14 | } else { 15 | dpMap.set(N + " " + W, MaxAmount(N - 1, W)); 16 | } 17 | 18 | return dpMap.get(N + " " + W); 19 | } 20 | } 21 | 22 | A = 10; 23 | B = [6, 7]; 24 | C = [5, 5]; 25 | 26 | console.log(InfiniteKnapsack(A, B, C)); 27 | -------------------------------------------------------------------------------- /Practice/Dynamic Programming/LetsParty.js: -------------------------------------------------------------------------------- 1 | function LetsParty(A) { 2 | let arr = Array(A + 1).fill(-1); 3 | let mod = 10003; 4 | calculate(A); 5 | 6 | return arr[arr.length - 1]; 7 | function calculate(A) { 8 | if (A == 1) { 9 | arr[1] = 1; 10 | return arr[1]; 11 | } 12 | 13 | if (A == 2) { 14 | arr[2] = 2; 15 | return arr[2]; 16 | } 17 | 18 | if (arr[A] != -1) return arr[A]; 19 | 20 | arr[A] = 21 | ((calculate(A - 1) % mod) + ((A - 1) % mod) * (calculate(A - 2) % mod)) % 22 | mod; 23 | 24 | return arr[A]; 25 | } 26 | } 27 | A = 465; 28 | console.log(LetsParty(A)); 29 | -------------------------------------------------------------------------------- /Practice/Dynamic Programming/MinimumNumberOfSquares.js: -------------------------------------------------------------------------------- 1 | function MinimumNumberOfSquares(A) { 2 | let arr = []; 3 | for (let i = 0; i <= A; i++) { 4 | arr.push(-1); 5 | } 6 | return findValue(A); 7 | function findValue(A) { 8 | if (A == 0) return 0; 9 | if (arr[A] != -1) return arr[A]; 10 | 11 | arr[A] = 1; 12 | let min = Number.MAX_SAFE_INTEGER; 13 | 14 | for (let i = 1; i * i <= A; i++) { 15 | min = Math.min(min, findValue(A - i * i)); 16 | } 17 | arr[A] += min; 18 | return arr[A]; 19 | } 20 | } 21 | A = 6; 22 | console.log(MinimumNumberOfSquares(A)); 23 | -------------------------------------------------------------------------------- /Practice/Dynamic Programming/Stairs.js: -------------------------------------------------------------------------------- 1 | function Stairs(A) { 2 | let arr = []; 3 | 4 | for (let i = 0; i <= A; i++) { 5 | arr.push(-1); 6 | } 7 | 8 | return WaysToClimb(A); 9 | function WaysToClimb(A) { 10 | if (A == 1) return 1; 11 | if (A == 2) return 2; 12 | 13 | if (arr[A] != -1) return arr[A]; 14 | 15 | arr[A] = WaysToClimb(A - 1) + WaysToClimb(A - 2); 16 | return arr[A]; 17 | } 18 | } 19 | 20 | A = 3; 21 | 22 | console.log(Stairs(A)); 23 | -------------------------------------------------------------------------------- /Practice/Graphs/ColoringACycleGraph.js: -------------------------------------------------------------------------------- 1 | function ColoringACycleGraph(A) { 2 | if (A % 2 == 0) return 2; 3 | return 3; 4 | } 5 | 6 | A = 6; // Number of vertices in a cycling graph 7 | 8 | console.log(ColoringACycleGraph(A)); 9 | -------------------------------------------------------------------------------- /Practice/Graphs/FirstDepthFirstSearch.js: -------------------------------------------------------------------------------- 1 | function FirstDepthFirstSearch(A, B, C) { 2 | let graphPaths = {}; 3 | for (let i = 0; i < A.length; i++) { 4 | if (graphPaths[A[i]] == undefined) { 5 | graphPaths[A[i]] = [i + 1]; 6 | } else { 7 | let arr = graphPaths[A[i]]; 8 | arr.push(i + 1); 9 | graphPaths[A[i]] = arr; 10 | } 11 | } 12 | visitedArray = new Set(); 13 | DFS(graphPaths, C); 14 | if (visitedArray.has(B)) return 1; 15 | return 0; 16 | function DFS(graphPaths, source) { 17 | visitedArray.add(source); 18 | if (graphPaths[source] != undefined) { 19 | for (let i = 0; i < graphPaths[source].length; i++) { 20 | if (!visitedArray.has(graphPaths[source][i])) { 21 | DFS(graphPaths, graphPaths[source][i]); 22 | } 23 | } 24 | } 25 | } 26 | } 27 | 28 | A = [1, 1, 2]; 29 | B = 1; 30 | C = 2; 31 | 32 | console.log(FirstDepthFirstSearch(A, B, C)); 33 | -------------------------------------------------------------------------------- /Practice/Greedy Alogirthm/AnotherCoinProblem.java: -------------------------------------------------------------------------------- 1 | public class AnotherCoinProblem{ 2 | 3 | public static void main(String[] args) { 4 | AnotherCoinProblem anotherCoinProblem = new AnotherCoinProblem(); 5 | System.out.println(anotherCoinProblem.solve(47)); 6 | 7 | } 8 | public int solve(int A){ 9 | int coins = 0; 10 | 11 | while(A>=5){ 12 | int val = A%5; 13 | coins += val; 14 | A -= val; 15 | 16 | A /= 5; 17 | } 18 | 19 | coins += A; 20 | 21 | return coins; 22 | } 23 | } -------------------------------------------------------------------------------- /Practice/Greedy Alogirthm/AssignMiceToHole.js: -------------------------------------------------------------------------------- 1 | function AssignMiceToHole(A, B) { 2 | let ans = Number.MIN_SAFE_INTEGER; 3 | A.sort((a, b) => a - b); 4 | B.sort((a, b) => a - b); 5 | 6 | for (let i = 0; i < A.length; i++) { 7 | ans = Math.max(ans, Math.abs(A[i] - B[i])); 8 | } 9 | return ans; 10 | } 11 | 12 | A = [-4, 2, 3]; 13 | B = [0, -2, 4]; 14 | 15 | console.log(AssignMiceToHole(A, B)); 16 | -------------------------------------------------------------------------------- /Practice/Greedy Alogirthm/FinishMaximumJobs.js: -------------------------------------------------------------------------------- 1 | function FinishMaximumJobs(A, B) { 2 | let output = 1; 3 | let newArray = []; 4 | for (let i = 0; i < A.length; i++) { 5 | let curr_input = [A[i], B[i]]; 6 | newArray.push(curr_input); 7 | } 8 | newArray.sort(function (a, b) { 9 | return a[1] - b[1]; 10 | }); 11 | let endTime = newArray[0][1]; 12 | for (let i = 1; i < newArray.length; i++) { 13 | if (newArray[i][0] >= endTime) { 14 | output++; 15 | endTime = newArray[i][1]; 16 | } 17 | } 18 | 19 | console.log(output); 20 | } 21 | 22 | A = [4, 4, 8, 15, 6]; 23 | B = [9, 5, 15, 16, 7]; 24 | 25 | FinishMaximumJobs(A, B); 26 | -------------------------------------------------------------------------------- /Practice/Hashing/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "avoid", 3 | "singleQuote": true 4 | } 5 | -------------------------------------------------------------------------------- /Practice/Hashing/CheckPalindrome.js: -------------------------------------------------------------------------------- 1 | A = 2 | 'mnxljrajwhxiaquajokwvoqqphylxpbanmmhfxsmssxzsdnprtgibuhaxnwxzfozexiascybplaaqjcthuydnoowmkzyamodzknkqmwdglqqnhflfslqyowcangsddhcjjuiyfbdkevlghbictrvnmnathotrekyrggwcmbzorqtyeowksywlbetsyhjvczcnvusfdrxythrhhoxtuuprqftgwohcgpngktkharijsovuknae'; 3 | 4 | function CheckPalindrome(A) { 5 | let hm = new Map(); 6 | 7 | for (let i = 0; i < A.length; i++) { 8 | hm.set(A[i], hm.has(A[i]) ? hm.get(A[i]) + 1 : 1); 9 | } 10 | let numberOfOneValueKeys = 0; 11 | if (A.length % 2 == 0) { 12 | for (const [key, value] of hm.entries()) { 13 | if (value % 2 != 0) return 0; 14 | } 15 | } else { 16 | for (const [key, value] of hm.entries()) { 17 | if (value % 2 != 0) numberOfOneValueKeys++; 18 | if (numberOfOneValueKeys > 1) return 0; 19 | } 20 | } 21 | 22 | return 1; 23 | } 24 | 25 | console.log(CheckPalindrome(A)); 26 | -------------------------------------------------------------------------------- /Practice/Hashing/ColorfulNumber.js: -------------------------------------------------------------------------------- 1 | A = 231; 2 | 3 | function ColorFulNumber(A) { 4 | let stringValue = String(A); 5 | let hs = new Set(); 6 | for (let i = 0; i < stringValue.length; i++) { 7 | let product = stringValue[i]; 8 | for (let j = i; j < stringValue.length; j++) { 9 | if (j == i) { 10 | if (hs.has(stringValue[i])) return 0; 11 | else hs.add(stringValue[i]); 12 | } else { 13 | product = product * stringValue[j]; 14 | if (hs.has(String(product))) return 0; 15 | else hs.add(String(product)); 16 | } 17 | } 18 | } 19 | return 1; 20 | } 21 | 22 | console.log(ColorFulNumber(A)); 23 | -------------------------------------------------------------------------------- /Practice/Hashing/CommonElements.js: -------------------------------------------------------------------------------- 1 | function CommonElements(A, B) { 2 | const hm = new Map(); 3 | let output = []; 4 | for (let i = 0; i < B.length; i++) { 5 | hm.set(B[i], hm.has(B[i]) ? hm.get(B[i]) + 1 : 1); 6 | } 7 | 8 | for (let i = 0; i < A.length; i++) { 9 | if (hm.has(A[i])) { 10 | output.push(A[i]); 11 | hm.set(A[i], hm.get(A[i]) - 1); 12 | if (hm.get(A[i]) == 0) hm.delete(A[i]); 13 | } 14 | } 15 | 16 | return output; 17 | } 18 | 19 | A = [1, 2, 2, 1]; 20 | B = [2, 3, 1, 2]; 21 | console.log(CommonElements(A, B)); 22 | -------------------------------------------------------------------------------- /Practice/Hashing/CountRightTriangles.js: -------------------------------------------------------------------------------- 1 | function CountRightTriangles(A, B) { 2 | const arr = []; 3 | const hmX = new Map(); 4 | const hmY = new Map(); 5 | 6 | for (let i = 0; i < A.length; i++) { 7 | let ar = [A[i], B[i]]; 8 | arr.push(ar); 9 | hmX.set(A[i], hmX.has(A[i]) ? hmX.get(A[i]) + 1 : 1); 10 | hmY.set(B[i], hmY.has(B[i]) ? hmY.get(B[i]) + 1 : 1); 11 | } 12 | let ans = 0; 13 | for (let i = 0; i < arr.length; i++) { 14 | let x = arr[i][0]; 15 | let y = arr[i][1]; 16 | 17 | let xVal = hmX.get(x) - 1; 18 | let yVal = hmY.get(y) - 1; 19 | 20 | ans += xVal * yVal; 21 | } 22 | 23 | return ans; 24 | } 25 | 26 | A = [1, 1, 2]; 27 | B = [1, 2, 1]; 28 | 29 | console.log(CountRightTriangles(A, B)); 30 | -------------------------------------------------------------------------------- /Practice/Hashing/DistinctNumberOfWindows.js: -------------------------------------------------------------------------------- 1 | const A = [1, 2, 1, 3, 4, 3]; 2 | const B = 3; 3 | 4 | const DistinctNumberOfWindows = (A, B) => { 5 | let output = []; 6 | if (B > A.length) { 7 | return output; 8 | } 9 | 10 | let hs = new Map(); 11 | 12 | for (let i = 0; i < B; i++) { 13 | hs.set(A[i], hs.has(A[i]) ? hs.get(A[i]) + 1 : 1); 14 | } 15 | 16 | output.push(hs.size); 17 | 18 | for (let i = B; i < A.length; i++) { 19 | hs.set(A[i - B], hs.get(A[i - B]) - 1); 20 | if (hs.get(A[i - B]) == 0) hs.delete(A[i - B]); 21 | hs.set(A[i], hs.has(A[i]) ? hs.get(A[i]) + 1 : 1); 22 | output.push(hs.size); 23 | } 24 | 25 | return output; 26 | }; 27 | 28 | console.log(DistinctNumberOfWindows(A, B)); 29 | -------------------------------------------------------------------------------- /Practice/Hashing/LargestContinuousSequenceZeroSum.js: -------------------------------------------------------------------------------- 1 | A = [1, 2, -2, 4, -4]; 2 | 3 | const LargestContinuousSequenceZeroSum = A => { 4 | pref_A = [0]; 5 | 6 | for (let i = 0; i < A.length; i++) { 7 | pref_A.push(pref_A[i] + A[i]); 8 | } 9 | 10 | let hm = new Map(); 11 | 12 | hm['0'] = 0; 13 | let start = -1; 14 | let end = -1; 15 | ans = 0; 16 | for (let j = 0; j < pref_A.length; j++) { 17 | if (hm.has(pref_A[j])) { 18 | if (j - hm.get(pref_A[j]) > ans) { 19 | ans = j - hm.get(pref_A[j]); 20 | start = hm.get(pref_A[j]); 21 | end = j; 22 | } 23 | } else { 24 | hm.set(pref_A[j], j); 25 | } 26 | } 27 | 28 | let output = []; 29 | 30 | for (let i = start; i < end; i++) { 31 | output.push(A[i]); 32 | } 33 | 34 | return output; 35 | }; 36 | -------------------------------------------------------------------------------- /Practice/Hashing/LongestConsecutiveSequence.js: -------------------------------------------------------------------------------- 1 | A = [-6, -4, -5, -2, -3]; 2 | let maxConsecutiveLength = function(A){ 3 | const hs = new Set(A); 4 | let ans = 0; 5 | 6 | for(let num of A){ 7 | if(!hs.has(num-1)){ 8 | let curr_count = 0; 9 | while(hs.has(num++)){ 10 | curr_count++; 11 | } 12 | ans = Math.max(ans,curr_count); 13 | } 14 | } 15 | 16 | return ans; 17 | } 18 | 19 | console.log(maxConsecutiveLength(A)); -------------------------------------------------------------------------------- /Practice/Hashing/MinimumDistance.js: -------------------------------------------------------------------------------- 1 | function MinimumDistance(A) { 2 | let min_distance = Number.MAX_SAFE_INTEGER; 3 | let o = -1; 4 | let x = -1; 5 | for (let i = 0; i < A.length; i++) { 6 | if (A[i] == 'x') { 7 | x = i; 8 | if (o != -1) min_distance = Math.min(min_distance, Math.abs(o - x)); 9 | } else if (A[i] == 'o') { 10 | o = i; 11 | if (x != -1) min_distance = Math.min(min_distance, Math.abs(o - x)); 12 | } 13 | } 14 | 15 | if (min_distance == Number.MAX_SAFE_INTEGER) return -1; 16 | return min_distance; 17 | } 18 | 19 | A = 'x...o.x...o'; 20 | 21 | console.log(MinimumDistance(A)); 22 | -------------------------------------------------------------------------------- /Practice/Hashing/ReplicateSubstring.js: -------------------------------------------------------------------------------- 1 | function ReplicateSubstring(A, B) { 2 | const hm = new Map(); 3 | 4 | for (let i = 0; i < B.length; i++) { 5 | hm.set(B[i], hm.has(B[i]) ? hm.get(B[i]) + 1 : 1); 6 | } 7 | 8 | for (const [key, value] of hm.entries()) { 9 | if (value % A != 0) return -1; 10 | } 11 | 12 | return 1; 13 | } 14 | 15 | A = 2; 16 | B = 'bbaabb'; 17 | 18 | console.log(ReplicateSubstring(A, B)); 19 | -------------------------------------------------------------------------------- /Practice/Hashing/SortArrayInGivenOrder.js: -------------------------------------------------------------------------------- 1 | A = [1, 2, 3, 4, 5]; 2 | B = [5, 4, 2]; 3 | 4 | function SortArrayInGivenOrder(A, B) { 5 | A.sort(function (a, b) { 6 | return a - b; 7 | }); 8 | let hm = new Map(); 9 | 10 | for (let i = 0; i < A.length; i++) { 11 | hm.set(A[i], hm.has(A[i]) ? hm.get(A[i]) + 1 : 1); 12 | } 13 | let output = []; 14 | for (let j = 0; j < B.length; j++) { 15 | while (hm.has(B[j])) { 16 | hm.set(B[j], hm.get(B[j]) - 1); 17 | if (hm.get(B[j]) == 0) hm.delete(B[j]); 18 | output.push(B[j]); 19 | } 20 | } 21 | 22 | for (let i = 0; i < A.length; i++) { 23 | if (hm.has(A[i])) output.push(A[i]); 24 | } 25 | 26 | return output; 27 | } 28 | 29 | console.log(SortArrayInGivenOrder(A, B)); 30 | -------------------------------------------------------------------------------- /Practice/Hashing/SubArrayWithZeroSum.js: -------------------------------------------------------------------------------- 1 | A = [1, 2, 3, 4, 5]; 2 | let SubArrayWithZeroSum = function(A){ 3 | for(let i=0;i { 2 | let curr = head; 3 | while (curr != null) { 4 | let newNode = new Node(); 5 | newNode.data = curr.data; 6 | newNode.next = curr.next; 7 | curr.next = newNode; 8 | curr = newNode.next; 9 | } 10 | curr = head; 11 | head2 = curr.next; 12 | curr2 = head2; 13 | 14 | while (curr != null && curr2 != null) { 15 | if (curr.random != null) { 16 | curr2.random = curr.random.next; 17 | } 18 | curr = curr2.next; 19 | if (curr != null) { 20 | curr2 = curr.next; 21 | } 22 | } 23 | 24 | curr = head; 25 | curr2 = head2; 26 | 27 | while (curr != null && curr2 != null) { 28 | curr.next = curr2.next; 29 | curr = curr.next; 30 | if (curr != null && curr.next != null) { 31 | curr2.next = curr.next; 32 | curr2 = curr2.next; 33 | } 34 | } 35 | 36 | return head2; 37 | }; 38 | -------------------------------------------------------------------------------- /Practice/LinkedList/DeleteMiddleNodeOfLinkedList.js: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | // function Node(data){ 3 | // this.data = data 4 | // this.next = null 5 | // } 6 | 7 | module.exports = { 8 | //param A : head node of linked list 9 | //return the head node in the linked list 10 | solve: function (A) { 11 | let llist_length = 0; 12 | let currentNode = A; 13 | while (currentNode != null) { 14 | llist_length++; 15 | currentNode = currentNode.next; 16 | } 17 | if (llist_length == 1) { 18 | A = null; 19 | return A; 20 | } 21 | let pos_to_del = Math.floor(llist_length / 2); 22 | 23 | currentNode = A; 24 | let count = 1; 25 | while (count < pos_to_del) { 26 | currentNode = currentNode.next; 27 | count++; 28 | } 29 | let temp = currentNode.next; 30 | currentNode.next = temp.next; 31 | return A; 32 | }, 33 | }; 34 | -------------------------------------------------------------------------------- /Practice/LinkedList/KreverseLinkedList.js: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | // function Node(data){ 3 | // this.data = data 4 | // this.next = null 5 | // } 6 | 7 | module.exports = { 8 | //param A : head node of linked list 9 | //param B : integer 10 | //return the head node in the linked list 11 | reverseList: function (A, B) { 12 | return reverseLList(A, B); 13 | }, 14 | }; 15 | 16 | function reverseLList(A, B) { 17 | if (A == null) return null; 18 | let prevNode = null; 19 | let currentNode = A; 20 | let count = B; 21 | 22 | while (count > 0 && currentNode != null) { 23 | let nextNode = currentNode.next; 24 | currentNode.next = prevNode; 25 | prevNode = currentNode; 26 | currentNode = nextNode; 27 | count--; 28 | } 29 | A.next = reverseLList(currentNode, B); 30 | return prevNode; 31 | } 32 | -------------------------------------------------------------------------------- /Practice/LinkedList/ListCycles.js: -------------------------------------------------------------------------------- 1 | let ListCycles = function (A) { 2 | if (A == null || A.next == null) return null; 3 | let slow_pointer = A; 4 | let fast_pointer = A; 5 | while (fast_pointer.next != null && fast_pointer.next.next != null) { 6 | slow_pointer = slow_pointer.next; 7 | fast_pointer = fast_pointer.next.next; 8 | if (slow_pointer == fast_pointer) { 9 | slow_pointer = A; 10 | while (slow_pointer != fast_pointer) { 11 | slow_pointer = slow_pointer.next; 12 | fast_pointer = fast_pointer.next; 13 | } 14 | return slow_pointer; 15 | } 16 | } 17 | 18 | return null; 19 | }; 20 | -------------------------------------------------------------------------------- /Practice/LinkedList/RemoveDuplicatesFromSortedList.java: -------------------------------------------------------------------------------- 1 | 2 | //Definition for singly-linked list. 3 | class ListNode { 4 | public int val; 5 | public ListNode next; 6 | ListNode(int x) { val = x; next = null; } 7 | } 8 | 9 | 10 | public class RemoveDuplicatesFromSortedList { 11 | public ListNode deleteDuplicates(ListNode A) { 12 | ListNode currentNode = A; 13 | 14 | while(currentNode.next != null){ 15 | while(currentNode.val == currentNode.next.val && currentNode.next!= null && currentNode.next.next!= null) 16 | { 17 | currentNode.next = currentNode.next.next; 18 | } 19 | 20 | currentNode = currentNode.next; 21 | } 22 | 23 | return A; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /Practice/LinkedList/RemoveLoopFromLinkedList.js: -------------------------------------------------------------------------------- 1 | function RemoveLoopFromLinkedList(A) { 2 | if (A == null || A.next == null) return null; 3 | let slow_pointer = A; 4 | let fast_pointer = A; 5 | while (fast_pointer.next != null && fast_pointer.next.next != null) { 6 | slow_pointer = slow_pointer.next; 7 | fast_pointer = fast_pointer.next.next; 8 | if (slow_pointer == fast_pointer) { 9 | slow_pointer = A; 10 | let prev = null; 11 | while (slow_pointer != fast_pointer) { 12 | slow_pointer = slow_pointer.next; 13 | prev = fast_pointer; 14 | fast_pointer = fast_pointer.next; 15 | } 16 | prev.next = null; 17 | return A; 18 | } 19 | } 20 | 21 | return A; 22 | } 23 | -------------------------------------------------------------------------------- /Practice/LinkedList/ReverseLinkedList.js: -------------------------------------------------------------------------------- 1 | // Definition for singly-linked list. 2 | // function Node(data){ 3 | // this.data = data 4 | // this.next = null 5 | // } 6 | 7 | module.exports = { 8 | //param A : head node of linked list 9 | //return the head node in the linked list 10 | reverseList: function (A) { 11 | let prev = null; 12 | let currNode = A; 13 | while (currNode != null) { 14 | let nextNode = currNode.next; 15 | currNode.next = prev; 16 | prev = currNode; 17 | currNode = nextNode; 18 | } 19 | 20 | return prev; 21 | }, 22 | }; 23 | -------------------------------------------------------------------------------- /Practice/LinkedList/ReverseLinkedListII.js: -------------------------------------------------------------------------------- 1 | function Reverse(A, B, C) { 2 | if (A == null || B == C) return A; 3 | let nodeBeforeStart = A; 4 | let startNode = null; 5 | let swappingNode = null; 6 | 7 | if (B != 1) { 8 | let count = 1; 9 | while (count < B - 1) { 10 | nodeBeforeStart = nodeBeforeStart.next; 11 | count++; 12 | } 13 | startNode = nodeBeforeStart.next; 14 | } else { 15 | startNode = A; 16 | nodeBeforeStart = null; 17 | } 18 | let count = B; 19 | while (count < C) { 20 | swappingNode = startNode.next; 21 | startNode.next = swappingNode.next; 22 | if (B == 1) { 23 | swappingNode.next = A; 24 | A = swappingNode; 25 | // head = A; 26 | } else { 27 | swappingNode.next = nodeBeforeStart.next; 28 | nodeBeforeStart.next = swappingNode; 29 | } 30 | 31 | count++; 32 | // printLinkedList(); 33 | } 34 | return A; 35 | } 36 | -------------------------------------------------------------------------------- /Practice/LinkedList/Test.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/LinkedList/Test.js -------------------------------------------------------------------------------- /Practice/Maths/AandBModulo.java: -------------------------------------------------------------------------------- 1 | public class AandBModulo { 2 | public int solve(int A, int B) { 3 | return Math.abs(A - B); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Practice/Maths/AllGCDPairs.js: -------------------------------------------------------------------------------- 1 | A = [ 2 | 1, 31, 1, 1, 1, 1, 14, 2, 1, 1, 1, 2, 22, 1, 11, 1, 1, 1, 1, 23, 1, 1, 11, 1, 3 | 11, 4 | ]; 5 | function AllGCDPairs(A) { 6 | A.sort(function (x, y) { 7 | return y - x; 8 | }); 9 | let hs = new Map(); 10 | let output = []; 11 | 12 | for (const x of A) { 13 | if (hs.has(x)) { 14 | hs.set(x, hs.get(x) - 1); 15 | if (hs.get(x) == 0) hs.delete(x); 16 | } else { 17 | for (const y of output) { 18 | let gcd = GCD(x, y); 19 | hs.set(gcd, hs.has(gcd) ? hs.get(gcd) + 2 : 2); 20 | } 21 | output.push(x); 22 | } 23 | } 24 | 25 | return output; 26 | } 27 | 28 | function GCD(A, B) { 29 | if (B == 0) return A; 30 | 31 | return GCD(B, A % B); 32 | } 33 | 34 | console.log(AllGCDPairs(A)); 35 | -------------------------------------------------------------------------------- /Practice/Maths/DivisorGame.js: -------------------------------------------------------------------------------- 1 | function DivisorGame(A, B, C) { 2 | let LCM = (B * C) / GCD(B, C); 3 | let count = 1; 4 | for (let i = LCM; i <= A; i = LCM * count) { 5 | count++; 6 | } 7 | return count - 1; 8 | } 9 | 10 | function GCD(A, B) { 11 | if (B == 0) return A; 12 | return GCD(B, A % B); 13 | } 14 | 15 | let A = 81991; 16 | let B = 2549; 17 | let C = 7; 18 | 19 | console.log(DivisorGame(A, B, C)); 20 | -------------------------------------------------------------------------------- /Practice/Maths/ExcelColumnToNumber.java: -------------------------------------------------------------------------------- 1 | class ExcelColumnToNumber { 2 | public int titleToNumber(String A) { 3 | int col_index = 0; 4 | int pow = 0; 5 | for (int i = A.length() - 1; i >= 0; i--) { 6 | col_index += ((int) A.charAt(i) - 'A' + 1) * Math.pow(26, pow); 7 | pow++; 8 | } 9 | return col_index; 10 | } 11 | } -------------------------------------------------------------------------------- /Practice/Maths/LargestCoPrimeDivisor.js: -------------------------------------------------------------------------------- 1 | function LargestCoPrimeDivisor(A, B) { 2 | if (GCD(A, B) == 1) return A; 3 | let ans = 1; 4 | for (let i = 2; i * i <= A; i++) { 5 | if (A % i == 0) { 6 | if (GCD(B, i) == 1) ans = i; 7 | let fact2 = A / i; 8 | if (GCD(B, fact2) == 1) return fact2; 9 | } 10 | } 11 | 12 | return ans; 13 | } 14 | 15 | function GCD(A, B) { 16 | if (B == 0) return A; 17 | return GCD(B, A % B); 18 | } 19 | 20 | let A = 30; 21 | let B = 12; 22 | 23 | console.log(LargestCoPrimeDivisor(A, B)); 24 | -------------------------------------------------------------------------------- /Practice/Maths/MagicNumberBase2.java: -------------------------------------------------------------------------------- 1 | public class MagicNumberBase2 { 2 | public static void NthMagicNumber() { 3 | int N = 10; 4 | int pow = 1; 5 | int ans = 0; 6 | 7 | while(N>0) { 8 | if((N & 1) == 1) { 9 | ans += Math.pow(5, pow); 10 | } 11 | pow++; 12 | N = N>>1; 13 | } 14 | 15 | System.out.println(ans); 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Practice/Maths/MagicNumberBase3.java: -------------------------------------------------------------------------------- 1 | public void MagicNumber() { 2 | int[] A = {2,1,2}; 3 | 4 | 5 | int l = A.length/2; 6 | int first =0; 7 | int count1 = 0; 8 | for(int i=0;i l) System.out.println(first); 28 | } -------------------------------------------------------------------------------- /Practice/Maths/ModString.java: -------------------------------------------------------------------------------- 1 | public class ModString { 2 | public int findMod(String A, int B) { 3 | int ans = 0; 4 | long pow = 1; 5 | long result = 0; 6 | for(int i=A.length()-1;i>=0;i--){ 7 | result = (Integer.parseInt(A.substring(i, i+1))%B * pow%B)%B; 8 | ans = (ans%B+(int)result%B)%B; 9 | pow = (pow%B*10%B)%B; 10 | } 11 | 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Practice/Maths/SortedPermutationRank.js: -------------------------------------------------------------------------------- 1 | function SortedPermutationRank(A) { 2 | let mod = 1000003; 3 | let ans = 0; 4 | 5 | for (let i = 0; i < A.length; i++) { 6 | let count = 0; 7 | for (let j = i + 1; j < A.length; j++) { 8 | if (A[j] < A[i]) { 9 | count++; 10 | } 11 | } 12 | ans += count * fact(A.length - i - 1, mod); 13 | } 14 | 15 | return (ans + 1) % mod; 16 | } 17 | 18 | function fact(N, mod) { 19 | let ans = 1; 20 | while (N > 0) { 21 | ans *= N; 22 | ans = ans % mod; 23 | N--; 24 | } 25 | 26 | return ans; 27 | } 28 | let A = "gTFAMYjxCewRlftmGOKJHUy"; 29 | 30 | console.log(SortedPermutationRank(A)); 31 | //831052 32 | -------------------------------------------------------------------------------- /Practice/Patterns.js: -------------------------------------------------------------------------------- 1 | function divider() 2 | { 3 | console.log('---------------------------------------------------') 4 | } 5 | 6 | l = 10 7 | b = 5 8 | 9 | //Solid Rectangle 10 | for(i=0;i output = new ArrayList<>(); 7 | 8 | int length = 1; 9 | int[] A = {0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4}; 10 | output.add(A[0]); 11 | for (int i = 1; i < A.length; i++) { 12 | if (A[i] != A[i - 1]) { 13 | length++; 14 | output.add(A[i]); 15 | } 16 | } 17 | 18 | System.out.println(length); 19 | for (int x : output) { 20 | System.out.print(x + " "); 21 | } 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /Practice/ProblemSolving1stClass/Javascript/AtLeastTwoGreaterElements.js: -------------------------------------------------------------------------------- 1 | A = [11, 17, 100, 5] 2 | 3 | console.log(AtLeastTwoGreaterElement(A)) 4 | function AtLeastTwoGreaterElement(A){ 5 | max = A[0] 6 | max2 = Number.MIN_SAFE_INTEGER 7 | 8 | for(i = 1; i < A.length;i++){ 9 | if(A[i]> max){ 10 | temp = max 11 | max = A[i] 12 | max2 = temp 13 | } 14 | else if(max2 < A[i]){ 15 | max2 = A[i] 16 | } 17 | 18 | } 19 | 20 | maxIndex = A.indexOf(max) 21 | A.splice(maxIndex,1) 22 | max2Index = A.indexOf(max2) 23 | A.splice(max2Index,1) 24 | 25 | return A 26 | } -------------------------------------------------------------------------------- /Practice/ProblemSolving1stClass/Javascript/OddEvenDifference.js: -------------------------------------------------------------------------------- 1 | A = [5, 17, 100, 1] 2 | 3 | console.log(Difference(A)) 4 | function Difference(A){ 5 | even = Number.MIN_SAFE_INTEGER 6 | odd = Number.MAX_SAFE_INTEGER 7 | 8 | for(i = 0; i < A.length;i++){ 9 | if(A[i]%2 == 0){ 10 | even = Math.max(even,A[i]) 11 | } 12 | else{ 13 | odd = Math.min(A[i], odd) 14 | } 15 | } 16 | 17 | return even - odd 18 | 19 | } -------------------------------------------------------------------------------- /Practice/ProblemSolving1stClass/Javascript/PatternPrinting.js: -------------------------------------------------------------------------------- 1 | A = 3 2 | 3 | console.log(PatterPrinting(A)) 4 | 5 | function PatterPrinting(A){ 6 | farr = [] 7 | for(i = 0; i < A; i++ ){ 8 | arr = [] 9 | 10 | for(j= 0; j < A;j++){ 11 | 12 | arr.push((j<=i? j+1: 0)) 13 | } 14 | 15 | farr.push(arr) 16 | } 17 | 18 | return farr 19 | } -------------------------------------------------------------------------------- /Practice/ProblemSolving1stClass/Javascript/StrictlySmallerAndGreater.js: -------------------------------------------------------------------------------- 1 | A = [ 913, 440, 865, 72, 612, 445, 101, 994, 356, 91, 461, 930, 583, 448, 543, 170, 333, 107, 425, 73, 172, 416, 899, 826, 659, 561, 314, 25, 110 ] 2 | console.log(StrictlySmallerAndGreater(A)) 3 | function StrictlySmallerAndGreater(A){ 4 | 5 | max = Number.MIN_SAFE_INTEGER 6 | counter = 0 7 | min = Number.MAX_SAFE_INTEGER 8 | 9 | 10 | for(i = 0; i < A.length; i ++){ 11 | max = Math.max(A[i],max) 12 | min = Math.min(A[i],min) 13 | } 14 | 15 | for(i=0;i min && A[i] < max){ 17 | counter++ 18 | } 19 | } 20 | return counter 21 | 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /Practice/ProblemSolving1stClass/Lecture 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/ProblemSolving1stClass/Lecture 1.pdf -------------------------------------------------------------------------------- /Practice/Queues/FirstNonRepeatingCharacter.js: -------------------------------------------------------------------------------- 1 | function FirstNonRepeatingCharacter(A) { 2 | let deque = []; 3 | deque.push(A[0]); 4 | let outputString = ""; 5 | outputString += A[0]; 6 | let hm = {}; 7 | hm[A[0]] = 1; 8 | for (let i = 1; i < A.length; i++) { 9 | let val = A[i]; 10 | if (val == deque[0]) { 11 | deque.shift(); 12 | hm[val] = hm[val] + 1; 13 | } else { 14 | deque.push(val); 15 | if (hm[val] != null) { 16 | hm[val] = hm[val] + 1; 17 | } else { 18 | hm[val] = 1; 19 | } 20 | } 21 | while (hm[deque[0]] > 1) { 22 | deque.shift(); 23 | } 24 | if (deque.length > 0) { 25 | outputString += deque[0]; 26 | } else outputString += "#"; 27 | } 28 | 29 | return outputString; 30 | } 31 | 32 | A = "rzgbjnrbriuqwcbgndnqiddjzpbglrkzhclejgih"; 33 | 34 | console.log(FirstNonRepeatingCharacter(A)); 35 | -------------------------------------------------------------------------------- /Practice/Queues/NIntegersContaining123.js: -------------------------------------------------------------------------------- 1 | function NIntegersContaining123(A) { 2 | let arr = []; 3 | let count = 0; 4 | let l = -1; 5 | 6 | while (count < A) { 7 | num1 = (l == -1 ? 0 : arr[l] * 10) + 1; 8 | arr.push(num1); 9 | count++; 10 | if (count == A) { 11 | return arr; 12 | } 13 | num2 = (l == -1 ? 0 : arr[l] * 10) + 2; 14 | arr.push(num2); 15 | count++; 16 | if (count == A) { 17 | return arr; 18 | } 19 | 20 | num3 = (l == -1 ? 0 : arr[l] * 10) + 3; 21 | arr.push(num3); 22 | count++; 23 | 24 | l++; 25 | } 26 | return arr; 27 | } 28 | 29 | console.log(NIntegersContaining123(9)); 30 | -------------------------------------------------------------------------------- /Practice/Queues/SlidingWindowMaximum.js: -------------------------------------------------------------------------------- 1 | function slidingMaximum(A, B) { 2 | let output = []; 3 | let deque = []; 4 | for (let i = 0; i < B; i++) { 5 | let l = deque.length; 6 | while (l && deque[l - 1] < A[i]) { 7 | deque.pop(); 8 | l--; 9 | } 10 | deque.push(A[i]); 11 | } 12 | output.push(deque[0]); 13 | 14 | for (let i = B; i < A.length; i++) { 15 | if (deque[0] == A[i - B]) { 16 | deque.shift(); 17 | } 18 | let l = deque.length; 19 | while (l && deque[l - 1] < A[i]) { 20 | deque.pop(); 21 | l--; 22 | } 23 | deque.push(A[i]); 24 | output.push(deque[0]); 25 | } 26 | 27 | return output; 28 | } 29 | 30 | A = [1, 3, -1, -3, 5, 3, 6, 7]; 31 | B = 3; 32 | 33 | console.log(slidingMaximum(A, B)); 34 | -------------------------------------------------------------------------------- /Practice/Queues/TaskScheduler.js: -------------------------------------------------------------------------------- 1 | function TaskScheduler(A, B) { 2 | let tasks = 0; 3 | let l = 0; 4 | let n = A.length; 5 | for (let i = 0; i < B.length; i++) { 6 | let current_task = B[i]; 7 | while (A[l] != current_task) { 8 | if (A[l] != 0) { 9 | tasks++; 10 | } 11 | l = (l + 1) % n; 12 | } 13 | A[l] = 0; 14 | l = (l + 1) % n; 15 | tasks++; 16 | } 17 | 18 | return tasks; 19 | } 20 | A = [2, 3, 1, 5, 4]; 21 | B = [1, 3, 5, 4, 2]; 22 | 23 | console.log(TaskScheduler(A, B)); 24 | -------------------------------------------------------------------------------- /Practice/RandomPractice/HCF.java: -------------------------------------------------------------------------------- 1 | package RandomPractice; 2 | 3 | public class HCF { 4 | 5 | public FindHCF(int num1, int num2) { 6 | 7 | int HCF = 1; 8 | 9 | for (int i = 2; i <= Math.sqrt(Math.max(num1, num2)); i++) { 10 | if (num1 % i == 0 && num2 % i == 0) { 11 | HCF *= i; 12 | num1 = num1 / i; 13 | num2 = num2 / i; 14 | i = 1; 15 | } 16 | } 17 | 18 | System.out.println(HCF); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Practice/Recursion/CheckPalindrome.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Solution: 4 | # @param A : string 5 | # @return an integer 6 | 7 | sys.setrecursionlimit(10**6) 8 | def solve(self, A): 9 | return checkPalindrome(A,0,len(A)-1) 10 | 11 | 12 | def checkPalindrome(A,s,e): 13 | if s>e: 14 | return 1 15 | if A[s] == A[e]: 16 | return checkPalindrome(A,s+1,e-1) 17 | else: 18 | return 0 19 | 20 | -------------------------------------------------------------------------------- /Practice/Recursion/FindFactorial.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return an integer 4 | def solve(self, A): 5 | return fact(A) 6 | 7 | 8 | def fact(A): 9 | 10 | if A == 0: 11 | return 1 12 | 13 | return fact(A-1) * A -------------------------------------------------------------------------------- /Practice/Recursion/FindFibonacci.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return an integer 4 | def findAthFibonacci(self, A): 5 | return getFibValue(A) 6 | 7 | 8 | def getFibValue(A): 9 | 10 | if(A==0): 11 | return 0 12 | 13 | if(A>0 and A<=2): 14 | return 1 15 | 16 | return getFibValue(A-1) + getFibValue(A-2) 17 | -------------------------------------------------------------------------------- /Practice/Recursion/GrayCode.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList grayCode(int a) { 3 | ArrayList res = new ArrayList(); 4 | res.add(0); 5 | Set set = new HashSet<>(); 6 | set.add(0); 7 | dfs(res, a, set); 8 | return res; 9 | } 10 | 11 | private void dfs(ArrayList res, int n, Set set) { 12 | if (res.size() == (1 << n)) return; 13 | 14 | int prev = 0, cur = 0; 15 | for (int i = 0; i < n; i++) { 16 | prev = res.get(res.size() - 1); 17 | cur = prev ^ (1 << i); 18 | if (!set.contains(cur)) { 19 | set.add(cur); 20 | res.add(cur); 21 | dfs(res, n, set); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Practice/Recursion/GrayCode.py: -------------------------------------------------------------------------------- 1 | A = 3 2 | length = pow(2,A) 3 | output = [0] 4 | val = 0 5 | j = 0 6 | for i in range(0,length-1): 7 | if i%2 != 0 or i == 0 or i == 1: 8 | val = val + (1< 9) { 5 | A = sumOfDigits(A); 6 | } 7 | 8 | if (A == 1) 9 | return 1; 10 | return 0; 11 | } 12 | 13 | public int sumOfDigits(int N) { 14 | if (N == 0) 15 | return 0; 16 | 17 | return sumOfDigits(N / 10) + N % 10; 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Practice/Recursion/K Occurences.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @param B : integer 4 | # @param C : list of integers 5 | # @return an integer 6 | def getSum(self, A, B, C): 7 | dict = {} 8 | sum = 0 9 | isElementFound = False 10 | for i in range(0,A): 11 | if dict.get(C[i]) is not None: 12 | dict[C[i]] = dict.get(C[i]) + 1 13 | else: 14 | dict[C[i]] = 1 15 | 16 | 17 | for ele in dict: 18 | if dict.get(ele) == B: 19 | isElementFound = True 20 | sum += ele 21 | 22 | if isElementFound: 23 | return sum 24 | 25 | return -1 26 | 27 | -------------------------------------------------------------------------------- /Practice/Recursion/KthSymbol.py: -------------------------------------------------------------------------------- 1 | A = 2 2 | B = 1 3 | val = '0' 4 | count = 1 5 | 6 | while count s = new HashSet<>(); 8 | int count = 0; 9 | for (int i : A) { 10 | if (s.contains(i)) { 11 | count++; 12 | } else { 13 | s.add(i); 14 | } 15 | } 16 | 17 | return count; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Practice/Revision2ndOctober/MaxEvenMinOddDiff.java: -------------------------------------------------------------------------------- 1 | class MaxEvenMinOddDiff { 2 | public static int DiffBetweenEvenAndOdd() { 3 | int[] A = {0, 2, 9}; 4 | int even_max = Integer.MIN_VALUE; 5 | int odd_min = Integer.MAX_VALUE; 6 | 7 | for (int i : A) { 8 | if (i % 2 == 0) { 9 | if (i > even_max) { 10 | even_max = i; 11 | } 12 | } else if (i % 2 != 0) { 13 | if (i < odd_min) { 14 | odd_min = i; 15 | } 16 | } 17 | } 18 | 19 | return even_max - odd_min; 20 | } 21 | } -------------------------------------------------------------------------------- /Practice/Revision2ndOctober/NumberOfBits.java: -------------------------------------------------------------------------------- 1 | class NumberOfBits { 2 | public NumberOfBits() { 3 | int A = 15; 4 | int count = 0; 5 | while (A > 0) { 6 | count++; 7 | A = A & (A - 1); 8 | } 9 | 10 | System.out.println(count); 11 | } 12 | } -------------------------------------------------------------------------------- /Practice/Revision2ndOctober/Pattern1.java: -------------------------------------------------------------------------------- 1 | class Pattern1 { 2 | public static int[][] PrintPattern1() { 3 | int A = 3; 4 | int[][] output = new int[A][A]; 5 | for ( 6 | int i = 1; 7 | i <= A; i++) { 8 | for (int j = 1; j <= A; j++) { 9 | if (j <= i) { 10 | output[i - 1][j - 1] = j; 11 | } 12 | } 13 | 14 | } 15 | 16 | return output; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Practice/Revision2ndOctober/StrictlySmallerAndGreater.java: -------------------------------------------------------------------------------- 1 | class StrictlySmallerAndGreater { 2 | public static int SmallerAndGreater(int[] A) { 3 | 4 | int max = A[0]; 5 | int min = A[0]; 6 | int count = 0; 7 | for (int i = 1; i < A.length; i++) { 8 | if (A[i] > max) { 9 | max = A[i]; 10 | } else if (A[i] < min) { 11 | min = A[i]; 12 | } 13 | } 14 | 15 | for (int i : A) { 16 | if (i < max && i > min) { 17 | count++; 18 | } 19 | } 20 | return count; 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /Practice/Revision2ndOctober/TwoGreaterElement.java: -------------------------------------------------------------------------------- 1 | class TwoGreaterElement { 2 | public static int[] TwoGreaterElements(int[] A) { 3 | 4 | int L = A.length; 5 | int[] output = new int[L - 2]; 6 | 7 | int first_max = Integer.MIN_VALUE; 8 | int second_max = Integer.MIN_VALUE; 9 | 10 | for (int value : A) { 11 | if (value > first_max) { 12 | second_max = first_max; 13 | first_max = value; 14 | } else if (value > second_max) { 15 | second_max = value; 16 | } 17 | } 18 | int j = 0; 19 | for (int k : A) { 20 | if (k < second_max) { 21 | output[j] = k; 22 | j++; 23 | } 24 | } 25 | return output; 26 | } 27 | } -------------------------------------------------------------------------------- /Practice/RockPaperScissor.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/RockPaperScissor.js -------------------------------------------------------------------------------- /Practice/Stack/BalancedParanthesis.js: -------------------------------------------------------------------------------- 1 | let BalancedParanthesis = function (str) { 2 | let stack = []; 3 | for (const c of str) { 4 | if (`[({`.includes(c)) { 5 | stack.push(c); 6 | } else if (c == `]`) { 7 | if (stack.length == 0 || stack[stack.length - 1] != `[`) return 0; 8 | stack.pop(); 9 | } else if (c == `}`) { 10 | if (stack.length == 0 || stack[stack.length - 1] != `{`) return 0; 11 | stack.pop(); 12 | } else if (c == `)`) { 13 | if (stack.length == 0 || stack[stack.length - 1] != `(`) return 0; 14 | stack.pop(); 15 | } 16 | } 17 | 18 | if (stack.length > 0) return 0; 19 | return 1; 20 | }; 21 | let str = `(((((((`; 22 | console.log(str); 23 | console.log(BalancedParanthesis(str)); 24 | -------------------------------------------------------------------------------- /Practice/Stack/DivisibilityTest.js: -------------------------------------------------------------------------------- 1 | A = "3030300"; 2 | 3 | function divisibilityTest(A) { 4 | if (A.charAt(A.length - 1) != "0") return 0; 5 | let s = A.substring(0, A.length - 1); 6 | let sum = 0; 7 | for (let i = 0; i < s.length; i++) { 8 | sum += Number(A.charAt(i)); 9 | } 10 | 11 | if (sum % 3 == 0) return 1; 12 | return 0; 13 | } 14 | 15 | console.log(divisibilityTest(A)); 16 | -------------------------------------------------------------------------------- /Practice/Stack/DoubleCharacterTrouble.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class DoubleCharacterTrouble { 4 | public String solve(String A) { 5 | Stack stack = new Stack<>(); 6 | 7 | for (int i = 0; i < A.length(); i++) { 8 | char currentValue = A.charAt(i); 9 | if (!stack.isEmpty() && stack.peek() == currentValue) { 10 | stack.pop(); 11 | } else { 12 | stack.push(currentValue); 13 | } 14 | } 15 | StringBuilder output = new StringBuilder(); 16 | while (!stack.isEmpty()) { 17 | output.insert(0, stack.pop()); 18 | } 19 | 20 | return output.toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /Practice/Stack/DoubleCharacterTrouble.js: -------------------------------------------------------------------------------- 1 | let DoubleCharacterTrouble = function (A) { 2 | let stack = []; 3 | for (const c of A) { 4 | if (stack.length == 0) stack.push(c); 5 | else { 6 | let top = stack[stack.length - 1]; 7 | if (top == c) { 8 | stack.pop(); 9 | } else stack.push(c); 10 | } 11 | } 12 | 13 | return stack.join(""); 14 | }; 15 | 16 | let str = `abbabbcd`; 17 | console.log(DoubleCharacterTrouble(str)); 18 | -------------------------------------------------------------------------------- /Practice/Stack/NearestSmallestElement.js: -------------------------------------------------------------------------------- 1 | function NearestSmallestElement(A) { 2 | let stack = []; 3 | let output = []; 4 | for (let i = 0; i < A.length; i++) { 5 | let top = findTop(stack); 6 | if (top != null) { 7 | while (top >= A[i]) { 8 | stack.pop(); 9 | top = findTop(stack); 10 | } 11 | output.push(top == null ? -1 : top); 12 | } else { 13 | output.push(-1); 14 | } 15 | stack.push(A[i]); 16 | } 17 | return output; 18 | } 19 | 20 | function findTop(stack) { 21 | if (stack.length == 0) return null; 22 | return stack[stack.length - 1]; 23 | } 24 | A = [4, 5, 2, 10, 8]; 25 | 26 | console.log(NearestSmallestElement(A)); 27 | -------------------------------------------------------------------------------- /Practice/Stack/PassingGame.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Stack; 3 | 4 | public class PassingGame { 5 | public int solve(int A, int B, ArrayList C) { 6 | Stack stack = new Stack(); 7 | stack.push(B); 8 | for(int i=0;i R) { 9 | R = i; 10 | L = i; 11 | while (i < s.length && s[R] == s[R - L]) R++; 12 | z.push(R - L); 13 | R--; 14 | } else if (z[i - L] < R - i + 1) { 15 | z[i] = z[i - L]; 16 | } else { 17 | L = i; 18 | while (i < s.length && s[R] == s[R - L]) R++; 19 | z.push(R - L); 20 | R--; 21 | } 22 | } 23 | 24 | let l = B.length; 25 | let ans = 0; 26 | for (let i = 0; i < z.length; i++) { 27 | if (z[i] == l) ans++; 28 | } 29 | if (A == B) return ans - 1; 30 | return ans; 31 | } 32 | let A = "0111111111"; 33 | let B = "1111111101"; 34 | 35 | console.log(CyclicPermutation(A, B)); 36 | -------------------------------------------------------------------------------- /Practice/String Pattern Matching/PeriodOfAString.js: -------------------------------------------------------------------------------- 1 | function PeriodOfAString(A) { 2 | let s = A; 3 | let z = [s.length]; 4 | let L = 0; 5 | let R = 0; 6 | 7 | for (let i = 1; i < s.length; i++) { 8 | if (i > R) { 9 | L = i; 10 | R = i; 11 | while (R < s.length && s[R] == s[R - L]) R++; 12 | z.push(R - L); 13 | R--; 14 | } else if (z[i - L] < R - i + 1) { 15 | z[i] = z[i - L]; 16 | } else { 17 | L = i; 18 | while (R < s.length && s[R] == s[R - L]) R++; 19 | z.push(R - L); 20 | R--; 21 | } 22 | } 23 | console.log(z); 24 | for (let i = 1; i < z.length; i++) { 25 | if (z[i] + i == A.length) return i; 26 | } 27 | 28 | return A.length; 29 | } 30 | 31 | A = "abababababb"; 32 | console.log(PeriodOfAString(A)); 33 | -------------------------------------------------------------------------------- /Practice/Strings/ColorFulNumber.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int colorful(int A) { 3 | if (A <10) return 1; 4 | 5 | HashSet hs = new HashSet(); 6 | 7 | String s = Integer.toString(A); 8 | 9 | for(int i=0;i0){ 15 | mul = mul * (val%10); 16 | val = val/10; 17 | } 18 | 19 | if(hs.contains(mul)){ 20 | return 0; 21 | } 22 | hs.add(mul); 23 | 24 | } 25 | } 26 | 27 | return 1; 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Practice/Strings/ConcatenatingNumbers.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int solve(int A, int B, int C) { 3 | String a = Integer.toString(A); 4 | String b = Integer.toString(B); 5 | String c = Integer.toString(C); 6 | 7 | if (A<=B && B<=C) return Integer.parseInt(a+b+c); 8 | 9 | else if (B<=A && A<=C) return Integer.parseInt(b + a + c); 10 | 11 | else if (C<=A && A<=B) return Integer.parseInt(c+a+b); 12 | 13 | else if (C<=B && B<=A) return Integer.parseInt(c+b+a); 14 | 15 | else if (A<=C && C<=B) return Integer.parseInt(a+c+b); 16 | 17 | else return Integer.parseInt(b+c+a); 18 | 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Practice/Strings/ConvertToLower.py: -------------------------------------------------------------------------------- 1 | A = ['S', 'c', 'A', 'l', 'e', 'r', 'A', 'c', 'a', 'D', 'e', 'm', 'y'] 2 | 3 | for i in range(0, len(A)): 4 | ch = ord(A[i]) 5 | if ch > 64 and ch < 91: 6 | A[i] = chr(ch + 32) 7 | print(A) -------------------------------------------------------------------------------- /Practice/Strings/CountUniqueXORPairs.py: -------------------------------------------------------------------------------- 1 | A = [3, 6, 8, 10, 15, 50] 2 | B = 5 3 | 4 | 5 | hs = set() 6 | 7 | count = 0 8 | for item in A: 9 | xor_val = B^item 10 | if xor_val in hs: 11 | count += 1 12 | else: 13 | hs.add(item) 14 | 15 | print(count) 16 | -------------------------------------------------------------------------------- /Practice/Strings/IsAlpha.py: -------------------------------------------------------------------------------- 1 | A = [ "S", "c", "A", "L", "E", "r", "A", "c", "a", "D", "e", "m", "y" ] 2 | 3 | for i in range(0,len(A)): 4 | if ord(A[i]) in range(97,123): 5 | A[i] = chr(ord(A[i])-32) 6 | print(A) -------------------------------------------------------------------------------- /Practice/Strings/IsPalindromeByRearranging.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : string 3 | # @return an integer 4 | def solve(self, A): 5 | hs = set() 6 | for i in range(0,len(A)): 7 | hs.add(A[i]) 8 | 9 | if len(A) == 1: return 1 10 | if len(A)%2 == 0: 11 | for val in hs: 12 | if A.count(val)%2 != 0: 13 | return 0 14 | return 1 15 | else: 16 | count = 0 17 | for val in hs: 18 | if A.count(val)%2 != 0: 19 | count+=1 20 | if count > 1: 21 | return 0 22 | return 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /Practice/Strings/ReverseSingleString.py: -------------------------------------------------------------------------------- 1 | A = 'Sagar' 2 | output = "" 3 | for i in range(0,len(A)): 4 | output = A[i] + output 5 | 6 | return output -------------------------------------------------------------------------------- /Practice/Strings/ReverseString.py: -------------------------------------------------------------------------------- 1 | A = "tihx dnwrmmby fa x tejuftd lrjixyiui lwvzp eymuxx" 2 | output = "" 3 | 4 | final = "" 5 | i = 0 6 | j = len(A) -1 7 | for i in range(0,len(A)): 8 | output = A[i] + output 9 | 10 | print(A.index(' ')) 11 | print(output) 12 | 13 | p1 = 0 14 | p2 = 0 15 | isLastWord = False 16 | while(not isLastWord): 17 | p1 = 0 18 | p2 = 0 19 | B = "" 20 | if ' ' in output: 21 | p2 = output.index(' ') 22 | else: 23 | isLastWord = True 24 | p2 = len(output) 25 | 26 | for i in range(p1,p2): 27 | B = output[i] + B 28 | 29 | final = final + B + ' ' 30 | output = output[p2+1:] 31 | 32 | print(final.strip()) 33 | 34 | 35 | #hv xdq op qoddptokkz vemmoxrgf ombt gg crulgzfkif 36 | #hv xdq op qoddptokkz vemmoxrgf ombt gg crulgzfkif 37 | -------------------------------------------------------------------------------- /Practice/Test.js: -------------------------------------------------------------------------------- 1 | factB = 1 2 | mod = 1000000007 3 | for( i=1;i<=3;i++){ 4 | factB = (factB%mod * i%mod)%mod; 5 | 6 | } 7 | console.log(factB) 8 | console.log(Math.pow(2,factB)) -------------------------------------------------------------------------------- /Practice/Trees/BSTNodeInARange.js: -------------------------------------------------------------------------------- 1 | function BSTNodeInARange(A, B, C) { 2 | let count = 0; 3 | NodesInRange(A, B, C); 4 | return count; 5 | function NodesInRange(A) { 6 | if (!A) return; 7 | 8 | if (A.data < B) NodesInRange(A.right); 9 | else if (A.data > C) NodesInRange(A.left); 10 | else { 11 | count++; 12 | NodesInRange(A.left); 13 | NodesInRange(A.right); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Practice/Trees/BalancedBinaryTree.cs: -------------------------------------------------------------------------------- 1 | public int isBalanced(TreeNode A) { 2 | int ans = 1; 3 | CheckBBT(A,ref ans); 4 | return ans; 5 | } 6 | 7 | public int CheckBBT(TreeNode node,ref int ans){ 8 | if(node == null){ 9 | return -1; 10 | } 11 | 12 | int leftHeight = CheckBBT(node.left,ref ans); 13 | int rightHeight = CheckBBT(node.right,ref ans); 14 | 15 | if(Math.Abs(leftHeight - rightHeight) > 1) { 16 | ans = 0; 17 | } 18 | 19 | return Math.Max(leftHeight,rightHeight) + 1; 20 | } -------------------------------------------------------------------------------- /Practice/Trees/BinaryTreeFromInorderAndPreorder.js: -------------------------------------------------------------------------------- 1 | const BinaryTreeFromInorderAndPreorder = (A,B) => { 2 | 3 | 4 | 5 | const Construct = (A,s,e, B, i, j) => { 6 | 7 | 8 | let index = -1; 9 | for(let k=i;k<=j;k++){ 10 | if(B[k] == A[s]){ 11 | index = k; 12 | break; 13 | } 14 | } 15 | let x = index - i; 16 | let root = new TreeNode(A[s]); 17 | root.left = Construct(A,s+1,s+x,B,i,index -1); 18 | root.right = Construct(A,s+x+1,e,B,index+1,j); 19 | return root; 20 | } 21 | } -------------------------------------------------------------------------------- /Practice/Trees/BoundaryTraversalOfBinaryTree.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Trees/BoundaryTraversalOfBinaryTree.java -------------------------------------------------------------------------------- /Practice/Trees/CheckForBSTWithOneChild.js: -------------------------------------------------------------------------------- 1 | const A = [12, 1, 9, 6, 2]; 2 | function CheckForBSTWithOneChild(A) { 3 | if(A <=1) return "YES"; 4 | let leftLimit = Number.MIN_SAFE_INTEGER; 5 | let rightLimit = Number.MAX_SAFE_INTEGER; 6 | 7 | for(let i=1;i rightLimit) return "NO"; 9 | if(A[i] > A[i-1]){ 10 | leftLimit = A[i-1]; 11 | } 12 | else{ 13 | rightLimit = A[i-1]; 14 | } 15 | } 16 | 17 | return "YES"; 18 | } 19 | 20 | console.log(CheckForBSTWithOneChild(A)); 21 | -------------------------------------------------------------------------------- /Practice/Trees/CommonNodesInTwoBST.js: -------------------------------------------------------------------------------- 1 | function CommonNodesInTwoBST() { 2 | inorderA = []; 3 | inorderB = []; 4 | let mod = 1000000007; 5 | let sum = 0; 6 | inorderA = InorderTraversal(A, inorderA); 7 | inorderB = InorderTraversal(B, inorderB); 8 | 9 | let hs = new Set(inorderA); 10 | 11 | for (let i = 0; i < inorderB.length; i++) { 12 | if (hs.has(inorderB[i])) { 13 | sum = ((sum % mod) + (inorderB[i] % mod)) % mod; 14 | } 15 | } 16 | 17 | return sum; 18 | } 19 | 20 | function InorderTraversal(A, output) { 21 | if (A == null) return; 22 | 23 | InorderTraversal(A.left, output); 24 | output.push(A.data); 25 | InorderTraversal(A.right, output); 26 | 27 | return output; 28 | } 29 | -------------------------------------------------------------------------------- /Practice/Trees/DeserializeBinaryTree.js: -------------------------------------------------------------------------------- 1 | function DeserializeBinaryTree(A) { 2 | let arr = []; 3 | 4 | for (let i = 0; i < A.length; i++) { 5 | if (A[i] != -1) { 6 | arr.push(new TreeNode(A[i])); 7 | } else arr.push(-1); 8 | } 9 | 10 | let j = 1; 11 | 12 | for (let i = 0; i < arr.length; i++) { 13 | if (arr[i] == -1) continue; 14 | if (arr[j] != -1) { 15 | arr[i].left = arr[j++]; 16 | } else j++; 17 | 18 | if (arr[j] != -1) { 19 | arr[i].right = arr[j++]; 20 | } else j++; 21 | } 22 | 23 | return arr[0]; 24 | } 25 | -------------------------------------------------------------------------------- /Practice/Trees/DiameterOfATree.js: -------------------------------------------------------------------------------- 1 | let diameter = 0; 2 | 3 | function DiameterOfATree(root) { 4 | if (root == null) return -1; 5 | 6 | let leftHeight = DiameterOfATree(root.left); 7 | let rightHeight = DiameterOfATree(root.right); 8 | 9 | diameter = Math.max(diameter, leftHeight + rightHeight + 2); 10 | 11 | return Math.max(leftHeight, rightHeight) + 1; 12 | } 13 | DiameterOfATree(A); 14 | console.log(diameter); 15 | -------------------------------------------------------------------------------- /Practice/Trees/EqualTreePartition.js: -------------------------------------------------------------------------------- 1 | function EqualTreePartition(A) { 2 | let totalSum = 0; 3 | let hs = new Set(); 4 | Sum(A); 5 | function Sum(A) { 6 | if (A == null) return 0; 7 | let leftSum = Sum(A.left); 8 | let rightSum = Sum(A.right); 9 | totalSum = leftSum + rightSum + A.data; 10 | hs.add(totalSum); 11 | return totalSum; 12 | } 13 | if (totalSum == 0 || totalSum % 2 != 0) return 0; 14 | if (hs.has(Math.floor(totalSum / 2))) return 1; 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /Practice/Trees/InvertBinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ScalerPractice.Trees 8 | { 9 | internal class InvertBinaryTree 10 | { 11 | public TreeNode InvertTree(TreeNode A) 12 | { 13 | if (A == null) 14 | { 15 | return null; 16 | } 17 | 18 | InvertTree(A.Left); 19 | InvertTree(A.Right); 20 | TreeNode temp = A.Left; 21 | A.Left = A.Right; 22 | A.Right = temp; 23 | 24 | 25 | 26 | return A; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Practice/Trees/KthSmallestElementInBst.js: -------------------------------------------------------------------------------- 1 | function KthSmallestElementInBst(A,B){ 2 | let output = []; 3 | InorderTraversal(A); 4 | return output[B-1]; 5 | function InorderTraversal(A){ 6 | if (A == null) return; 7 | 8 | InorderTraversal(A.left); 9 | output.push(A.data); 10 | InorderTraversal(A.right); 11 | } 12 | } -------------------------------------------------------------------------------- /Practice/Trees/LeastCommonAncestor.js: -------------------------------------------------------------------------------- 1 | function LeastCommonAncestor(A,B,C){ 2 | if(A == null) return false; 3 | 4 | let leftNode = LeastCommonAncestor(A.left,B,C); 5 | let rightNode = LeastCommonAncestor(A.right,B,C); 6 | 7 | 8 | // if both nodes are found 9 | if(leftNode && rightNode){ 10 | ans = A.data; 11 | } 12 | 13 | //if one value is current node and the other is coming either from left or right 14 | if((leftNode || rightNode) && (A.data == B || A.data == C)){ 15 | ans = A.data; 16 | } 17 | 18 | //if both values are same and found 19 | if(A.data == B && A.data == C){ 20 | ans = A.data; 21 | } 22 | 23 | //if either is found return true 24 | if(A.data == B || A.data == C) return true; 25 | 26 | return leftNode || rightNode; 27 | } -------------------------------------------------------------------------------- /Practice/Trees/LeftViewOfBinaryTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * We construct a level order tree and print first value from each level 3 | * @param {Root of binary Tree} A 4 | * @returns leftView 5 | */ 6 | 7 | function LeftViewBinaryTree(A) { 8 | let output = []; 9 | if (!A.left && !A.right) { 10 | let curr_output = [A.data]; 11 | output.push(curr_output); 12 | return output; 13 | } 14 | let queue = [A]; 15 | 16 | while (queue.length) { 17 | let len = queue.length; 18 | output.push(queue.map((node) => node.data)); 19 | 20 | while (len--) { 21 | let node = queue.shift(); 22 | if (node.left) queue.push(node.left); 23 | if (node.right) queue.push(node.right); 24 | } 25 | } 26 | let leftview = []; 27 | for (const x of output) { 28 | leftview.push(x[0]); 29 | } 30 | 31 | return leftview; 32 | } 33 | -------------------------------------------------------------------------------- /Practice/Trees/LevelOrder.js: -------------------------------------------------------------------------------- 1 | // Definition for a binary tree node 2 | // function TreeNode(data){ 3 | // this.data = data 4 | // this.left = null 5 | // this.right = null 6 | // } 7 | A = function LevelOrder(A) { 8 | let output = []; 9 | if (!A.left && !A.right) { 10 | let curr_output = [A.data]; 11 | output.push(curr_output); 12 | return output; 13 | } 14 | let queue = [A]; 15 | 16 | while (queue.length) { 17 | let len = queue.length; 18 | output.push(queue.map((node) => node.data)); 19 | 20 | while (len--) { 21 | let node = queue.shift(); 22 | if (node.left) queue.push(node.left); 23 | if (node.right) queue.push(node.right); 24 | } 25 | } 26 | 27 | return output; 28 | }; 29 | -------------------------------------------------------------------------------- /Practice/Trees/MaxPathSum.java: -------------------------------------------------------------------------------- 1 | public class MaxPathSum { 2 | static int ans; 3 | 4 | public static void main(String[] args) { 5 | ans = Integer.MIN_VALUE; 6 | MaxPathSum mp = new MaxPathSum(); 7 | TreeNode A = new TreeNode(1); 8 | A.left = new TreeNode(2); 9 | A.right = new TreeNode(3); 10 | mp.FindMaxPathSum(A); 11 | System.out.println(ans); 12 | } 13 | 14 | public int FindMaxPathSum(TreeNode A) { 15 | 16 | if (A == null) 17 | return 0; 18 | 19 | int left = Math.max(0, FindMaxPathSum(A.left)); 20 | int right = Math.max(0, FindMaxPathSum(A.right)); 21 | ans = Math.max(ans, left + right + A.val); 22 | 23 | return A.val + Math.max(left, right); 24 | } 25 | } -------------------------------------------------------------------------------- /Practice/Trees/MaxValue.js: -------------------------------------------------------------------------------- 1 | // Definition for a binary tree node 2 | // function TreeNode(data){ 3 | // this.data = data 4 | // this.left = null 5 | // this.right = null 6 | // } 7 | 8 | module.exports = { 9 | //param A : root node of tree 10 | //return an integer 11 | solve: function (A) { 12 | return MaxValue(A); 13 | }, 14 | }; 15 | 16 | function MaxValue(A) { 17 | if (A == null) return -1; 18 | 19 | let max = Math.max(MaxValue(A.left), A.data); 20 | max = Math.max(max, MaxValue(A.right)); 21 | 22 | return max; 23 | } 24 | -------------------------------------------------------------------------------- /Practice/Trees/NextPointerBinaryTree.js: -------------------------------------------------------------------------------- 1 | function NextPointerBinaryTree(A) { 2 | let curr = A; 3 | 4 | while (curr != null) { 5 | let temp = curr; 6 | 7 | while (temp != null) { 8 | if (temp.left) temp.left.next = temp.right; 9 | if (temp.right && temp.next) temp.right = temp.next.left; 10 | temp = temp.next; 11 | } 12 | 13 | curr = curr.left; 14 | } 15 | 16 | return A; 17 | } 18 | -------------------------------------------------------------------------------- /Practice/Trees/NodeDistanceCInBinaryTree.js: -------------------------------------------------------------------------------- 1 | function NodeDistanceCInBinaryTree(A, B, C) {} 2 | -------------------------------------------------------------------------------- /Practice/Trees/NodesCount.js: -------------------------------------------------------------------------------- 1 | // Definition for a binary tree node 2 | // function TreeNode(data){ 3 | // this.data = data 4 | // this.left = null 5 | // this.right = null 6 | // } 7 | 8 | module.exports = { 9 | //param A : root node of tree 10 | //return an integer 11 | solve: function (A) { 12 | return NodesCount(A); 13 | }, 14 | }; 15 | 16 | function NodesCount(A) { 17 | if (A == null) return 0; 18 | 19 | let lc = NodesCount(A.left); 20 | let rc = NodesCount(A.right); 21 | 22 | return lc + rc + 1; 23 | } 24 | -------------------------------------------------------------------------------- /Practice/Trees/NodesSum.js: -------------------------------------------------------------------------------- 1 | // Definition for a binary tree node 2 | // function TreeNode(data){ 3 | // this.data = data 4 | // this.left = null 5 | // this.right = null 6 | // } 7 | 8 | module.exports = { 9 | //param A : root node of tree 10 | //return an integer 11 | solve: function (A) { 12 | return NodeSum(A); 13 | }, 14 | }; 15 | 16 | function NodeSum(A) { 17 | if (A == null) return 0; 18 | 19 | let ls = NodeSum(A.left); 20 | let rs = NodeSum(A.right); 21 | 22 | return ls + rs + A.data; 23 | } 24 | -------------------------------------------------------------------------------- /Practice/Trees/OddAndEvenLevel.js: -------------------------------------------------------------------------------- 1 | function OddAndEvenLevel(A) { 2 | let level = 1; 3 | let oddSum = 0; 4 | let evenSum = 0; 5 | let queue = [A]; 6 | 7 | while (queue.length > 0) { 8 | let count = queue.length; 9 | if (level % 2 == 0) { 10 | while (count--) { 11 | let val = queue.shift(); 12 | if (val != -1 && val != null) { 13 | evenSum += val.data; 14 | queue.push(val.left == null ? -1 : val.left); 15 | queue.push(val.right == null ? -1 : val.right); 16 | } 17 | } 18 | } else { 19 | while (count--) { 20 | let val = queue.shift(); 21 | if (val != -1 && val != null) { 22 | oddSum += val.data; 23 | queue.push(val.left == null ? -1 : val.left); 24 | queue.push(val.right == null ? -1 : val.right); 25 | } 26 | } 27 | } 28 | } 29 | 30 | return oddSum - evenSum; 31 | } 32 | -------------------------------------------------------------------------------- /Practice/Trees/PathSum.js: -------------------------------------------------------------------------------- 1 | function PathSum(root, sum) { 2 | if (root == null) return false; 3 | sum -= root.data; 4 | 5 | if (!root.left && !root.right) return sum === root.val; 6 | 7 | return PathSum(root.left, sum) || PathSum(root.right, sum); 8 | } 9 | -------------------------------------------------------------------------------- /Practice/Trees/PostOrderTraversal.js: -------------------------------------------------------------------------------- 1 | let output = []; 2 | module.exports = { 3 | //param A : root node of tree 4 | //return a array of integers 5 | postorderTraversal: function (A) { 6 | output = []; 7 | return postorderTraversal(A); 8 | }, 9 | }; 10 | 11 | function postorderTraversal(A) { 12 | if (A == null) return; 13 | 14 | postorderTraversal(A.left); 15 | postorderTraversal(A.right); 16 | output.push(A.data); 17 | 18 | return output; 19 | } 20 | -------------------------------------------------------------------------------- /Practice/Trees/RightViewOfBinaryTree.js: -------------------------------------------------------------------------------- 1 | /** 2 | * We construct a level order tree and print last value from each level or we can construct from right to left and print the first value from each level 3 | * @param {Root of binary Tree} A 4 | * @returns leftView 5 | */ 6 | 7 | function RightViewBinaryTree(A) { 8 | let output = []; 9 | if (!A.left && !A.right) { 10 | let curr_output = [A.data]; 11 | output.push(curr_output); 12 | return output; 13 | } 14 | let queue = [A]; 15 | 16 | while (queue.length) { 17 | let len = queue.length; 18 | output.push(queue.map((node) => node.data)); 19 | 20 | while (len--) { 21 | let node = queue.shift(); 22 | if (node.right) queue.push(node.right); 23 | if (node.left) queue.push(node.left); 24 | } 25 | } 26 | let rightview = []; 27 | for (const x of output) { 28 | rightview.push(x[0]); 29 | } 30 | 31 | return rightview; 32 | } 33 | -------------------------------------------------------------------------------- /Practice/Trees/SerializeBinaryTree.js: -------------------------------------------------------------------------------- 1 | function SerializeBinaryTree(A) { 2 | let output = []; 3 | let queue = []; 4 | queue.push(A); 5 | 6 | while (queue.length > 0) { 7 | let val = queue.shift(); 8 | output.push(val == -1 ? -1 : val.data); 9 | if (val != -1) { 10 | queue.push(!val.left ? -1 : val.left); 11 | queue.push(!val.right ? -1 : val.right); 12 | } 13 | } 14 | 15 | return output; 16 | } 17 | -------------------------------------------------------------------------------- /Practice/Trees/SortedArrayToBST.js: -------------------------------------------------------------------------------- 1 | const A = [1, 2, 3, 5, 10]; 2 | 3 | function SortedArrayToBST(A, left, right) { 4 | if (A == null || left > right) return null; 5 | 6 | let mid = Math.floor((left + right) / 2); 7 | let root = new Node(A[mid]); 8 | root.left = SortedArrayToBST(A, left, mid - 1); 9 | root.right = SortedArrayToBST(A, mid + 1, right); 10 | 11 | return root; 12 | } 13 | 14 | class Node { 15 | constructor(num) { 16 | this.data = num; 17 | this.left = null; 18 | this.right = null; 19 | } 20 | } 21 | 22 | console.log(SortedArrayToBST(A, 0, A.length - 1)); 23 | -------------------------------------------------------------------------------- /Practice/Trees/SymmetricBinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ScalerPractice.Trees 8 | { 9 | internal class SymmetricBinaryTree 10 | { 11 | public int IsSymmetric(TreeNode A) 12 | { 13 | 14 | return CheckBinaryTree(A.Left, A.Right) == true ? 1 : 0; 15 | } 16 | 17 | 18 | public bool CheckBinaryTree(TreeNode A, TreeNode B) 19 | { 20 | if (A == null && B == null) return true; 21 | if (A == null || B == null) return false; 22 | 23 | if (A.Value != B.Value) 24 | { 25 | return false; 26 | } 27 | 28 | return (CheckBinaryTree(A.Left, B.Right) && CheckBinaryTree(A.Right, B.Left)); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Practice/Trees/TreeHeight.js: -------------------------------------------------------------------------------- 1 | // Definition for a binary tree node 2 | // function TreeNode(data){ 3 | // this.data = data 4 | // this.left = null 5 | // this.right = null 6 | // } 7 | 8 | module.exports = { 9 | //param A : root node of tree 10 | //return an integer 11 | solve: function (A) { 12 | return TreeHeight(A); 13 | }, 14 | }; 15 | 16 | function TreeHeight(A) { 17 | if (A == null) return 0; 18 | 19 | return Math.max(TreeHeight(A.left), TreeHeight(A.right)) + 1; 20 | } 21 | -------------------------------------------------------------------------------- /Practice/Trees/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | TreeNode(int x) { 7 | this.val = x; 8 | this.left = null; 9 | this.right = null; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Practice/Trees/Trees1_09_Feb_2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Trees/Trees1_09_Feb_2022.pdf -------------------------------------------------------------------------------- /Practice/Trees/ValidBinarySearchTree.js: -------------------------------------------------------------------------------- 1 | function ValidBinarySearchTree(A) { 2 | return IsValid(A, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); 3 | } 4 | 5 | function IsValid(A, min, max) { 6 | if (A == null) return true; 7 | 8 | if (A.data < min || A.data > max) return false; 9 | 10 | return IsValid(A.left, min, A.data) && IsValid(A.right, A.data, max); 11 | } 12 | -------------------------------------------------------------------------------- /Practice/Trie/backend-node/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "arrowParens": "avoid" 4 | } 5 | -------------------------------------------------------------------------------- /Practice/Trie/backend-node/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Trie", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "Trie.js", 6 | "dependencies": { 7 | "cors": "^2.8.5", 8 | "express": "^4.17.1" 9 | }, 10 | "devDependencies": {}, 11 | "scripts": { 12 | "test": "echo \"Error: no test specified\" && exit 1" 13 | }, 14 | "keywords": [], 15 | "author": "", 16 | "license": "ISC" 17 | } 18 | -------------------------------------------------------------------------------- /Practice/Trie/backend-node/store.json: -------------------------------------------------------------------------------- 1 | ["sagar", "sunil", "ranjit", "alex", "newperson"] 2 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major versions 15 | last 2 iOS major versions 16 | Firefox ESR 17 | not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line. 18 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | 16 | # IDEs and editors 17 | /.idea 18 | .project 19 | .classpath 20 | .c9/ 21 | *.launch 22 | .settings/ 23 | *.sublime-workspace 24 | 25 | # IDE - VSCode 26 | .vscode/* 27 | !.vscode/settings.json 28 | !.vscode/tasks.json 29 | !.vscode/launch.json 30 | !.vscode/extensions.json 31 | .history/* 32 | 33 | # misc 34 | /.sass-cache 35 | /connect.lock 36 | /coverage 37 | /libpeerconnection.log 38 | npm-debug.log 39 | yarn-error.log 40 | testem.log 41 | /typings 42 | 43 | # System Files 44 | .DS_Store 45 | Thumbs.db 46 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule, Routes } from '@angular/router'; 3 | 4 | const routes: Routes = []; 5 | 6 | @NgModule({ 7 | imports: [RouterModule.forRoot(routes)], 8 | exports: [RouterModule] 9 | }) 10 | export class AppRoutingModule { } 11 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Trie/frontend/src/app/app.component.css -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 |
5 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.css'] 7 | }) 8 | export class AppComponent { 9 | title = 'trie'; 10 | } 11 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | 4 | import { AppRoutingModule } from './app-routing.module'; 5 | import { AppComponent } from './app.component'; 6 | import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; 7 | import { NavbarComponent } from './components/navbar/navbar.component'; 8 | import { AutoCompleteComponent } from './components/auto-complete/auto-complete.component'; 9 | 10 | import { HttpClientModule } from '@angular/common/http'; 11 | import { FormsModule } from '@angular/forms'; 12 | @NgModule({ 13 | declarations: [AppComponent, NavbarComponent, AutoCompleteComponent], 14 | imports: [ 15 | BrowserModule, 16 | AppRoutingModule, 17 | NgbModule, 18 | HttpClientModule, 19 | FormsModule, 20 | ], 21 | providers: [], 22 | bootstrap: [AppComponent], 23 | }) 24 | export class AppModule {} 25 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/components/auto-complete/auto-complete.component.css: -------------------------------------------------------------------------------- 1 | .w-100p { 2 | width: 100%; 3 | } 4 | .h-100p { 5 | height: calc(100vh - 64px); 6 | } 7 | 8 | .search-container { 9 | justify-content: center; 10 | } 11 | 12 | .nodiplay { 13 | display: none; 14 | } 15 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/components/auto-complete/auto-complete.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 |
6 | 14 |
15 |
16 | Sorry, suggestions could not be loaded. 17 |
18 |
19 |
20 |
21 |
22 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/components/auto-complete/auto-complete.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { AutoCompleteComponent } from './auto-complete.component'; 4 | 5 | describe('AutoCompleteComponent', () => { 6 | let component: AutoCompleteComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ AutoCompleteComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(AutoCompleteComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/components/navbar/navbar.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Trie/frontend/src/app/components/navbar/navbar.component.css -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/components/navbar/navbar.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { NavbarComponent } from './navbar.component'; 4 | 5 | describe('NavbarComponent', () => { 6 | let component: NavbarComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ NavbarComponent ] 12 | }) 13 | .compileComponents(); 14 | }); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(NavbarComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/components/navbar/navbar.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-navbar', 5 | templateUrl: './navbar.component.html', 6 | styleUrls: ['./navbar.component.css'], 7 | }) 8 | export class NavbarComponent implements OnInit { 9 | constructor() {} 10 | 11 | ngOnInit(): void {} 12 | } 13 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/services/wikipedia.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { WikipediaService } from './wikipedia.service'; 4 | 5 | describe('WikipediaService', () => { 6 | let service: WikipediaService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(WikipediaService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/app/services/wikipedia.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, HttpParams } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { of } from 'rxjs'; 4 | import { map } from 'rxjs/operators'; 5 | 6 | // const WIKI_URL = 'https://en.wikipedia.org/w/api.php'; 7 | const WIKI_URL = 'http://localhost:3001/getsome'; 8 | const PARAMS = new HttpParams({ 9 | fromObject: { 10 | action: 'opensearch', 11 | format: 'json', 12 | origin: '*', 13 | }, 14 | }); 15 | 16 | @Injectable({ 17 | providedIn: 'root', 18 | }) 19 | export class WikipediaService { 20 | constructor(private http: HttpClient) {} 21 | 22 | search(term: string) { 23 | if (term === '') { 24 | return of([]); 25 | } 26 | 27 | return this.http.get(WIKI_URL); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Trie/frontend/src/assets/.gitkeep -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/Trie/frontend/src/favicon.ico -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Trie 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting(), 21 | { teardown: { destroyAfterEach: true }}, 22 | ); 23 | 24 | // Then we find all the tests. 25 | const context = require.context('./', true, /\.spec\.ts$/); 26 | // And load the modules. 27 | context.keys().map(context); 28 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "forceConsistentCasingInFileNames": true, 8 | "strict": true, 9 | "noImplicitReturns": true, 10 | "noFallthroughCasesInSwitch": true, 11 | "sourceMap": true, 12 | "declaration": false, 13 | "downlevelIteration": true, 14 | "experimentalDecorators": true, 15 | "moduleResolution": "node", 16 | "importHelpers": true, 17 | "target": "es2017", 18 | "module": "es2020", 19 | "lib": [ 20 | "es2018", 21 | "dom" 22 | ] 23 | }, 24 | "angularCompilerOptions": { 25 | "enableI18nLegacyMessageIdFormat": false, 26 | "strictInjectionParameters": true, 27 | "strictInputAccessModifiers": true, 28 | "strictTemplates": true 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Practice/Trie/frontend/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /Practice/TrieDSA/AutoComplete.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Calyfs0/DSAFromScaler/c7f73fb54127a6984520a5c5495349a2123d5f94/Practice/TrieDSA/AutoComplete.js -------------------------------------------------------------------------------- /Practice/TwoPointers/AnotherCountRectangle.js: -------------------------------------------------------------------------------- 1 | function AnotherCountRectangle(A, B) { 2 | let count = 0; 3 | let p1 = 0; 4 | let p2 = A.length - 1; 5 | 6 | while (p1 <= p2) { 7 | let prod = A[p1] * A[p2]; 8 | if (prod < B) { 9 | count += (p2 - p1) * 2; 10 | if (A[p1] * A[p1] < B) count++; 11 | p1++; 12 | } else { 13 | p2--; 14 | } 15 | } 16 | return count % 1000000007; 17 | } 18 | -------------------------------------------------------------------------------- /Practice/TwoPointers/ContainerWithMostWater.js: -------------------------------------------------------------------------------- 1 | A = [1, 5, 4, 3]; 2 | 3 | function MaxArea(A){ 4 | if(A<2) return 0; 5 | let i = 0; 6 | let j = A.length -1; 7 | let max_area = 0; 8 | while(i> threeSum(int[] nums) { 12 | 13 | } 14 | } 15 | // @lc code=end 16 | 17 | -------------------------------------------------------------------------------- /Practice/leetcode/1bit2bit.js: -------------------------------------------------------------------------------- 1 | A = [1, 0, 0, 0] //Answer : True 2 | B = [1, 1, 1, 0] //Answer false 3 | console.log(checkValid(A)) 4 | console.log(checkValid(B)) 5 | 6 | function checkValid(bits) { 7 | L = bits.length 8 | if(L ==1) return true 9 | i = 0 10 | while(i 0){ 14 | newNum = newNum*10 + xCopy%10; 15 | xCopy = xCopy/10; 16 | } 17 | 18 | return x == newNum; 19 | } 20 | } 21 | // @lc code=end 22 | 23 | -------------------------------------------------------------------------------- /Practice/leetcode/ContainerWithMoreWater.java: -------------------------------------------------------------------------------- 1 | public class ContainerWithMoreWater { 2 | public int maxArea(int[] height) { 3 | 4 | int area = 0; 5 | int i = 0; 6 | int j = height.length - 1; 7 | 8 | while (i != j) { 9 | int current_area = (j - i) * Math.min(height[i], height[j]); 10 | 11 | if (current_area > area) { 12 | area = current_area; 13 | } 14 | 15 | if (height[i] > height[j]) { 16 | j--; 17 | } else { 18 | i++; 19 | } 20 | } 21 | 22 | return area; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Practice/leetcode/DecodeXORedArray.java: -------------------------------------------------------------------------------- 1 | public class DecodeXORedArray { 2 | public int[] decode(int[] encoded, int first) { 3 | int[] output = new int[encoded.length + 1]; 4 | 5 | output[0] = first; 6 | 7 | for (int i = 0; i < encoded.length; i++) { 8 | output[i + 1] = output[i] ^ encoded[i]; 9 | } 10 | 11 | return output; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Practice/leetcode/DifferenceBetweenProductandSum.java: -------------------------------------------------------------------------------- 1 | public class DifferenceBetweenProductandSum { 2 | public int subtractProductAndSum(int n) { 3 | int sum = 0; 4 | int product = 1; 5 | 6 | while (n > 0) { 7 | int val = n % 10; 8 | sum += val; 9 | product *= val; 10 | n = n / 10; 11 | } 12 | 13 | return product - sum; 14 | 15 | } 16 | 17 | // Optimized approach using string 18 | public int subtractProductAndSumUsingString(int n) { 19 | String s = Integer.toString(n); 20 | char[] arr = s.toCharArray(); 21 | int sum = 0; 22 | int product = 1; 23 | for (int i = 0; i < arr.length; i++) { 24 | int val = Character.getNumericValue(arr[i]); 25 | sum += val; 26 | product *= val; 27 | } 28 | 29 | return product - sum; 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Practice/leetcode/FindTargetIndicesAfterSorting.java: -------------------------------------------------------------------------------- 1 | public class FindTargetIndicesAfterSorting { 2 | public List targetIndices(int[] nums, int target) { 3 | Arrays.sort(nums); 4 | List output = new ArrayList(); 5 | 6 | for (int i = 0; i < nums.length; i++) { 7 | if (nums[i] == target) { 8 | output.add(i); 9 | } 10 | } 11 | 12 | return output; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Practice/leetcode/ShuffleString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String restoreString(String s, int[] indices) { 3 | char[] arr = s.toCharArray(); 4 | for (int i = 0; i < indices.length; i++) { 5 | while (indices[i] != i) { 6 | int index = indices[i]; 7 | 8 | char temp_char = arr[index]; 9 | arr[index] = arr[i]; 10 | arr[i] = temp_char; 11 | 12 | int temp = indices[index]; 13 | indices[index] = indices[i]; 14 | indices[i] = temp; 15 | 16 | } 17 | } 18 | 19 | return new String(arr); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /Practice/leetcode/countofSmallNumberThanCurrent.java: -------------------------------------------------------------------------------- 1 | public class countofSmallNumberThanCurrent { 2 | public int[] smallerNumbersThanCurrent(int[] nums) { 3 | 4 | int max = 0; 5 | for(int i=0;i max) max = nums[i]; 7 | } 8 | 9 | int[] bag = new int[max+1]; 10 | 11 | for(int j = 0;j map = new HashMap(); 8 | for (int n : nums) { 9 | int count_val = map.getOrDefault(n, 0); 10 | gpCount += count_val; 11 | map.put(n, count_val + 1); 12 | 13 | } 14 | 15 | return gpCount; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding from "Hello World" to DSA, Design patterns, LLD, HLD. 2 | 3 | 4 | This repo can be used for submitting your best solutions and also for learning. 5 | 6 | 7 | # Note: 8 | 9 | Invalid pushes will be rejected. 10 | -------------------------------------------------------------------------------- /Revision/Arrays/CopyTheArray.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class CopyTheArray { 5 | public ArrayList solve(final List A, int B) { 6 | ArrayList output = new ArrayList(); 7 | 8 | for (int i = 0; i < A.size(); i++) { 9 | output.add(A.get(i) + B); 10 | } 11 | 12 | return output; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Revision/Arrays/CountDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.List;; 3 | 4 | public class CountDuplicates { 5 | public int solve(final List A) { 6 | 7 | HashSet hs = new HashSet(); 8 | int ans = 0; 9 | for (int i = 0; i < A.size(); i++) { 10 | if (hs.contains(A.get(i))) 11 | ans++; 12 | else 13 | hs.add(A.get(i)); 14 | } 15 | 16 | return ans; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Revision/Arrays/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | public class FizzBuzz { 2 | public String[] PrintFizzBuzz(int A){ 3 | String[] output = new String[A]; 4 | for(int i=1;i<=A;i++){ 5 | String s = ""; 6 | if(i%3 == 0) s += "Fizz"; 7 | if(i%5 == 0) s += "Buzz"; 8 | if(s.equals("")){ 9 | output[i-1] = Integer.toString(i); 10 | } 11 | else{ 12 | output[i-1] = s; 13 | } 14 | } 15 | 16 | return output; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Revision/Arrays/GoodPairBruteForce.java: -------------------------------------------------------------------------------- 1 | public class GoodPairBruteForce { 2 | public int solve(int[] A, int B) { 3 | for(int i=0;i hs = new HashSet(); 6 | for(int i =0;i A; 5 | 6 | public LeadersInAnArray(ArrayList inputArray) { 7 | this.A = inputArray; 8 | } 9 | 10 | public ArrayList FindLeadersInArray() { 11 | ArrayList output = new ArrayList(); 12 | int currentMax = A.get(A.size() - 1); 13 | output.add(currentMax); 14 | 15 | for (int i = A.size() - 2; i >= 0; i--) { 16 | int currentValue = A.get(i); 17 | if (currentValue > currentMax) { 18 | output.add(currentValue); 19 | currentMax = currentValue; 20 | } 21 | } 22 | 23 | return output; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Revision/Arrays/LowerTriangularMatrix.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | 4 | public class LowerTriangularMatrix { 5 | public int solve(final List> A) { 6 | for (int i = 0; i < A.size(); i++) { 7 | for (int j = i + 1; j < A.get(0).size(); j++) { 8 | if (A.get(i).get(j) != 0) 9 | return 0; 10 | } 11 | } 12 | 13 | return 1; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Revision/Arrays/MAXMIN.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | 4 | public class MAXMIN { 5 | public int solve(ArrayList A, int B) { 6 | Collections.sort(A); 7 | return (A.get(A.size() - B) - A.get(B-1)); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Revision/Arrays/MaxAndMinOfAnArray.java: -------------------------------------------------------------------------------- 1 | public class MaxAndMinOfAnArray { 2 | 3 | public void PrintMaxAndMin(int[] inputArray) { 4 | int maxElement = Integer.MIN_VALUE; 5 | int minElement = Integer.MAX_VALUE; 6 | 7 | for (int i = 0; i < inputArray.length; i++) { 8 | if (maxElement < inputArray[i]) { 9 | maxElement = inputArray[i]; 10 | } 11 | 12 | if (minElement > inputArray[i]) { 13 | minElement = inputArray[i]; 14 | } 15 | 16 | } 17 | System.out.print(maxElement + " " + minElement); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Revision/Arrays/MaxMod.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | 4 | public class MaxMod { 5 | public int solve(ArrayList A) { 6 | Collections.sort(A); 7 | int maxMod = Integer.MIN_VALUE; 8 | for(int i=1;i input; 7 | 8 | public MaxSumContiguousArray(List input) { 9 | this.input = input; 10 | } 11 | 12 | public int CalculateMaxContiguousSum() { 13 | int maxSum = Integer.MIN_VALUE; 14 | int currentSum = 0; 15 | 16 | for (int i = 0; i < input.size(); i++) { 17 | currentSum += input.get(i); 18 | maxSum = Math.max(maxSum, currentSum); 19 | if (currentSum < 0) { 20 | currentSum = 0; 21 | } 22 | } 23 | 24 | return maxSum; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Revision/Arrays/MultiplicationOfPreviousAndNext.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class MultiplicationOfPreviousAndNext { 4 | public ArrayList solve(ArrayList A) { 5 | if (A.size() == 1) 6 | return A; 7 | ArrayList output = new ArrayList(); 8 | output.add(A.get(0) * A.get(1)); 9 | int lastIndex = A.size() - 1; 10 | for (int i = 1; i < lastIndex; i++) { 11 | output.add(A.get(i - 1) * A.get(i + 1)); 12 | } 13 | 14 | output.add(A.get(lastIndex) * A.get(lastIndex - 1)); 15 | return output; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Revision/Arrays/NobleInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | import java.util.Collections; 4 | 5 | public class NobleInteger { 6 | ArrayList A; 7 | 8 | public NobleInteger(ArrayList A) { 9 | this.A = A; 10 | } 11 | 12 | public int FindNumberOfNobleIntegers() { 13 | Collections.sort(A); 14 | int prevValue = A.get(A.size() - 1); 15 | if (prevValue == 0) { 16 | return 1; 17 | } 18 | int largerElements = 0; 19 | for (int i = A.size() - 2; i >= 0; i--) { 20 | int currentValue = A.get(i); 21 | if (currentValue != prevValue) { 22 | largerElements = A.size() - 1 - i; 23 | } 24 | if (currentValue == largerElements) 25 | return 1; 26 | 27 | prevValue = currentValue; 28 | } 29 | 30 | return -1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Revision/Arrays/ReverseTheArray.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class ReverseTheArray { 4 | final ArrayList A; 5 | 6 | public ReverseTheArray(ArrayList A) { 7 | this.A = A; 8 | } 9 | 10 | public ArrayList Reverse() { 11 | int i = 0; 12 | int j = A.size() - 1; 13 | 14 | while (i < j) { 15 | A.set(i, A.get(i) ^ A.get(j)); 16 | A.set(j, A.get(i) ^ A.get(j)); 17 | A.set(i, A.get(i) ^ A.get(j)); 18 | i++; 19 | j--; 20 | } 21 | 22 | return A; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Revision/Arrays/RotationGame.java: -------------------------------------------------------------------------------- 1 | public class RotationGame { 2 | int[] A; 3 | int B; 4 | 5 | public RotationGame(int[] A, int B) { 6 | this.A = A; 7 | this.B = B; 8 | } 9 | 10 | public void RotateArray() { 11 | 12 | int startIndex = A.length - (B % A.length); 13 | for (int i = startIndex, j = 0; j < A.length; j++, i++) { 14 | System.out.print(A[i % A.length] + " "); 15 | } 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Revision/Arrays/RotationGameReversingTheArray.java: -------------------------------------------------------------------------------- 1 | public class RotationGameReversingTheArray { 2 | int[] A; 3 | int B; 4 | 5 | public RotationGameReversingTheArray(int[] A, int B) { 6 | this.A = A; 7 | this.B = B; 8 | } 9 | 10 | public void RotateArray() { 11 | Rotate(A, 0, A.length - 1); 12 | 13 | Rotate(A, 0, B - 1); 14 | 15 | Rotate(A, B, A.length - 1); 16 | 17 | System.out.println(A.toString()); 18 | } 19 | 20 | public void Rotate(int[] arr, int i, int j) { 21 | while (i < j) { 22 | int temp = arr[i]; 23 | arr[i] = arr[j]; 24 | arr[j] = temp; 25 | } 26 | i++; 27 | j--; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Revision/Arrays/SubArrayWithLeastAverage.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class SubArrayWithLeastAverage { 4 | ArrayList A; 5 | int B; 6 | 7 | public SubArrayWithLeastAverage(ArrayList A, int B) { 8 | this.A = A; 9 | this.B = B; 10 | } 11 | 12 | public int GetFirstIndexOofLeastAverageSubArray() { 13 | int minSum = 0; 14 | 15 | int outputIndex = 0; 16 | 17 | for (int i = 0; i < B; i++) { 18 | minSum += A.get(i); 19 | } 20 | 21 | int currentSum = minSum; 22 | 23 | for (int i = B; i < A.size(); i++) { 24 | currentSum -= A.get(i - B); 25 | currentSum += A.get(i); 26 | if (currentSum < minSum) { 27 | minSum = currentSum; 28 | outputIndex = i - B + 1; 29 | } 30 | } 31 | 32 | return outputIndex; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Revision/Arrays/SumOfAllSubArrays.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ScalerPractice 8 | { 9 | internal class SumOfAllSubArrays 10 | { 11 | public long subarraySum(List A) 12 | { 13 | long sum = 0; 14 | 15 | for (int i = 0; i < A.Count; i++) 16 | { 17 | sum += (long)A[i] * (i + 1) * (A.Count - i); 18 | } 19 | 20 | return sum; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Revision/Arrays/TimeToEquality.java: -------------------------------------------------------------------------------- 1 | public class TimeToEquality { 2 | int[] A = {2, 4, 1, 3, 2}; 3 | public int CalculateTotalTime(int[] A){ 4 | int max = Integer.MIN_VALUE; 5 | int currentSum = 0; 6 | for(int i=0;i max){ 8 | max = A[i]; 9 | } 10 | 11 | currentSum += A[i]; 12 | 13 | } 14 | 15 | //if all element become max, total sum = max * length of array 16 | //So time taken will be total sum - current sum 17 | 18 | return max * A.length - currentSum; 19 | } 20 | 21 | } 22 | 23 | 24 | -------------------------------------------------------------------------------- /Revision/Backtracking/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | 6 | String[] inputString = {"53..7....","6..195...",".98....6.","8...6...3","4..8.3..1","7...2...6",".6....28.","...419..5","....8..79"}; 7 | char[][] A = new char[inputString.length][]; 8 | for(int i=0;i0){ 14 | pow++; 15 | X = X>>1; 16 | } 17 | 18 | int val = (int)Math.pow(2,pow); 19 | long totalSetBits = (long)(val/2)*pow + (A-val+1) + TotalSetBits(A-val); 20 | return (int)(totalSetBits%1000000007); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Revision/BitManipulation/FindReverseBitUnsigned.java: -------------------------------------------------------------------------------- 1 | public class FindReverseBitUnsigned{ 2 | 3 | public static void main(String[] args) { 4 | int A = 3; 5 | System.out.println(FindReverseBitUnsigned.FindReverse(A)); 6 | } 7 | 8 | public static long FindReverse(int A){ 9 | long reverse = 0; 10 | 11 | for(int i=0;i<32;i++){ 12 | if(A*(1< 0){ 13 | reverse += (long)1 << (31-i); 14 | } 15 | } 16 | 17 | return reverse; 18 | } 19 | } -------------------------------------------------------------------------------- /Revision/BitManipulation/InterestingArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class InterestingArray { 4 | public static void main(String[] args) { 5 | ArrayList A = new ArrayList<>(List.of(9,17)); 6 | InterestingArray ia = new InterestingArray(); 7 | System.out.println(ia.solve(A)); 8 | } 9 | public String solve(ArrayList A) { 10 | int xorValue = 0; 11 | 12 | for(int i=0;i a) { 6 | int output = 0; 7 | for (int x : a) { 8 | output = output ^ x; 9 | } 10 | return output; 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /Revision/BitManipulation/MinimumXORValue.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class MinimumXORValue { 4 | public static void main(String[] args) { 5 | ArrayList A = new ArrayList<>(List.of(4,7,0,9)); 6 | MinimumXORValue mxv = new MinimumXORValue(); 7 | System.out.println(mxv.findMinXor(A)); 8 | } 9 | public int findMinXor(ArrayList A) { 10 | Collections.sort(A); 11 | 12 | int min = Integer.MAX_VALUE; 13 | 14 | for(int i=1;i0){ 13 | noOfSetBits++; 14 | A = A &(A-1); 15 | } 16 | 17 | return noOfSetBits; 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Revision/BitManipulation/ReverseBits.java: -------------------------------------------------------------------------------- 1 | public class ReverseBits { 2 | public static void main(String[] args) { 3 | ReverseBits reverseBits = new ReverseBits(); 4 | long A = 3; 5 | System.out.println(reverseBits.reverse(A)); 6 | } 7 | public long reverse(long a) { 8 | long reverseInt = 0; 9 | 10 | for(int i=0;i<32;i++){ 11 | if((a & (1< 0){ 12 | reverseInt |= (long)1<<(31-i); 13 | } 14 | 15 | } 16 | 17 | return reverseInt; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Revision/BitManipulation/SingleNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | public class SingleNumber { 4 | public static void main(String[] args) { 5 | List A = new ArrayList(List.of(1,1,2,2,3,3,4)); 6 | SingleNumber sn = new SingleNumber(); 7 | System.out.println(sn.singleNumber(A)); 8 | } 9 | public int singleNumber(final List A) { 10 | int ans = 0; 11 | for(int i=0;i A = new ArrayList(List.of(1,1,1,2,2,2,3,3,3,4)); 8 | SingleNumberII sn = new SingleNumberII(); 9 | System.out.println(sn.singleNumber(A)) ; 10 | } 11 | public int singleNumber(final List A) { 12 | int ans = 0; 13 | 14 | for(int i=0;i<32;i++){ 15 | int count = 0; 16 | for(int j=0;j 0){ 20 | count++; 21 | } 22 | } 23 | 24 | if(count%3!=0){ 25 | ans |= 1<=0;i--){ 12 | if((A & (1< 0){ 13 | ans |= 1<0){ 13 | if((A &(1<<0)) == 0){ 14 | smallNumber |= 1<>1; 18 | } 19 | 20 | largeNumber |= 1<<(i); 21 | return smallNumber^largeNumber; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Revision/Dynamic Programming/LetsParty.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class LetsParty { 4 | public static void main(String[] args) { 5 | int A = 4; 6 | int mod = 10003; 7 | int[] dp = new int[A + 1]; 8 | Arrays.fill(dp, -1); 9 | 10 | LetsParty letsParty = new LetsParty(); 11 | int ans = letsParty.noOfWays(A, dp, mod); 12 | 13 | System.out.println(ans); 14 | 15 | } 16 | 17 | public int noOfWays(int A, int[] dp, int mod) { 18 | if (A < 3) 19 | return A; 20 | 21 | if (dp[A] != -1) 22 | return dp[A]; 23 | dp[A] = (noOfWays(A - 1, dp, mod) + (noOfWays(A - 2, dp, mod) * (A - 1)) % mod) % mod; 24 | return dp[A]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Revision/Dynamic Programming/MinimumNumberOfSquare.java: -------------------------------------------------------------------------------- 1 | public class MinimumNumberOfSquare { 2 | public int countMinSquares(int A) { 3 | int[] minimumCountArray = new int[A + 1]; 4 | for (int i = 0; i < minimumCountArray.length; i++) { 5 | minimumCountArray[i] = -1; 6 | } 7 | return minimumCount(A, minimumCountArray); 8 | } 9 | 10 | public int minimumCount(int A, int[] minimumCountArray) { 11 | 12 | if (A == 0) 13 | return 0; 14 | if (minimumCountArray[A] != -1) 15 | return minimumCountArray[A]; 16 | minimumCountArray[A] = 1; 17 | int ans = Integer.MAX_VALUE; 18 | for (int i = 1; i * i <= A; i++) { 19 | ans = Math.min(ans, minimumCount(A - i * i, minimumCountArray)); 20 | } 21 | minimumCountArray[A] += ans; 22 | return minimumCountArray[A]; 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Revision/Dynamic Programming/Stairs.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | public class Stairs { 3 | public static void main(String[] args) { 4 | int A = 10; 5 | int dp[] = new int[A + 1]; 6 | Arrays.fill(dp, -1); 7 | 8 | Stairs stairs = new Stairs(); 9 | int ans = stairs.ways(A, dp); 10 | System.out.println(ans); 11 | } 12 | 13 | public int ways(int A, int[] dp) { 14 | if (A == 0) 15 | return 1; 16 | if (A < 3) 17 | return A; 18 | 19 | if (dp[A] != -1) 20 | return dp[A]; 21 | dp[A] = ways(A - 1, dp) + ways(A - 2, dp); 22 | return dp[A]; 23 | } 24 | } -------------------------------------------------------------------------------- /Revision/Greedy/DistributeCandies.java: -------------------------------------------------------------------------------- 1 | public class DistributeCandies{ 2 | public int candy(int[] A) { 3 | int[] candies = new int[A.length]; 4 | candies[0] = 1; 5 | for(int i=1;iA[i-1]){ 8 | candies[i] = candies[i-1] + 1; 9 | } 10 | } 11 | 12 | for(int i=A.length -2;i>=0;i--){ 13 | if(A[i] > A[i+1] && candies[i]<=candies[i+1]){ 14 | candies[i] = candies[i+1] + 1; 15 | } 16 | } 17 | int totalCandies = 0; 18 | for(int i=0;i=5){ 5 | n = n/5; 6 | ans += n; 7 | } 8 | 9 | return ans; 10 | 11 | } 12 | } -------------------------------------------------------------------------------- /Revision/LeetCode Random Problems/LongestCommonPrefix.js: -------------------------------------------------------------------------------- 1 | function LongestCommonPrefix(strs) { 2 | let str = ""; 3 | let length = Number.MAX_VALUE; 4 | for (let i = 0; i < strs.length; i++) { 5 | if (strs[i].length < length) { 6 | str = strs[i]; 7 | length = strs[i].length; 8 | } 9 | } 10 | 11 | for (let i = 0; i < strs.length; i++) { 12 | while (!strs[i].startsWith(str)) { 13 | str = str.substring(0, str.length - 1); 14 | } 15 | } 16 | 17 | return str; 18 | } 19 | 20 | let strs = ["reflower", "flow", "flight"]; 21 | 22 | console.log(LongestCommonPrefix(strs)); 23 | -------------------------------------------------------------------------------- /Revision/LeetCode Random Problems/Move_Zeroes.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void MoveZeroes(int[] nums) { 3 | int index = 0; 4 | 5 | for(int i=0;i hs = new Dictionary(); 4 | int count = 0; 5 | for(int i=0;i i) { 14 | j--; 15 | } 16 | 17 | if (s[i] == s[j]) { 18 | i++; 19 | j--; 20 | } else { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | 27 | s = "0P"; 28 | 29 | console.log(ValidParenthesis(s)); 30 | -------------------------------------------------------------------------------- /Revision/LinkedList/KReverseLinkedlist.java: -------------------------------------------------------------------------------- 1 | public class KReverseLinkedlist { 2 | public ListNode ReverseLinkedList(ListNode A, int B){ 3 | 4 | if(A == null) return null; 5 | ListNode head = A; 6 | ListNode currentNode = A.next; 7 | ListNode prevNode = A; 8 | ListNode next = null; 9 | int tempB = B; 10 | while(tempB-- > 0 && currentNode!= null){ 11 | next = currentNode.next; 12 | currentNode.next = prevNode; 13 | prevNode = currentNode; 14 | currentNode = next; 15 | } 16 | 17 | 18 | head.next = ReverseLinkedList(currentNode, B); 19 | 20 | return prevNode; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Revision/LinkedList/ListCycle.java: -------------------------------------------------------------------------------- 1 | public class ListCycle { 2 | public ListNode detectCycle(ListNode a) { 3 | if(a == null) return a; 4 | ListNode fastPointer = a; 5 | ListNode slowPointer = a; 6 | while(fastPointer.next != null && fastPointer.next.next != null){ 7 | slowPointer = slowPointer.next; 8 | fastPointer = fastPointer.next.next; 9 | if(slowPointer == fastPointer){ 10 | slowPointer = a; 11 | while(slowPointer != fastPointer){ 12 | slowPointer = slowPointer.next; 13 | fastPointer = fastPointer.next; 14 | } 15 | return slowPointer; 16 | } 17 | } 18 | 19 | return null; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Revision/LinkedList/MiddleElementOfLinkedlist.java: -------------------------------------------------------------------------------- 1 | public class MiddleElementOfLinkedlist { 2 | 3 | public int solve(ListNode A) { 4 | ListNode slowPointer = A; 5 | ListNode fastPointer = A; 6 | 7 | while(fastPointer!= null && fastPointer.next != null){ 8 | slowPointer = slowPointer.next; 9 | fastPointer = fastPointer.next.next; 10 | } 11 | 12 | return slowPointer.val; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Revision/LinkedList/RemoveLoopFromLinkedlist.java: -------------------------------------------------------------------------------- 1 | public class RemoveLoopFromLinkedlist { 2 | public ListNode solve(ListNode A) { 3 | if(A == null) return A; 4 | ListNode fastPointer = A; 5 | ListNode slowPointer = A; 6 | while(fastPointer.next != null && fastPointer.next.next != null){ 7 | slowPointer = slowPointer.next; 8 | fastPointer = fastPointer.next.next; 9 | if(slowPointer == fastPointer){ 10 | ListNode prev = null; 11 | slowPointer = A; 12 | while(slowPointer != fastPointer){ 13 | prev = fastPointer; 14 | slowPointer = slowPointer.next; 15 | fastPointer = fastPointer.next; 16 | } 17 | prev.next = null; 18 | return A; 19 | } 20 | } 21 | 22 | return null; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Revision/LinkedList/ReverseALinkedList.java: -------------------------------------------------------------------------------- 1 | public class ReverseALinkedList { 2 | public ListNode reverseList(ListNode A) { 3 | ListNode prev = null; 4 | ListNode next = null; 5 | ListNode curr = A; 6 | 7 | while(curr!= null){ 8 | next = curr.next; 9 | curr.next = prev; 10 | prev = curr; 11 | curr = next; 12 | } 13 | 14 | return prev; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Revision/Recursion/AnotherSequenceProblem.java: -------------------------------------------------------------------------------- 1 | public class AnotherSequenceProblem { 2 | public int solve(int A) { 3 | if(A == 0) return 1; 4 | if(A <=2) return A; 5 | 6 | return solve(A-1) + solve(A-2) + solve(A-3) + A; 7 | 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Revision/Recursion/FindFactorial.java: -------------------------------------------------------------------------------- 1 | public class FindFactorial { 2 | public int solve(int A) { 3 | if(A == 0) return 1; 4 | 5 | return solve(A-1) * A; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Revision/Recursion/FindFibonacciII.java: -------------------------------------------------------------------------------- 1 | public class FindFibonacciII { 2 | public int findAthFibonacci(int A) { 3 | if(A <=1) return A; 4 | 5 | return findAthFibonacci(A-1) + findAthFibonacci(A-2); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Revision/Recursion/IsMagic.java: -------------------------------------------------------------------------------- 1 | public class IsMagic { 2 | public int solve(int A) { 3 | 4 | while(A> 9){ 5 | A = IsMagic(A); 6 | } 7 | 8 | if(A == 1) return 1; 9 | return 0; 10 | } 11 | 12 | public int IsMagic(int A){ 13 | if(A == 0) return 0; 14 | 15 | return IsMagic(A/10) + A%10; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Revision/Recursion/PowerFunction.java: -------------------------------------------------------------------------------- 1 | public class PowerFunction{ 2 | public static void main(String[] args) { 3 | PowerFunction powerFunction = new PowerFunction(); 4 | int A = 2; 5 | int B = 3; 6 | int C = 3; 7 | System.out.println(powerFunction.pow(A, B, C)); 8 | } 9 | 10 | public int pow(int A, int B, int C){ 11 | if(A == 0) return 0; 12 | if(B == 0) return 1; 13 | 14 | long currentValue = pow(A,B/2,C); 15 | 16 | long output = (currentValue%C * currentValue%C)%C; 17 | 18 | if(B%2!=0){ 19 | output = (output * A)%C; 20 | } 21 | 22 | if(output < 0){ 23 | output += C; 24 | } 25 | 26 | return (int)output; 27 | } 28 | } -------------------------------------------------------------------------------- /Revision/Recursion/ReverseString.java: -------------------------------------------------------------------------------- 1 | public class ReverseString { 2 | public static void main(String[] args) { 3 | String s = "scaleracademy"; 4 | System.out.println(ReverseString.reverseString(s)); 5 | } 6 | 7 | public static String reverseString(String s){ 8 | if(s.length() == 1) return s; 9 | 10 | return reverseString(s.substring(1)) + s.charAt(0); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Revision/Recursion/SumOfDigits.java: -------------------------------------------------------------------------------- 1 | public class SumOfDigits { 2 | 3 | public int solve(int A) { 4 | if(A == 0) return 0; 5 | 6 | return solve(A/10) + A%10; 7 | } 8 | 9 | } 10 | --------------------------------------------------------------------------------