├── .gitignore ├── COVID-19-21-Day-Coding-Streak ├── Day-1 │ ├── MandN.py │ ├── README.md │ ├── SatisfyTheCondition.py │ └── TriangleAndSquare.py ├── Day-2 │ ├── MinimumNightsToMakeTwoNumbersEqual.py │ ├── MinimumPicksToGetKpairsOfSocks.py │ ├── README.md │ ├── RobTheHouses.py │ ├── checkSubArrayForSorting.py │ └── minimumNights_v2_optimized.py ├── Day-3 │ ├── README.md │ ├── SubArrayGivenSum2DArray.py │ ├── checkIfRectangleExistsInBinaryMatrix.py │ └── findKthElementInSpiralTraversal.py ├── Day-4 │ ├── AverageSubArray.py │ ├── CollectingWood_BinarySearch.py │ ├── MaximumAreaOfSquareWithRectangles.py │ ├── MinimumTimeToPaintHouse-DP.py │ ├── MinimumTimeToPaintHouse.py │ └── README.md ├── Day-6 │ └── StringCompression.py └── README.md ├── CodeSignal └── ZigZagPairs.py ├── Codility └── SplitIntoPairs.py ├── Collabedit ├── README.md └── next_greater_element.py ├── Colorful_Buildings.py ├── CormenBook └── Chapter_15.1_Rod_Cutting.py ├── DS_pocketnotes.pdf ├── DailyCodingProblem ├── AutoCompleteSystem.py ├── CodeOutput01.py ├── CollatzSequence.py ├── Connect4.py ├── DistanceBetween2Words.py ├── DoesPalindromeExist.py ├── IsReachEndOfArray.py ├── IsStringBalanced.py ├── JobScheduler.py ├── LargestRectangleContainingOnly1s.py ├── LongestCommonSubsequence.py ├── LongestSubArrayOfDistinctElements.py ├── NthSevenishNumber.py ├── Problem424.py ├── Problem438.py ├── Problem439.py ├── Problem446.py ├── Problem447.py ├── README.md ├── SentenceValidator.py ├── SumOf2NumbersInLinkedList.py ├── TowerOfHanoi.py ├── XORLinkedList.cpp ├── XORLinkedList.py ├── applyPermutation.py ├── balancedParenthesis.py ├── boustrophedon.py ├── checkPairsWithGivenSum.py ├── convertRomanToDecimal.py ├── ensureNoAdjacentCharacters.py ├── estimatePiMonteCarlo.py ├── evaluatePostfixExpression.py ├── findAllIndices.py ├── findAreaOfIntersection.py ├── findBalancedStringWithMinimumInsertionsDeletions.py ├── findCorrespondingColumn.py ├── findDeepestNode.py ├── findElementsAppearingExactlyOnce.py ├── findIntersectionNode.py ├── findLargestRange.py ├── findMajorityElementInSeq.py ├── findMissingNumbers.py ├── findNodesWhoseSumIsK.py ├── findSparseNumber.py ├── generateNumbers.py ├── generateValidIPCombinations.py ├── getElementsWhoseSumIsK.py ├── getNewArray.py ├── getNthPerfectNumber.py ├── get_shortest_substring.py ├── implement3StacksSingleList.py ├── implementPrefixMapSum.py ├── implementStackWithHeap.py ├── implement_regex.py ├── isBipartiteGraph.py ├── isInsidePolygon.py ├── isIntegerPalindrome.py ├── isStringANumber.py ├── justifyText.py ├── largestSubsetBasedOnConditions.py ├── largestSumNonAdjacentNumbers.py ├── leastMissingPositiveInteger.py ├── lengthOfLongestPath.py ├── lock_Unlock_btree.py ├── longestAbsolutePath.py ├── maxCircularSubArraySum.py ├── maxCoinToCollect.py ├── maxProfitFromBuysandSells.py ├── maximumWeightPathTriangle.py ├── minCost.py ├── minSteps.py ├── minSumRootToLeaf.py ├── minTrialDrops.py ├── minimumElementOlogN.py ├── minimumIntervalsToRemove.py ├── minimumRooms.py ├── minimum_swaps.py ├── nearestKPoints.py ├── nextPermutationAbsoluteOrder.py ├── numberOfStepsToReach1.py ├── numberOfUnivalSubTrees.py ├── pairImplementation.py ├── partitionArray2Subsets.py ├── partitionTheList.py ├── pascalTriangle.py ├── possibleDecodings.py ├── problem195.py ├── problem_22.py ├── rearrangeValues.py ├── recordLastNOrderIDs.py ├── recurringElement.py ├── removeKthLastElement.py ├── removeZeroSumed.py ├── replaceColour.py ├── reversalDirectedGraph.py ├── reverseBits.py ├── rotateArrayInPlace.py ├── rotateListByKElements.py ├── runLengthEncodingDecoding.py ├── serializeDeserialize.py ├── shortestUniquePrefix.py ├── sortUsingReverse.py ├── squarerootOfRealNumber.py └── sumSubList.py ├── DynamicProgramming ├── EditDistanceReference.java └── minimumConversionsBetween2Strings.py ├── GCC-2019 ├── ContinuousSeries.py ├── README.md └── theManipulator.py ├── GFG_Practice ├── GraphAlgorithms │ ├── AdjacencyList.py │ ├── matrix2Graph.py │ ├── pyBFS.py │ ├── pyBFS_GFG.py │ ├── pyDFS_GFG.py │ ├── pyDFS_Iterative.py │ └── pyDFS_recursive.py ├── Matrix │ ├── Count_Zeros_Binary_Matrix.py │ ├── Difference_Between_Diagnols_Of_Matrix.py │ ├── IsSudokuValid.py │ ├── KingsMarch.py │ ├── KingsMarch1.png │ ├── KingsMarch2.png │ ├── RankOfMatrix.py │ ├── SortedMatrix.py │ ├── Starting_Point.py │ ├── Transpose_Of_Matrix.py │ ├── allPathsInaMatrix.py │ ├── maxOf1s_In_a_Matrix.py │ ├── numPathsToOrigin.py │ └── numberOfPalindromicPaths.py ├── NumberTheory │ └── AbsoluteDifferenceBetweenPowers.py ├── Queue │ ├── Reverse_First_K_Elements_Queue.py │ ├── Reverse_First_K_Elements_Queue_v02.py │ ├── __init__.py │ └── queue_Implementation.py ├── README.md ├── Recursion │ ├── SumOfDigits_Recursion.py │ ├── SumOfDigits_Recursion_v2.py │ ├── maximumNumberOfPieceswith_abc.py │ ├── print1toN_Recursion.py │ └── printNto1_Recursion.py ├── Searching │ └── longestContiguousSubArray.py ├── Stack │ ├── SortAStack.py │ └── stack_Implementation.py └── Trees │ ├── maxHeightBinaryTree.py │ └── tree122.gif ├── GFG_Publications ├── BitEvenArrays_v0.2.py ├── Bit_Even_Arrays_Question.md ├── GFG_Contributions_Pending │ ├── minimumOperationsArrayA2B.py │ └── sumOf2Arrays.py ├── README.md ├── RankOfMatrix.py ├── Sub_Sequences_of_String.py ├── decryptString.py ├── isInsidePolygon.py ├── lengthMaximumSizeSubArray.py ├── mergeSortOfLinkedListpy.py ├── minSteps_in_InfiniteGrid.py ├── minimizeReplacements_string.py ├── printAllSubArraysWithZeroSum.py └── string_to_BinarySeq.py ├── GeeksForGeeks_Arrays_Questions └── Array_Rotations │ ├── Block_Swap_Array_Rotation.py │ ├── Cyclic_Rotation_Array_By_One.py │ ├── Find_Element_Rotated_Sorted_Array.py │ ├── Find_Pair_Given_Sum_Sorted_Rotated_Array.py │ ├── Maximum_Possible_Sum.py │ ├── Maximum_Possible_Sum_Array_Only_Rotations_Allowed.py │ ├── Minimum_Rotations_String.py │ ├── Multiple_Left_Rotations_Array.py │ ├── Program_For_Array_Rotation.py │ ├── Reversal_Algorithm_Array_Rotation.py │ ├── Rotation_Count_Of_Array.py │ └── maximize_sum_for_all_rotations_given_array.py ├── Hackerearth ├── Akash_and_GCD1.py ├── BYJU_Developer_Hiring_Challenge │ ├── Manhattan_Matrix.py │ ├── Manhattan_Matrix_Question_snip.JPG │ ├── Manhattan_Matrix_Question_snip2.JPG │ ├── Tournament_Q1.JPG │ ├── Tournament_Q2.JPG │ └── tournament.py ├── Capillary_Java_Hiring_Challenge │ ├── InfiniteArrays_image2.JPG │ ├── InfiniteArrays_image3.JPG │ ├── Infinite_Arrays_Solution.py │ ├── InfinityArrays_Image1.JPG │ ├── Nodes_In_a_SubTree_Count.py │ ├── Nodes_img3.JPG │ ├── Nodes_in_a_SubTree_img1.JPG │ └── Nodes_in_a_SubTree_img2.JPG ├── DynamicProgramming │ └── InversionGraphs.py ├── Fallabella_ReactJS_Hiring_Challenge │ ├── Flip_Bits_image1.png │ ├── Flip_Bits_image2.png │ ├── Sid_and_his_Stone_game.py │ ├── Sids_Stone_game.png │ ├── Sids_Stone_game2.png │ └── flip_the_bits.py ├── FindRequiredSubArray.py ├── Full_Contact_Engineer_Hiring_Challenge │ ├── Circular_Permutation.py │ ├── Circular_Permutation_Question_snip.JPG │ ├── cumulative_XOR_question.JPG │ ├── cumulative_XOR_question_example.JPG │ ├── findCumulativeXor.py │ └── findCumulativeXor_BruteForce.py ├── HSBC_Java_Hiring_Challenge │ ├── HelpJohn.py │ ├── Help_John_img1.png │ ├── Help_John_img2.png │ ├── sam_height_img1.png │ ├── sam_height_img2.png │ └── sam_height_img3.png ├── HaloDoc_Practice_test │ ├── Hackerearth_Practice_Test.png │ ├── Maximum_Mismatches_snip01.png │ ├── Maximum_Mismatches_snip02.png │ ├── String_Minimization_01.png │ ├── String_Minimization_02.png │ ├── countLikesDislikes.py │ └── maximumMismatches.py ├── Hexadecimal_Numbers.py ├── HourStorm#11 │ ├── Deleting_Numbers.py │ ├── Deleting_Numbers_img1.JPG │ └── Deleting_Numbers_img2.JPG ├── HourStorm#12 │ ├── Minimum_Transactions_v1.py │ ├── Minimum_Transactions_v2.py │ ├── minimum_transactions.png │ └── minimum_transactions_img2.png ├── Infrrd_Python_Challenge │ ├── Smallest_Subset_img1.png │ ├── Smallest_Subset_img2.png │ ├── countMe.py │ ├── maximize_palindromes.png │ ├── maximize_palindromes_img2.png │ ├── maximize_palindromic_strings.py │ ├── maximize_palindromic_strings_v2.py │ ├── maximumRowsWithAll1s.py │ ├── problem01.png │ └── problem02.png ├── July_Circuits_2019 │ ├── Largest_Super_Balanced_Bracket_SubSeq.py │ ├── Super_Balanced_Brackets.JPG │ └── Super_Balanced_Brackets_testcases.JPG ├── June_Circuits_2019 │ ├── DetermineWinner01.png │ ├── DetermineWinner02.png │ ├── DetermineWinner_v1.py │ ├── DetermineWinner_v2.py │ ├── README.md │ ├── functionValue01.png │ ├── functionValue02.png │ ├── functionValue_v1.py │ └── functionValue_v2.py ├── June_Easy_2019 │ ├── .gitignore │ ├── CostOfBalloons.png │ ├── CostOfBalloons2.png │ ├── CoverWithMosiaics.cpp │ ├── Mosaics1.png │ ├── Mosaics2.png │ ├── Mosaics3.png │ ├── medianGame.py │ ├── medianGame_V2.py │ └── minimumPurchasingCost.py ├── Largest_SubSeq.py ├── Machine-Learning │ ├── basic_probability.py │ └── conditional_probability.py ├── Micro_Array_Update.py ├── Print_Array_In_Reverse.py ├── README.md ├── Samsung_Developer_Hiring_Challenge │ ├── BitEvenArrays_v0.1.py │ ├── BitEvenArrays_v0.2.py │ └── Bit_Even_Arrays_Question.md ├── Vimeo_Coding_Challenge │ ├── Coloring_Tree.py │ └── Power_Steps.py ├── Vimeo_Full_Stack_Developer_Challenge │ ├── Vimeo_question_01.png │ ├── Vimeo_question_02.png │ └── Vimeo_question_03.png ├── countPositionsOfPartitions.py ├── deleteMinNumberOfDirectories.py ├── isPerfectNumber.py ├── practice_problems │ ├── BalancedPartition.py │ ├── Balanced_Partition_image1.JPG │ ├── Balanced_Partition_image2.JPG │ ├── Balanced_Partition_image3.JPG │ ├── Largest_CoPrime.py │ └── largest_CoPrime.png └── sumOflargestOddDivisiorsModuloM.py ├── Hackerrank ├── Mark_and_Toys.py ├── Marks_and_Toys_v2.py ├── OneMonthPreparationKit │ ├── PlusMinus.go │ ├── go.mod │ └── main.go ├── README.md ├── SQL │ ├── 15DaysOfLearningSQL.sql │ ├── Placements.sql │ └── SymmetricPairs.sql └── countInversions_MergeSort.py ├── InterviewBit ├── Add_Number_One.py ├── ObjectiveQuestion_Arrays.py ├── maxSub_Array.py └── minSteps_in_InfiniteGrid.py ├── KadanesAlgorithm.py ├── LICENSE ├── Last_Occurence_of_element_in_Array.py ├── LeetCode ├── BTNC.py ├── CourseSchedule.py ├── GCDOf2Strings.py ├── Greedy-Algorithms │ └── MinimumMovesToSeat.py ├── MergeAlternately.py ├── NUEL.py ├── ProgrammingInGo │ ├── KidsWithGreatestCandies │ │ └── maximumcandies.go │ ├── MergeAlternately │ │ └── MergeAlternately.go │ ├── MinMovesToSeatEveryone │ │ └── MinMovesToSeatEveryone.go │ ├── README.md │ ├── ReverseWords │ │ └── reverse.go │ ├── canplaceflowers │ │ └── canplaceflowers.go │ ├── dataengineering │ │ ├── removeduplicates │ │ │ └── removeduplicates.go │ │ └── secondlargestelement │ │ │ └── findsecondlargestelement.go │ ├── gcd │ │ └── gcdofstrings.go │ ├── go.mod │ ├── increasingtriplets │ │ └── increasingtripletsequence.go │ ├── main.go │ └── productofelements │ │ └── productexceptself.go ├── README.md ├── SQL50 │ ├── #OfManagersTheirReportees.sql │ ├── #OfUniqueSubjectsByEachTeacher.sql │ ├── %OfUsersAttendedContest.sql │ ├── Atleast5DirectReports.sql │ ├── AverageSellingPrice.sql │ ├── Average_Time_Of_Process_Per_Machine.sql │ ├── BigCountries.sql │ ├── BiggestSingleNumber.sql │ ├── ClassesMoreThan5Students.sql │ ├── ConfirmationRate.sql │ ├── ConsecutiveNumbers.sql │ ├── CountSalaryCategories.sql │ ├── CustWhoVisitedNoTransaction.sql │ ├── CustomersWhoBoughtAllProducts.sql │ ├── DeleteDuplicateEmails.sql │ ├── DepartmentTop3Salaries.sql │ ├── EmployeeBonus.sql │ ├── EmpsManagersLeftCompany.sql │ ├── ExchangeSeats.sql │ ├── FindFollowersCount.sql │ ├── FindUsersValidEmails.sql │ ├── FixNamesInTable.sql │ ├── FriendRequests-II.sql │ ├── GamePlayAnalysisIV.sql │ ├── GroupProductsByDate.sql │ ├── ImmediateFoodDelivery-II.sql │ ├── InvalidTweets.sql │ ├── InvestmentsIn2016.sql │ ├── LastPersonToFitInBus.sql │ ├── ListOfProductsOrdered.sql │ ├── MonthlyTransactions-I.sql │ ├── MovieRating.sql │ ├── NotBoringMovies.sql │ ├── Past30DaysUserActivity.sql │ ├── Patients_With_Condition.sql │ ├── PrimaryDepartmentOfEmployee.sql │ ├── ProductPriceGivenDate.sql │ ├── ProductSalesAnalysis-III.sql │ ├── ProductSalesAnalysis.sql │ ├── ProjectEmployees-I.sql │ ├── QueriesQuality&Percentage.sql │ ├── README.md │ ├── RestaurantGrowth.sql │ ├── RisingTemperature.sql │ ├── SQL1378.sql │ ├── SecondHighestSalary.sql │ ├── StudentsAndExaminations.sql │ └── TriangleJudgement.sql └── SetZeroesMatrix.py ├── LinearSearch.py ├── LinkedLists ├── Creation_of_Linked_List.py ├── Reversal_of_LinkedList.py └── create_linked_list_of_n_nodes.py ├── README.md ├── Skillenza ├── KingsMarch.py ├── KingsMarch1.png ├── KingsMarch2.png └── allPathsInaMatrix.py ├── SortingAlgorithms ├── .gitignore ├── BubbleSort.py ├── InsertionSort.py ├── MergeSort.py ├── QuickSort.py ├── SelectionSort.py └── SelectionSort_v2.py ├── Techgig └── CodeGladiators │ ├── OptimalReordering.py │ └── maximumNumberOfPPuffGirls.py ├── Trees ├── InorderSuccessor.py └── printLeftView_tree.py ├── _config.yml ├── binary_to_string.py ├── clooTrack_Python_Challenge ├── Python_Coding_Assignment.docx └── tweet_frequency.py ├── companyTag.py ├── fibonacci_progression.py ├── find2Numbers_DivisiorsGiven.py ├── gitPython_Plugin.py ├── interviewing.io ├── Airbnb │ ├── README.md │ ├── find_missing.py │ └── reverseString.py ├── Google │ └── generate_graph.py ├── Linkedin │ ├── README.md │ └── pairWithGivenSum.py ├── README.md └── Salesforce │ ├── README.md │ ├── check_rotation.py │ ├── findTheElementOccurringOnce.py │ └── minNumbers.py ├── minDiff_powerof2_N.py ├── modulo_expression.py ├── remAnagram.py ├── sample_question.py ├── simplAssignment ├── SQL_Query_PY.py ├── sampleData.txt ├── simplAssignemnt.zip ├── simplAssignment.py ├── simplCode.txt ├── simplCode_Q1.txt └── sqlQuery_Q2.txt └── sortedArray_Occurrence-nby2.py /COVID-19-21-Day-Coding-Streak/Day-1/MandN.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two positive integers M and N, after adding M and N if number of digits 3 | in M+N and N are same return N otherwise return M+N. 4 | 5 | Input: 6 | First line of input contains T denoting number of testcases. For each test 7 | case there will be two space seperated positive integers M and N. 8 | 9 | Output: 10 | If number of digits in M+N is same as N print N otherwise print M+N. 11 | 12 | Constraints: 13 | 1 <= T <= 100 14 | 1 <= M <= 109 15 | 1 <= N <=109 16 | 17 | Example: 18 | Input: 19 | 2 20 | 44 22 21 | 99 12 22 | 23 | Output: 24 | 22 25 | 111 26 | """ 27 | 28 | 29 | def MandN(M,N): 30 | r = M + N 31 | if len(str(r)) == len(str(N)): 32 | return N 33 | else: 34 | return r 35 | 36 | if __name__ == '__main__': 37 | T = int(input()) 38 | for tc in range(T): 39 | M,N = list(map(int,input().strip().split())) 40 | print (MandN(M, N)) -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-1/README.md: -------------------------------------------------------------------------------- 1 | ## Mathematics 2 | -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-1/SatisfyTheCondition.py: -------------------------------------------------------------------------------- 1 | """ 2 | BRUTE-FORCE Approach 3 | 4 | Given an integer X. Your task is to find out how many positive integers 5 | N ( 1 <= N <= X) satisfy the following condition:- 6 | 7 | 8 | n*(a^n) ≡ b (mod p) 9 | 10 | 11 | Input: 12 | First line of input contains T denoting the number of test cases. For each 13 | test case, the first line contains 4 spaces separated integers denoting values 14 | of a , b , p and X respectively. 15 | 16 | Output: 17 | For each test case, print the number of possible answers N. 18 | 19 | Constraints: 20 | 1 <= T <= 100 21 | 2 <= p <= 106 22 | 1 <= a,b< p 23 | 1 <= X <= 1012 24 | 25 | Example: 26 | Input: 27 | 2 28 | 17 17 19 12 29 | 2 2 3 19 30 | Output: 31 | 1 32 | 7 33 | 34 | """ 35 | 36 | def satisfyTheCondition(a,b,p,X): 37 | count = 0 38 | for g in range(1,X+1): 39 | u = (g*(a**g)) - b 40 | if u%p == 0: 41 | count += 1 42 | else: 43 | continue 44 | return count 45 | 46 | if __name__ == '__main__': 47 | T = int(input()) 48 | for tc in range(T): 49 | a,b,p,X = list(map(int,input().strip().split())) 50 | print (satisfyTheCondition(a,b,p,X)) 51 | -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-1/TriangleAndSquare.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a positive integer B denoting the base of a right angled isosceles triangle. Find the maximum number of squares of size 2×2 units that can fit in it. 3 | 4 | Input: 5 | First line of input contains an integer T denoting number of test cases. For each test case, there exists one line containing integer B ie-base of right angled isosceles triangle. 6 | 7 | Output: 8 | For each test case, print the maximum number of squares that can be fit into the triangle. 9 | 10 | Constraints: 11 | 1<= T <=100 12 | 1<= B <= 1000 13 | 14 | Example: 15 | 16 | Input: 17 | 2 18 | 8 19 | 2 20 | 21 | Output: 22 | 6 23 | 0 24 | """ 25 | 26 | def triangleAndSquare(base): 27 | if base <= 2: 28 | return 0 29 | else: 30 | if base%2 == 0: 31 | base = base - 2 32 | base = base / 2 33 | return int((base * (base + 1)/2)) 34 | else: 35 | base = base - 1 36 | base = base - 2 37 | base = base / 2 38 | return int((base * (base + 1)/2)) 39 | 40 | 41 | if __name__ == '__main__': 42 | T = int(input()) 43 | for tcase in range(T): 44 | b = int(input()) 45 | print (triangleAndSquare(b)) -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-2/README.md: -------------------------------------------------------------------------------- 1 | ## Arrays 2 | -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-3/README.md: -------------------------------------------------------------------------------- 1 | ## Matrix 2 | -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-4/MinimumTimeToPaintHouse-DP.py: -------------------------------------------------------------------------------- 1 | #User function Template for python3 2 | #DP solution 3 | """ 4 | Refer the problem statement from 5 | 6 | https://github.com/absognety/AlgorithmicQuestions/blob/master/COVID-19-21-Day-Coding-Streak/Day-4/MinimumTimeToPaintHouse.py 7 | """ 8 | 9 | def Min_Time(arr,n,k): 10 | #code here 11 | # initialize table 12 | dp = [[0 for i in range(n + 1)] 13 | for j in range(k + 1)] 14 | 15 | # base cases 16 | # k=1 17 | for i in range(1, n + 1): 18 | dp[1][i] = sum(arr[0:i]) 19 | 20 | # n=1 21 | for i in range(1, k + 1): 22 | dp[i][1] = arr[0] 23 | 24 | # 2 to k partitions 25 | for i in range(2, k + 1): # 2 to n boards 26 | for j in range(2, n + 1): 27 | 28 | # track minimum 29 | best = 10000 30 | 31 | # i-1 th separator before position arr[p=1..j] 32 | for p in range(1, j + 1): 33 | best = min(best, max(dp[i - 1][p], 34 | sum(arr[p:j]))) 35 | 36 | dp[i][j] = best 37 | 38 | # required 39 | return dp[k][n] 40 | 41 | 42 | #{ 43 | # Driver Code Starts 44 | #Initial Template for Python 3 45 | 46 | if __name__ == '__main__': 47 | tcs=int(input()) 48 | 49 | for _ in range(tcs): 50 | 51 | k,n=[int(x) for x in input().split()] 52 | 53 | arr=[int(x) for x in input().split()] 54 | 55 | print(Min_Time(arr,n,k)) 56 | # } Driver Code Ends -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-4/README.md: -------------------------------------------------------------------------------- 1 | ## Searching 2 | -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/Day-6/StringCompression.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given a large number of strings which you have to compress. 3 | If the process of compressing them is correctly done, the original 4 | string can be retreived by decompressing the compressed string. The 5 | process of decompressing is shown below : 6 | 1. Lets say the compressed string is ab*c*x 7 | 2. Iterate over the string from left to right, if you find a '*', 8 | remove it, and simply add a duplicate of the string on the left. 9 | Do this process repeatedly till all stars are removed. 10 | 11 | ex: Decompressing : ab*c*d -> ababc*d -> ababcababcd 12 | 13 | Your task is to compress string to its smallest possible form. In case 14 | there are multiple ways to compress a string, prefer the one which return 15 | smaller output. For example, if input is zzzzzzz, output should be z*z*z 16 | and not z**zzz 17 | 18 | Input: First line of input contains number of test cases T. Then T test 19 | cases follow. Each test case contains the string to be shortened in a 20 | newline. Input string consists solely of small case letters. Input will 21 | be read by driver code. 22 | 23 | Output: The shortened string is to be printed as output. Output will be 24 | printed by driver code. 25 | 26 | Your task: Your task is to complete the function compress() which takes 27 | the input string as argument and returns the compressed string. 28 | 29 | Constraints: T <= 500 ; 1 <= |s| <= 105 30 | 31 | Example: 32 | Input: 33 | 2 34 | ababcababcd 35 | zzzzzzz 36 | Output: 37 | ab*c*d 38 | z*z*z 39 | 40 | """ -------------------------------------------------------------------------------- /COVID-19-21-Day-Coding-Streak/README.md: -------------------------------------------------------------------------------- 1 | # GeeksForGeeks - Special 21 Days - Daily Coding Challenges: 2 | 3 | Everyday the coding questions are categorized as per the topic (Mathematics,Arrays,Matrix,Stacks,Queues,....etc). 4 | -------------------------------------------------------------------------------- /Codility/SplitIntoPairs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Split the list of N elements into N/2 pairs such that sum of each pair is odd 3 | and no one element in a pair is common between any set of pairs - any element exists in exactly one pair 4 | """ 5 | import itertools 6 | def solution(A): 7 | all_pairs = list(itertools.combinations(A, 2)) 8 | tracker = set() 9 | result = list() 10 | for t in all_pairs: 11 | if len(result) == 0: 12 | if sum(t) % 2 != 0: 13 | result.append(t) 14 | else: 15 | for pair in result: 16 | tracker = tracker.union(set(pair)) 17 | if not tracker.intersection(set(t)): 18 | if sum(t) % 2 != 0: 19 | result.append(t) 20 | print (result) 21 | final = list() 22 | for r in result: 23 | final.extend(list(r)) 24 | if (set(final) == set(A)) & (len(final) == len(A)): 25 | return True 26 | else: 27 | return False 28 | -------------------------------------------------------------------------------- /Collabedit/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Colorful_Buildings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | # Sample code to perform I/O: 3 | 4 | name = input() # Reading input from STDIN 5 | print('Hi, %s.' % name) # Writing output to STDOUT 6 | 7 | # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 8 | ''' 9 | 10 | 11 | def colorful_ways(n,k): 12 | a = k 13 | b = (k-1)**(n-1) 14 | return (a*b) 15 | 16 | if __name__=='__main__': 17 | T = int(input()) 18 | for tcase in range(T): 19 | N,K = list(map(int,input().strip().split())) 20 | print (colorful_ways(N,K)%((10**9) + 7)) -------------------------------------------------------------------------------- /CormenBook/Chapter_15.1_Rod_Cutting.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | def cut_rod(p,n): 3 | if n == 0: 4 | return 0 5 | q = -1 * np.Inf 6 | for i in range(1,n+1): 7 | q = max(q,p[i]+cut_rod(p,n-i)) 8 | return q -------------------------------------------------------------------------------- /DS_pocketnotes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/DS_pocketnotes.pdf -------------------------------------------------------------------------------- /DailyCodingProblem/AutoCompleteSystem.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #11 3 | This problem was asked by Twitter. 4 | 5 | Implement an autocomplete system. That is, given a query string s and a set 6 | of all possible query strings, return all strings in the set that have s 7 | as a prefix. 8 | 9 | For example, given the query string de and the set of strings 10 | [dog, deer, deal], return [deer, deal]. 11 | 12 | Hint: Try preprocessing the dictionary into a more efficient data 13 | structure to speed up queries. 14 | 15 | """ 16 | 17 | def auto_complete(s,stringset): 18 | return [x for x in stringset if x.startswith(s)] 19 | 20 | if __name__ == '__main__': 21 | T = int(input()) 22 | for tcs in range(T): 23 | s = input() 24 | stringset = input().strip().split() 25 | print (auto_complete(s,stringset)) -------------------------------------------------------------------------------- /DailyCodingProblem/CodeOutput01.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #188 3 | 4 | This problem was asked by Google. 5 | 6 | What will this code print out? 7 | 8 | def make_functions(): 9 | flist = [] 10 | 11 | for i in [1, 2, 3]: 12 | def print_i(): 13 | print(i) 14 | flist.append(print_i) 15 | 16 | return flist 17 | 18 | functions = make_functions() 19 | for f in functions: 20 | f() 21 | How can we make it print out what we apparently want? 22 | 23 | """ 24 | 25 | 26 | def make_functions(): 27 | flist = [] 28 | 29 | for i in [1, 2, 3]: 30 | def print_i(): 31 | print(i) 32 | flist.append(print_i) 33 | 34 | return flist 35 | 36 | functions = make_functions() 37 | for f in functions: 38 | f() 39 | 40 | ## Output 41 | #3 42 | #3 43 | #3 44 | ## Explanation: 45 | # when loop gets completed i is saved as 3 globally, so when we 46 | # initialized make_functions to a variable, all functions should 47 | # return 3 48 | 49 | #Alter function to print what we want -> 1, 2, 3 50 | def make_functions(): 51 | flist = [] 52 | for i in [1, 2, 3]: 53 | def print_i(): 54 | return (i) 55 | flist.append(print_i()) 56 | 57 | return flist 58 | 59 | functions = make_functions() 60 | for f in functions: 61 | print (f) -------------------------------------------------------------------------------- /DailyCodingProblem/CollatzSequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #210 3 | 4 | This problem was asked by Apple. 5 | 6 | A Collatz sequence in mathematics can be defined as follows. Starting 7 | with any positive integer: 8 | 1. if n is even, the next number in the sequence is n / 2 9 | 2. if n is odd, the next number in the sequence is 3n + 1 10 | 3. It is conjectured that every such sequence eventually reaches 11 | the number 1. Test this conjecture. 12 | 13 | Bonus: What input n <= 1000000 gives the longest sequence? 14 | 15 | """ 16 | 17 | def collatz_sequence(n): 18 | count = 0 19 | while True: 20 | if n==1: 21 | count += 1 22 | break 23 | if n%2 == 0: 24 | count += 1 25 | print (n//2,end=" ") 26 | n = n//2 27 | else: 28 | count += 1 29 | print (3*n + 1,end=" ") 30 | n = (3*n) + 1 31 | print ("\nlength of the sequence: ", count) 32 | print ("\n") 33 | 34 | #Testing for various entries of n 35 | collatz_sequence(68) 36 | collatz_sequence(287) 37 | collatz_sequence(29928) 38 | collatz_sequence(1000000) 39 | collatz_sequence(999999) 40 | collatz_sequence(999997) 41 | collatz_sequence(1818288278) 42 | 43 | #999999 will be the input that gives the longest sequence -------------------------------------------------------------------------------- /DailyCodingProblem/Connect4.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #219 3 | 4 | This problem was asked by Salesforce. 5 | 6 | Connect 4 is a game where opponents take turns dropping red or 7 | black discs into a 7 x 6 vertically suspended grid. The game ends 8 | either when one player creates a line of four consecutive discs of 9 | their color (horizontally, vertically, or diagonally), or when 10 | there are no more spots left in the grid. 11 | 12 | 13 | Design and implement Connect 4. 14 | 15 | """ 16 | 17 | def connect4game(m,n): 18 | grid = [[None for i in range(n)] for j in range(m)] 19 | while True: 20 | -------------------------------------------------------------------------------- /DailyCodingProblem/DoesPalindromeExist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #157 3 | 4 | This problem was asked by Amazon. 5 | 6 | Given a string, determine whether any permutation of it is 7 | a palindrome. 8 | 9 | For example, carrace should return true, since it can be 10 | rearranged to form racecar, which is a palindrome. daily 11 | should return false, since there's no rearrangement that can 12 | form a palindrome. 13 | 14 | """ 15 | 16 | import itertools 17 | def checkPalindrome(word): 18 | l = len(word) 19 | for w in itertools.permutations(word,l): 20 | w = "".join(w) 21 | if w == w[::-1]: 22 | return 'true' 23 | return 'false' 24 | 25 | print (checkPalindrome('carrace')) 26 | print (checkPalindrome('daily')) -------------------------------------------------------------------------------- /DailyCodingProblem/IsReachEndOfArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #192 3 | 4 | This problem was asked by Google. 5 | 6 | You are given an array of nonnegative integers. Let's say you start 7 | at the beginning of the array and are trying to advance to the end. 8 | You can advance at most, the number of steps that you're currently on. 9 | Determine whether you can get to the end of the array. 10 | 11 | For example, given the array [1, 3, 1, 2, 0, 1], we can go from 12 | indices 0 -> 1 -> 3 -> 5, so return true. 13 | 14 | Given the array [1, 2, 1, 0, 0], we can't reach the end, so return false. 15 | """ 16 | 17 | import math 18 | def min_jumps(arr,n): 19 | if n==1: 20 | return 0 21 | res = math.inf 22 | for i in range(n-2,-1,-1): 23 | if (i + arr[i]) >= n-1: 24 | sub_res = min_jumps(arr,i+1) 25 | if (sub_res != math.inf): 26 | res = min(res,sub_res + 1) 27 | return res 28 | 29 | def advance_to_end(arr,n): 30 | x = min_jumps(arr,n) 31 | if x > 0 and x != math.inf: 32 | return "true" 33 | elif x == 0 or x == math.inf: 34 | return "false" 35 | 36 | if __name__ == '__main__': 37 | for tcase in range(int(input())): 38 | arr = list(map(int,input().strip().split())) 39 | print (advance_to_end(arr,len(arr))) -------------------------------------------------------------------------------- /DailyCodingProblem/JobScheduler.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #10 3 | This problem was asked by Apple. 4 | 5 | Implement a job scheduler which takes in a function f and an integer n, 6 | and calls f after n milliseconds. 7 | 8 | Sol: The solution demonstrated here is simplified version of event scheduling 9 | program 10 | 11 | But for more efficient workflow management and monitoring frameworks, please 12 | explore: 13 | 1. Prefect (https://www.prefect.io/) 14 | 2. Airflow (The Apache software foundation) 15 | 3. Crontab (Linux command line tool) 16 | """ 17 | import time 18 | def f(a,b): 19 | s = a + b 20 | print ("the sum of 2 numbers {},{} is {}".format(a,b,s)) 21 | d = abs(a-b) 22 | print ("the absolute difference of 2 numbers {},{} is {}".format(a,b,d)) 23 | product = a*b 24 | print ("the product of 2 numbers {},{} is {}".format(a,b,product)) 25 | if b != 0: 26 | div = a/b 27 | print ("the division answer of 2 numbers {},{} is {}".format(a,b,div)) 28 | else: 29 | print ("the division of two numbers is not possible") 30 | 31 | def scheduler(f,m,n): 32 | f(m,n) 33 | 34 | if __name__ == '__main__': 35 | n = int(input()) 36 | while True: 37 | time.sleep(n/1000) 38 | scheduler(f,34,17) 39 | break -------------------------------------------------------------------------------- /DailyCodingProblem/LongestCommonSubsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #209 3 | 4 | This problem was asked by YouTube. 5 | 6 | Write a program that computes the length of the longest common 7 | subsequence of three given strings. For example, given "epidemiologist", 8 | "refrigeration", and "supercalifragilisticexpialodocious", it should 9 | return 5, since the longest common subsequence is "eieio". 10 | 11 | """ 12 | #Substrings need to be contiguous where as subsequences are not. 13 | #Two types of solutions: 14 | # 1. Overlapping subproblems using recursion 15 | # 2. DP problem 16 | 17 | def lcs(X,Y): 18 | m = len(X) 19 | n = len(Y) 20 | dp = [[0 for i in range(n+1)] for j in range(m+1)] 21 | for i in range(m+1): 22 | for j in range(n+1): 23 | if (i==0) or (j==0): 24 | dp[i][j] = 0 25 | elif X[i-1] == Y[j-1]: 26 | dp[i][j] = dp[i-1][j-1] + 1 27 | else: 28 | dp[i][j] = max(dp[i-1][j],dp[i][j-1]) 29 | return dp[m][n] 30 | 31 | if __name__ == '__main__': 32 | X = "AGGTAB" 33 | Y = "GXTXAYB" 34 | print ("Length of longest common subsequence: ",lcs(X,Y)) 35 | st1 = "epidemiologist" 36 | st2 = "refrigeration" 37 | st3 = "supercalifragilisticexpialodocious" 38 | print ("Length of longest common subsequence: ", 39 | min(lcs(st1,st2),lcs(st2,st3),lcs(st1,st3))) -------------------------------------------------------------------------------- /DailyCodingProblem/LongestSubArrayOfDistinctElements.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #189 3 | 4 | This problem was asked by Google. 5 | 6 | Given an array of elements, return the length of the longest 7 | subarray where all its elements are distinct. 8 | 9 | For example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 10 | as the longest subarray of distinct elements is [5, 2, 3, 4, 1]. 11 | 12 | """ 13 | 14 | ###Using itertools 15 | import itertools 16 | def longest_subarray_distinct(arr): 17 | if len(arr) == 0: 18 | return 0 19 | if len(arr) == 1: 20 | return len(arr) 21 | for l in range(len(arr),0,-1): 22 | subarrays = set(itertools.combinations(arr, l)) 23 | for suba in subarrays: 24 | if len(suba) == len(set(suba)): 25 | return len(suba) 26 | return 0 27 | 28 | print (longest_subarray_distinct([5, 1, 3, 5, 2, 3, 4, 1])) -------------------------------------------------------------------------------- /DailyCodingProblem/NthSevenishNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #221 3 | 4 | This problem was asked by Zillow. 5 | 6 | Let's define a "sevenish" number to be one which is either a power 7 | of 7, or the sum of unique powers of 7. The first few sevenish 8 | numbers are 1, 7, 8, 49, and so on. Create an algorithm to find the 9 | nth sevenish number. 10 | 11 | """ 12 | 13 | import itertools 14 | def nth_sevenish_number(n): 15 | a = 0 16 | i = 0 17 | sevenish_powers = [] 18 | sums = [] 19 | while True: 20 | #print (sevenish_powers) 21 | #print (sums) 22 | if i == n: 23 | break 24 | if len(sevenish_powers) < 2: 25 | sevenish_powers.append(pow(7,a)) 26 | else: 27 | for r in range(2,len(sevenish_powers)+1): 28 | combinations = itertools.combinations(sevenish_powers, 29 | r) 30 | for c in combinations: 31 | sums.append(sum(c)) 32 | sevenish_powers.append(pow(7,a)) 33 | a,i = a + 1, i + 1 34 | union = set(sevenish_powers).union(set(sums)) 35 | union = sorted(list(union)) 36 | return union[n-1],union[:25] 37 | 38 | 39 | print (nth_sevenish_number(5)) 40 | print (nth_sevenish_number(15)) 41 | print (nth_sevenish_number(20)) 42 | print (nth_sevenish_number(28)) -------------------------------------------------------------------------------- /DailyCodingProblem/Problem424.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #424 3 | 4 | This problem was asked by Facebook. 5 | 6 | Given an array of integers in which two elements appear exactly once 7 | and all other elements appear exactly twice, find the two elements 8 | that appear only once. 9 | 10 | For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and 8. The order does not matter. 11 | 12 | Follow-up: Can you do this in linear time and constant space? 13 | 14 | """ 15 | 16 | import collections 17 | def findElementsByCount(arr,c): 18 | collect_elements = set() 19 | hashMap = collections.Counter(arr) 20 | for k,v in hashMap.items(): 21 | if v == c: 22 | collect_elements.add(k) 23 | return collect_elements 24 | 25 | arr = [2, 4, 6, 8, 10, 2, 6, 10] 26 | c = 1 27 | print (findElementsByCount(arr, c)) 28 | c = 2 29 | print (findElementsByCount(arr, c)) -------------------------------------------------------------------------------- /DailyCodingProblem/Problem438.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #438 3 | 4 | This problem was asked by Amazon. 5 | 6 | Implement a stack API using only a heap. A stack implements the 7 | following methods: 8 | 9 | push(item), which adds an element to the stack 10 | pop(), which removes and returns the most recently added element 11 | (or throws an error if there is nothing on the stack) 12 | Recall that a heap has the following operations: 13 | 14 | push(item), which adds a new key to the heap 15 | pop(), which removes and returns the max value of the heap 16 | 17 | Solution: 18 | Duplicate of daily coding problem #154 - `implementStackWithHeap.py` 19 | 20 | """ -------------------------------------------------------------------------------- /DailyCodingProblem/Problem446.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #446 3 | 4 | This problem was asked by Indeed. 5 | 6 | Given a 32-bit positive integer N, determine whether it is a power 7 | of four in faster than O(log N) time. 8 | 9 | """ 10 | 11 | import math 12 | def isPowerOf4(N:int) -> bool: 13 | d = str(math.log(N,4)) 14 | if d.split(".")[1] == "0": 15 | return True 16 | else: 17 | return False 18 | 19 | print (isPowerOf4(256)) 20 | print (isPowerOf4(128)) 21 | print (isPowerOf4(1024)) 22 | print (isPowerOf4(1023)) -------------------------------------------------------------------------------- /DailyCodingProblem/Problem447.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #447 3 | 4 | This problem was asked by Google. 5 | 6 | Implement integer exponentiation. That is, implement the pow(x, y) 7 | function, where x and y are integers and returns x^y. 8 | 9 | Do this faster than the naive method of repeated multiplication. 10 | 11 | For example, pow(2, 10) should return 1024. 12 | 13 | """ 14 | 15 | import sys 16 | sys.setrecursionlimit(100000) 17 | def powxy(x,y): 18 | if y == 1: 19 | return x 20 | elif y == 0: 21 | return 1 22 | elif y > 0: 23 | return (x * powxy(x,y-1)) 24 | elif y < 0: 25 | res = x * powxy(x,(-1 * y)-1) 26 | return 1/res 27 | 28 | print (powxy(2, 4)) 29 | print (powxy(3,89)) 30 | print (powxy(4,-34)) 31 | print (powxy(5,-46)) 32 | print (powxy(4, 1999)) -------------------------------------------------------------------------------- /DailyCodingProblem/README.md: -------------------------------------------------------------------------------- 1 | ## Please Subscribe here: https://www.dailycodingproblem.com/ 2 | To get Daily Coding problems to your email 3 | 4 | Following problems have been completed: 5 | ``` 6 | 11,188,153,157,192,27,10,189,127,128,6, 7 | 1,14,163,185,80(nc),140,20(nc),155,125,152,102,2,103, 8 | 141,154,25,123,28,9,4,160,24(nc),17,190,122,130,19,23(nc), 9 | 135,191,21,150,8(nc),5,186,143,7,22,16,159,26,151,161,126,29,3, 10 | 162,147,129,149,198,197,199,206,205,203,202,201,207,209,208,210,195, 11 | 212,211,213,218,217,216,221,231,232,240,236,258,390,393,419,417,420, 12 | 431,439,438 13 | ``` 14 | `nc` means problem statement has been added but solution hasn't been added. Above list will be updated very often. 15 | Not all the solutions have been developed by myself, but I managed to solve few questions with help from several resources on the web, my intention is to make this one stop shop for daily coding problem solutions for candidates looking to practice algorithms. 16 | 17 | ## If you find these solutions helpful in cracking your coding tests and interviews, Please give a star to this repo. 18 | -------------------------------------------------------------------------------- /DailyCodingProblem/applyPermutation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #206 3 | 4 | This problem was asked by Twitter. 5 | 6 | A permutation can be specified by an array P, where P[i] represents 7 | the location of the element at i in the permutation. For example, 8 | [2, 1, 0] represents the permutation where elements at the index 0 and 9 | 2 are swapped. 10 | 11 | Given an array and a permutation, apply the permutation to the array. 12 | For example, given the array ["a", "b", "c"] and the permutation 13 | [2, 1, 0], return ["c", "b", "a"]. 14 | 15 | """ 16 | 17 | def apply_permutation(arr,P): 18 | new_arr = [] 19 | for i in range(len(arr)): 20 | new_arr.append(arr[P[i]]) 21 | return new_arr 22 | 23 | print (apply_permutation(["a","b","c"],[2,1,0])) -------------------------------------------------------------------------------- /DailyCodingProblem/checkPairsWithGivenSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #1 3 | This problem was recently asked by Google. 4 | 5 | Given a list of numbers and a number k, return whether any two numbers from the 6 | list add up to k. 7 | 8 | For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. 9 | """ 10 | 11 | 12 | def isPairWithGivenSum(arr,n,x): 13 | left,right = 0,n-1 14 | arr = sorted(arr) 15 | while left < right: 16 | if ((arr[left] + arr[right]) < x): 17 | left += 1 18 | elif (arr[left] + arr[right] == x): 19 | return True 20 | elif (arr[left] + arr[right] > x): 21 | right -= 1 22 | return False 23 | 24 | if __name__ == '__main__': 25 | T = int(input()) 26 | for tcs in range(T): 27 | arr = list(map(int,input().strip().split())) 28 | n = len(arr) 29 | x = int(input()) 30 | print (isPairWithGivenSum(arr,n,x)) -------------------------------------------------------------------------------- /DailyCodingProblem/convertRomanToDecimal.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Daily Coding Problem #216 4 | 5 | This problem was asked by Facebook. 6 | 7 | Given a number in Roman numeral format, convert it to decimal. 8 | 9 | The values of Roman numerals are as follows: 10 | 11 | { 12 | 'M': 1000, 13 | 'D': 500, 14 | 'C': 100, 15 | 'L': 50, 16 | 'X': 10, 17 | 'V': 5, 18 | 'I': 1 19 | } 20 | In addition, note that the Roman numeral system uses subtractive 21 | notation for numbers such as IV and XL. 22 | 23 | For the input XIV, for instance, you should return 14. 24 | 25 | 26 | """ 27 | 28 | home = { 29 | 'M': 1000, 30 | 'D': 500, 31 | 'C': 100, 32 | 'L': 50, 33 | 'X': 10, 34 | 'V': 5, 35 | 'I': 1 36 | } 37 | 38 | def roman2decimal(numeral): 39 | symbols = list(numeral) 40 | total = 0 41 | for i in range(len(symbols)-1): 42 | if home[symbols[i]] >= home[symbols[i+1]]: 43 | total += home[symbols[i]] 44 | else: 45 | total += (home[symbols[i+1]] - home[symbols[i]]) 46 | return total 47 | 48 | print (roman2decimal("XIV")) 49 | print (roman2decimal("IV")) 50 | print (roman2decimal("XL")) 51 | print (roman2decimal("XXIV")) -------------------------------------------------------------------------------- /DailyCodingProblem/estimatePiMonteCarlo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #14 3 | 4 | This problem was asked by Google. 5 | 6 | The area of a circle is defined as πr^2. Estimate π to 3 decimal 7 | places using a Monte Carlo method. 8 | 9 | Hint: The basic equation of a circle is x2 + y2 = r2. 10 | 11 | please refer: https://www.geeksforgeeks.org/estimating-value-pi-using-monte-carlo/ 12 | for the theory 13 | 14 | """ 15 | 16 | import numpy as np 17 | interval = int(input()) 18 | circle_points = 0 19 | square_points = 0 20 | 21 | i = 0 22 | while (i < (interval ** 2)): 23 | rand_x = np.random.uniform(-1,1) 24 | rand_y = np.random.uniform(-1,1) 25 | d = np.square(rand_x) + np.square(rand_y) 26 | if d <= 1: 27 | circle_points += 1 28 | square_points += 1 29 | pi = 4 * (np.divide(circle_points,square_points)) 30 | i += 1 31 | 32 | #final estimation of final Pi value 33 | print (pi) -------------------------------------------------------------------------------- /DailyCodingProblem/evaluatePostfixExpression.py: -------------------------------------------------------------------------------- 1 | #!/media/vikas/Data/Files/favpython/bin/python3 2 | 3 | """ 4 | Daily Coding Problem #163 5 | 6 | This problem was asked by Jane Street. 7 | 8 | Given an arithmetic expression in Reverse Polish Notation, 9 | write a program to evaluate it. 10 | 11 | The expression is given as a list of numbers and operands. 12 | For example: [5, 3, '+'] should return 5 + 3 = 8. 13 | 14 | For example, 15 | [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] 16 | should return 5, since it is equivalent to 17 | ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5. 18 | 19 | You can assume the given expression is always valid. 20 | 21 | """ 22 | 23 | def evaluate_postfix_exp(exp): 24 | stack = [] 25 | d = 0 26 | while (d <= len(exp)-1): 27 | if exp[d] in ['+','-','/','*']: 28 | if (len(stack) != 0) and (len(stack) >= 2): 29 | opd1 = stack.pop() 30 | opd2 = stack.pop() 31 | res = eval('{}{}{}'.format(opd2,exp[d],opd1)) 32 | stack.append(res) 33 | if isinstance(exp[d],int): 34 | stack.append(exp[d]) 35 | d += 1 36 | assert len(stack) == 1,"re-check your solution" 37 | return stack[0] 38 | 39 | print (evaluate_postfix_exp([5, 3, '+'])) 40 | print (evaluate_postfix_exp([15, 7, 1, 1, '+', 41 | '-', '/', 3, '*', 2, 1, 1, 42 | '+', '+', '-'])) 43 | print (evaluate_postfix_exp([2,3,1,'*','+',9,'-'])) -------------------------------------------------------------------------------- /DailyCodingProblem/findAllIndices.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #211 3 | 4 | This problem was asked by Microsoft. 5 | 6 | Given a string and a pattern, find the starting indices of all 7 | occurrences of the pattern in the string. For example, given the string 8 | "abracadabra" and the pattern "abr", you should return [0, 7]. 9 | 10 | """ 11 | 12 | import re 13 | def find_pattern(pattern,string): 14 | indices = [] 15 | for m in re.finditer(pattern,string): 16 | indices.append(m.span()[0]) 17 | return indices 18 | 19 | if __name__ == '__main__': 20 | pattern = "abr" 21 | string = "abracadabra" 22 | print (find_pattern(pattern,string)) 23 | pattern = "eee" 24 | string = "bsbsnsnnsqeiieee@$ghhg88888****eeednjdjskan!!!!^%&" 25 | print (find_pattern(pattern,string)) -------------------------------------------------------------------------------- /DailyCodingProblem/findBalancedStringWithMinimumInsertionsDeletions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #430 3 | 4 | This problem was asked by Facebook. 5 | 6 | Given a string of parentheses, find the balanced string that can be 7 | produced from it using the minimum number of insertions and deletions. 8 | If there are multiple solutions, return any of them. 9 | 10 | For example, given "(()", you could return "(())". Given "))()(", 11 | you could return "()()()()". 12 | 13 | Refer Problem #199 solution - `balancedParenthesis.py` 14 | 15 | """ 16 | 17 | -------------------------------------------------------------------------------- /DailyCodingProblem/findDeepestNode.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem # 80 3 | 4 | This problem was asked by Google. 5 | 6 | Given the root of a binary tree, return a deepest node. For example, in the following tree, return d. 7 | 8 | a 9 | / \ 10 | b c 11 | / 12 | d 13 | 14 | """ -------------------------------------------------------------------------------- /DailyCodingProblem/findElementsAppearingExactlyOnce.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #140 3 | 4 | This problem was asked by Facebook. 5 | 6 | Given an array of integers in which two elements appear exactly once and 7 | all other elements appear exactly twice, find the two elements that appear 8 | only once. 9 | 10 | For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and 8. 11 | The order does not matter. 12 | 13 | Follow-up: Can you do this in linear time and constant space? 14 | 15 | """ 16 | import collections 17 | 18 | def find_elements(arr): 19 | ind = None 20 | for e in arr: 21 | if arr.count(e) == 1: 22 | print (e) 23 | ind = 1 24 | if not ind: 25 | print ("No elements occurs exactly once") 26 | 27 | 28 | def find_elements2(arr): 29 | freqs = collections.Counter(arr) 30 | ind = None 31 | for key,val in freqs.items(): 32 | if val == 1: 33 | print (key) 34 | ind = 1 35 | if not ind: 36 | print ("No elements occurs exactly once") 37 | 38 | 39 | if __name__ == '__main__': 40 | for tc in range(int(input())): 41 | arr = list(map(int,input().strip().split())) 42 | find_elements(arr) 43 | find_elements2(arr) -------------------------------------------------------------------------------- /DailyCodingProblem/findIntersectionNode.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Daily Coding Problem #20 4 | 5 | This problem was asked by Google. 6 | 7 | Given two singly linked lists that intersect at some point, find the 8 | intersecting node. The lists are non-cyclical. 9 | 10 | For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return 11 | the node with value 8. 12 | 13 | In this example, assume nodes with the same value are the exact same node 14 | objects. 15 | 16 | Do this in O(M + N) time (where M and N are the lengths of the lists) and 17 | constant space. 18 | 19 | """ -------------------------------------------------------------------------------- /DailyCodingProblem/findLargestRange.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #393 3 | 4 | This problem was asked by Airbnb. 5 | 6 | Given an array of integers, return the largest range, 7 | inclusive, of integers that are all included in the array. 8 | 9 | For example, given the array [9, 6, 1, 3, 8, 10, 12, 11], 10 | return (8, 12) since 8, 9, 10, 11, and 12 are all in the array. 11 | 12 | """ 13 | 14 | def find_largest_range(arr): 15 | max_element = max(arr) 16 | all_ranges = [] 17 | for a in sorted(arr): 18 | i = a 19 | collect_ranges = [] 20 | while (i <= max_element): 21 | if i in arr: 22 | collect_ranges.append(i) 23 | else: 24 | break 25 | i += 1 26 | all_ranges.append(collect_ranges) 27 | sorted_ranges = sorted(all_ranges,key=lambda r: len(r),reverse=True) 28 | print (sorted_ranges) 29 | return (sorted_ranges[0][0],sorted_ranges[0][-1]) 30 | 31 | if __name__ == '__main__': 32 | arr = [9,6,1,3,8,10,12,11] 33 | print (find_largest_range(arr)) 34 | 35 | arr = [0,5,8,9,23,24,25,34,40,41,42,43] 36 | print (find_largest_range(arr)) -------------------------------------------------------------------------------- /DailyCodingProblem/findMajorityElementInSeq.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem: Problem #155 3 | 4 | This problem was asked by MongoDB. 5 | 6 | Given a list of elements, find the majority element, 7 | which appears more than half the time (> floor(len(lst) / 2.0)). 8 | 9 | You can assume that such element exists. 10 | 11 | For example, given [1, 2, 1, 1, 3, 4, 0], return 1. 12 | 13 | """ 14 | 15 | import collections 16 | import math 17 | def majority_element(arr): 18 | hash_map = collections.Counter(arr) 19 | l = len(arr) 20 | for key,value in hash_map.items(): 21 | if value >= math.floor(l / 2.0): 22 | return key 23 | return -1 24 | 25 | print (majority_element([1, 2, 1, 1, 3, 4, 0])) -------------------------------------------------------------------------------- /DailyCodingProblem/findMissingNumbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #390 3 | 4 | This problem was asked by Two Sigma. 5 | 6 | You are given an unsorted list of 999,000 unique integers, each from 1 7 | and 1,000,000. Find the missing 1000 numbers. What is the computational 8 | and space complexity of your solution? 9 | 10 | """ 11 | 12 | def missing_numbers(full_list,given_list): 13 | result = set(full_list)-set(given_list) 14 | print (len(result)) 15 | return result 16 | 17 | if __name__ == '__main__': 18 | t = int(input()) 19 | for tc in range(t): 20 | full_list = range(1,1000001) 21 | given_list = range(5,999005) 22 | print (missing_numbers(full_list, given_list)) -------------------------------------------------------------------------------- /DailyCodingProblem/findSparseNumber.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3.8 2 | 3 | """ 4 | Daily Coding Problem #217 5 | 6 | This problem was asked by Oracle. 7 | 8 | We say a number is sparse if there are no adjacent ones in its 9 | binary representation. For example, 21 (10101) is sparse, but 22 10 | (10110) is not. For a given input N, find the smallest sparse number 11 | greater than or equal to N. 12 | 13 | Do this in faster than O(N log N) time. 14 | 15 | """ 16 | 17 | def find_sparse_number(N): 18 | while True: 19 | binary_rep = bin(N)[2:] 20 | if binary_rep.count('1') == 1: 21 | return N 22 | c = binary_rep.find('1') 23 | if c == -1: 24 | pass 25 | else: 26 | checker = [] 27 | s = c + 1 28 | for j in range(s,len(binary_rep)): 29 | if binary_rep[j] == '1': 30 | if (j - c) == 1: 31 | checker.append(False) 32 | c = j 33 | else: 34 | checker.append(True) 35 | c = j 36 | print (checker) 37 | if len(set(checker)) == 1: 38 | if True in checker: 39 | return N 40 | N += 1 41 | 42 | #Testcases for finding sparse numbers 43 | print (find_sparse_number(19)) 44 | print (find_sparse_number(26)) 45 | print (find_sparse_number(39)) -------------------------------------------------------------------------------- /DailyCodingProblem/generateNumbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #152 3 | 4 | This problem was asked by Triplebyte. 5 | 6 | You are given n numbers as well as n probabilities that sum up 7 | to 1. Write a function to generate one of the numbers with its 8 | corresponding probability. 9 | 10 | For example, given the numbers [1, 2, 3, 4] and probabilities 11 | [0.1, 0.5, 0.2, 0.2], your function should return 1 10% of the 12 | time, 2 50% of the time, and 3 and 4 20% of the time. 13 | 14 | You can generate random numbers between 0 and 1 uniformly. 15 | 16 | """ 17 | 18 | import random 19 | def generate_numbers(numbers,probs): 20 | n = len(numbers) 21 | #generate a random number between 0 and 1 22 | r = random.uniform(0, 1) 23 | total = probs[0] 24 | for i in range(1,n+1): 25 | if r <= total: 26 | return (numbers[i-1]) 27 | total += probs[i] 28 | return ("non-zero exit status") 29 | 30 | #Test the function 31 | numbers = [1,2,3,4] 32 | probs = [0.1,0.5,0.2,0.2] 33 | print (generate_numbers(numbers, probs)) -------------------------------------------------------------------------------- /DailyCodingProblem/getElementsWhoseSumIsK.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding problem #102 3 | 4 | This problem was asked by Lyft. 5 | 6 | Given a list of integers and a number K, return which contiguous 7 | elements of the list sum to K. 8 | 9 | For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should 10 | return [2, 3, 4], since 2 + 3 + 4 = 9. 11 | 12 | """ 13 | 14 | def allSubArrays(L,L2=None): 15 | if L2==None: 16 | L2 = L[:-1] 17 | if L==[]: 18 | if L2==[]: 19 | return [] 20 | return allSubArrays(L2,L2[:-1]) 21 | return [L]+allSubArrays(L[1:],L2) 22 | 23 | 24 | # return any list that sum to K 25 | def get_elements(arr,k): 26 | for sub_arr in allSubArrays(arr): 27 | if sum(sub_arr) == k: 28 | return sub_arr 29 | return -1 30 | 31 | #print all sub-arrays that sum to k 32 | def get_elements_all(arr,k): 33 | for sub_arr in allSubArrays(arr): 34 | if sum(sub_arr) == k: 35 | print ("\n\nSecond function: ", sub_arr) 36 | return 37 | 38 | 39 | if __name__ == '__main__': 40 | for tcase in range(T:=int(input())): 41 | arr = list(map(int,input().strip().split())) 42 | k = int(input()) 43 | print ("First function: ",get_elements(arr, k)) 44 | get_elements_all(arr, k) -------------------------------------------------------------------------------- /DailyCodingProblem/getNewArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #2 3 | Given an array of integers, return a new array such that each element at index i 4 | of the new array is the product of all the numbers in the original array except 5 | the one at i. 6 | 7 | For example, if our input was [1, 2, 3, 4, 5], the expected output would be 8 | [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be 9 | [2, 3, 6]. 10 | """ 11 | 12 | def productOfArray(arr): 13 | prod = 1 14 | for a in arr: 15 | prod = prod * a 16 | return prod 17 | 18 | def newArray(arr): 19 | n = len(arr) 20 | new_arr = [None]*n 21 | for i in range(n): 22 | item = arr.pop(i) 23 | x = productOfArray(arr) 24 | new_arr[i] = x 25 | arr.insert(i,item) 26 | return new_arr 27 | 28 | if __name__ == '__main__': 29 | T = int(input()) 30 | for tcs in range(T): 31 | arr = list(map(int,input().strip().split())) 32 | print (newArray(arr)) -------------------------------------------------------------------------------- /DailyCodingProblem/getNthPerfectNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #420 3 | 4 | This problem was asked by Microsoft. 5 | 6 | A number is considered perfect if its digits sum up to exactly 7 | 10. 8 | 9 | Given a positive integer n, return the n-th perfect number. 10 | 11 | For example, given 1, you should return 19. Given 2, you 12 | should return 28. 13 | 14 | """ 15 | 16 | def getPerfectNumber(n): 17 | x = 11 18 | rank = 0 19 | while True: 20 | digits = [int(i) for i in list(str(x))] 21 | if sum(digits) == 10: 22 | rank += 1 23 | if rank == n: 24 | return x 25 | x += 1 26 | 27 | print (getPerfectNumber(1)) 28 | print (getPerfectNumber(2)) 29 | print (getPerfectNumber(3)) 30 | print (getPerfectNumber(4)) 31 | print (getPerfectNumber(20)) 32 | print (getPerfectNumber(100)) -------------------------------------------------------------------------------- /DailyCodingProblem/get_shortest_substring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #103 3 | This problem was asked by Square 4 | 5 | Given a string and a set of characters, return the shortest substring 6 | containing all the characters in the set. 7 | 8 | For example, given the string "figehaeci" and the set of characters 9 | {a, e, i}, you should return "aeci". 10 | 11 | If there is no substring containing all the characters in the set, 12 | return null. 13 | 14 | """ 15 | 16 | chars = {'a','e','i'} 17 | def getShortestSubstring(s): 18 | length = len(s) 19 | alist = [] 20 | for i in range(length): 21 | for j in range(i,length): 22 | if chars.issubset(s[i:j+1]): 23 | alist.append(s[i:j+1]) 24 | if not alist: 25 | return "null" 26 | result = alist[0] 27 | for sbs in alist[1:]: 28 | if len(sbs) < len(result): 29 | result = sbs 30 | return result 31 | 32 | 33 | if __name__ == '__main__': 34 | T = int(input()) 35 | while (T > 0): 36 | s = input() 37 | print (getShortestSubstring(s)) 38 | T -= 1 -------------------------------------------------------------------------------- /DailyCodingProblem/implement3StacksSingleList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #141 3 | 4 | This problem was asked by Microsoft. 5 | 6 | Implement 3 stacks using a single list: 7 | 8 | class Stack: 9 | def __init__(self): 10 | self.list = [] 11 | 12 | def pop(self, stack_number): 13 | pass 14 | 15 | def push(self, item, stack_number): 16 | pass 17 | 18 | """ 19 | 20 | class Stack: 21 | def __init__(self): 22 | self.list = [[],[],[]] 23 | 24 | def pop(self, stack_number): 25 | if len(self.list[stack_number-1]) == 0: 26 | print ("stack underflow") 27 | return 28 | res = self.list[stack_number-1].pop() 29 | return res 30 | 31 | def push(self, item, stack_number): 32 | self.list[stack_number-1].append(item) 33 | 34 | ##testing my class 35 | coins = Stack() 36 | coins.push(34, 3) 37 | coins.push(2,1) 38 | coins.push(100,2) 39 | coins.push(101, 2) 40 | coins.push(28,3) 41 | print (coins.list) 42 | coins.pop(3) 43 | coins.pop(1) 44 | coins.pop(1) 45 | print (coins.list) -------------------------------------------------------------------------------- /DailyCodingProblem/implementPrefixMapSum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #232 3 | 4 | This problem was asked by Google. 5 | 6 | Implement a PrefixMapSum class with the following methods: 7 | 8 | insert(key: str, value: int): Set a given key's value in the map. If the 9 | key already exists, overwrite the value. 10 | sum(prefix: str): Return the sum of all values of keys that begin with a 11 | given prefix. 12 | For example, you should be able to run the following code: 13 | 14 | mapsum.insert("columnar", 3) 15 | assert mapsum.sum("col") == 3 16 | 17 | mapsum.insert("column", 2) 18 | assert mapsum.sum("col") == 5 19 | 20 | """ 21 | 22 | class PrefixMapSum(object): 23 | 24 | def __init__(self): 25 | self.map = dict() 26 | 27 | def insert(self,key:str,value:int) -> None: 28 | self.map[key] = value 29 | 30 | def total(self,prefix:str) -> int: 31 | sums = 0 32 | if self.map: 33 | for k in self.map: 34 | if k.startswith(prefix): 35 | sums += self.map[k] 36 | return sums 37 | 38 | if __name__ == '__main__': 39 | mapsum = PrefixMapSum() 40 | mapsum.insert("columnar",3) 41 | assert mapsum.total("col") == 3, "Not matched" 42 | mapsum.insert("column", 2) 43 | assert mapsum.total("col") == 5, "Not matched" 44 | -------------------------------------------------------------------------------- /DailyCodingProblem/isIntegerPalindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #202 3 | 4 | This problem was asked by Palantir. 5 | 6 | Write a program that checks whether an integer is a palindrome. 7 | For example, 121 is a palindrome, as well as 888. 678 is not a 8 | palindrome. Do not convert the integer into a string. 9 | 10 | """ 11 | 12 | def isIntegerPalindrome(num): 13 | if len(str(num)) == 0: 14 | return "empty string" 15 | if len(str(num)) == 1 and str(num).isdigit(): 16 | return True 17 | digits = [] 18 | if (num%10) == 0: 19 | return False 20 | while (num%10 != 0): 21 | digits.append(num%10) 22 | num = num//10 23 | if digits == digits[::-1]: 24 | return True 25 | return False 26 | 27 | print (isIntegerPalindrome(888)) 28 | print (isIntegerPalindrome(121)) 29 | print (isIntegerPalindrome(678)) 30 | print (isIntegerPalindrome(234432)) 31 | print (isIntegerPalindrome(23)) 32 | print (isIntegerPalindrome("")) 33 | print (isIntegerPalindrome(8)) -------------------------------------------------------------------------------- /DailyCodingProblem/isStringANumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #123 3 | 4 | This problem was asked by LinkedIn. 5 | 6 | Given a string, return whether it represents a number. Here are the 7 | different kinds of numbers: 8 | 9 | "10", a positive integer 10 | "-10", a negative integer 11 | "10.1", a positive real number 12 | "-10.1", a negative real number 13 | "1e5", a number in scientific notation 14 | And here are examples of non-numbers: 15 | 16 | "a" 17 | "x 1" 18 | "a -2" 19 | "-" 20 | 21 | """ 22 | 23 | def is_string_number(s): 24 | if s.isdigit(): 25 | return True 26 | exc = None 27 | try: 28 | g = float(s) 29 | except Exception as e: 30 | exc = e 31 | pass 32 | if exc is None: 33 | if (g < 0) or (g > 0): 34 | return True 35 | else: 36 | return False 37 | 38 | 39 | if __name__ == '__main__': 40 | for tcase in range(T:=int(input())): 41 | s = input() 42 | print (is_string_number(s)) -------------------------------------------------------------------------------- /DailyCodingProblem/largestSubsetBasedOnConditions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #198 3 | 4 | This problem was asked by Google. 5 | 6 | Given a set of distinct positive integers, find the largest subset 7 | such that every pair of elements in the subset (i, j) satisfies 8 | either i % j = 0 or j % i = 0. 9 | 10 | For example, given the set [3, 5, 10, 20, 21], you should return 11 | [5, 10, 20]. Given [1, 3, 6, 24], return [1, 3, 6, 24]. 12 | 13 | """ 14 | import itertools 15 | def largest_subset(arr): 16 | l = len(arr) 17 | i = l 18 | while (i > 0): 19 | subsets = set(itertools.combinations(arr,i)) 20 | for s in subsets: 21 | checker = set() 22 | pairs = set(itertools.combinations(s,2)) 23 | for p in pairs: 24 | if (p[0]%p[1] == 0) or (p[1]%p[0] == 0): 25 | checker.add("T") 26 | else: 27 | checker.add("F") 28 | if len(checker) == 2: 29 | continue 30 | elif (len(checker) == 1) and ("T" in checker): 31 | return s 32 | i -= 1 33 | return "no subset satisfies required conditions" 34 | 35 | print (largest_subset([3, 5, 10, 20, 21])) 36 | print (largest_subset([1, 3, 6, 24])) -------------------------------------------------------------------------------- /DailyCodingProblem/leastMissingPositiveInteger.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #4 3 | 4 | This problem was asked by Stripe. 5 | 6 | Given an array of integers, find the first missing positive integer in linear 7 | time and constant space. In other words, find the lowest positive integer that does 8 | not exist in the array. The array can contain duplicates and negative numbers as well. 9 | 10 | For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. 11 | 12 | You can modify the input array in-place. 13 | 14 | """ 15 | 16 | 17 | def missing_integer(arr,n): 18 | poss = [x for x in arr if x > 0] 19 | if poss: 20 | if poss == list(range(1,n+1)): 21 | return max(poss)+1 22 | else: 23 | min_poss = min(poss) 24 | max_poss = max(poss) 25 | total_range = list(range(1,max_poss+1)) 26 | if set(total_range) != set(poss): 27 | missingNumbers = set(total_range) - set(poss) 28 | else: 29 | missingNumbers = [max(poss)+1] 30 | return min(missingNumbers) 31 | else: 32 | return 0 33 | 34 | 35 | if __name__ == '__main__': 36 | T = int(input()) 37 | for tcs in range(T): 38 | arr = list(map(int,input().strip().split())) 39 | n = len(arr) 40 | print (missing_integer(arr,n)) -------------------------------------------------------------------------------- /DailyCodingProblem/lock_Unlock_btree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #24 3 | 4 | This problem was asked by Google. 5 | 6 | Implement locking in a binary tree. A binary tree node can be locked or 7 | unlocked only if all of its descendants or ancestors are not locked. 8 | 9 | Design a binary tree node class with the following methods: 10 | 1. is_locked, which returns whether the node is locked. 11 | 2. lock, which attempts to lock the node. If it cannot be locked, then it should 12 | return false. Otherwise, it should lock it and return true. 13 | 3. unlock, which unlocks the node. If it cannot be unlocked, then it 14 | should return false. Otherwise, it should unlock it and return true. 15 | 16 | You may augment the node to add parent pointers or any other property you 17 | would like. You may assume the class is used in a single-threaded program, so 18 | there is no need for actual locks or mutexes. Each method should run in O(h), 19 | where h is the height of the tree. 20 | 21 | """ -------------------------------------------------------------------------------- /DailyCodingProblem/maxCircularSubArraySum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #190 3 | 4 | This problem was asked by Facebook. 5 | 6 | Given a circular array, compute its maximum subarray sum in O(n) 7 | time. A subarray can be empty, and in this case the sum is 0. 8 | 9 | For example, given [8, -1, 3, 4], return 15 as we choose the 10 | numbers 3, 4, and 8 where the 8 is obtained from wrapping around. 11 | 12 | Given [-4, 5, 1, 0], return 6 as we choose the numbers 5 and 1. 13 | 14 | """ 15 | 16 | def kadane_algorithm(arr,n): 17 | max_so_far = max_ending_here = 0 18 | for a in range(n): 19 | max_ending_here = max_ending_here + arr[a] 20 | if max_ending_here < 0: 21 | max_ending_here = 0 22 | if max_so_far < max_ending_here: 23 | max_so_far = max_ending_here 24 | return max_so_far 25 | 26 | def maxSum(arr,n): 27 | ##Your code here 28 | max_kadane = kadane_algorithm(arr, n) 29 | max_wrap = 0 30 | for i in range(n): 31 | max_wrap += arr[i] 32 | arr[i] = -1 * arr[i] 33 | max_wrap = max_wrap + kadane_algorithm(arr,n) 34 | if max_wrap > max_kadane: 35 | return max_wrap 36 | else: 37 | return max_kadane 38 | 39 | # if __name__ == '__main__': 40 | # for tcase in range(int(input())): 41 | # n = int(input()) 42 | # arr = list(map(int,input().strip().split())) 43 | # print (maxSum(arr,n)) 44 | 45 | ##Test cases 46 | print (maxSum([8,-1,3,4], 4)) 47 | print (maxSum([-4,5,1,0],4)) -------------------------------------------------------------------------------- /DailyCodingProblem/maxProfitFromBuysandSells.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding problem #130 3 | 4 | This problem was asked by Facebook. 5 | 6 | Given an array of numbers representing the stock prices of a 7 | company in chronological order and an integer k, return the 8 | maximum profit you can make from k buys and sells. You must 9 | buy the stock before you can sell it, and you must sell the 10 | stock before you can buy it again. 11 | 12 | For example, given k = 2 and the array [5, 2, 4, 0, 1], you should 13 | return 3. 14 | 15 | Solution: 16 | https://www.youtube.com/watch?v=Pw6lrYANjz4&t=1004s 17 | 18 | """ 19 | import math 20 | def maxProfitWithKTransactions(arr,k): 21 | if len(arr) == 0: 22 | return 0 23 | profit = [[0 for d in arr] for t in range(k+1)] 24 | for t in range(1,k+1): 25 | maxThusFar = -math.inf 26 | for d in range(1,len(arr)): 27 | maxThusFar = max(maxThusFar, 28 | profit[t-1][d-1] - arr[d-1]) 29 | profit[t][d] = max(profit[t][d-1], 30 | maxThusFar + arr[d]) 31 | return profit[-1][-1] 32 | 33 | if __name__ == '__main__': 34 | for tcase in range(int(input())): 35 | k = int(input()) 36 | arr = list(map(int,input().strip().split())) 37 | print (maxProfitWithKTransactions(arr, k)) -------------------------------------------------------------------------------- /DailyCodingProblem/maximumWeightPathTriangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #201 3 | 4 | This problem was asked by Google. 5 | 6 | You are given an array of arrays of integers, where each array 7 | corresponds to a row in a triangle of numbers. For example, 8 | [[1], [2, 3], [1, 5, 1]] represents the triangle: 9 | 10 | 1 11 | 2 3 12 | 1 5 1 13 | We define a path in the triangle to start at the top and go down 14 | one row at a time to an adjacent value, eventually ending with an 15 | entry on the bottom row. For example, 1 -> 3 -> 5. The weight of 16 | the path is the sum of the entries. 17 | 18 | Write a program that returns the weight of the maximum weight path. 19 | 20 | """ 21 | import math 22 | 23 | dp = {} 24 | def helper(triangle,i,j): 25 | if i >= len(triangle): 26 | return 0 27 | j = 0 if j < 0 else j 28 | szt = len(triangle[i]) 29 | j = szt - 1 if j >= szt else j 30 | if (i,j) not in dp: 31 | dp[(i,j)] = max(helper(triangle,i+1,j),helper(triangle,i+1,j+1)) + triangle[i][j] 32 | return dp[(i,j)] 33 | 34 | 35 | def maximum_weight_path(triangle): 36 | sz = len(triangle[-1]) 37 | res = -1 * math.inf 38 | for i in range(0,sz): 39 | res = max(res,helper(triangle,0,i)) 40 | return res 41 | 42 | print (maximum_weight_path([[1],[2,3],[1,5,1]])) 43 | tri = [ 44 | [2], 45 | [3,4], 46 | [6,5,7], 47 | [4,1,8,3] 48 | ] 49 | dp = {} 50 | print (maximum_weight_path(tri)) -------------------------------------------------------------------------------- /DailyCodingProblem/minCost.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #19 3 | 4 | This problem was asked by Facebook. 5 | 6 | A builder is looking to build a row of N houses that can be of K different 7 | colors. He has a goal of minimizing cost while ensuring that no two neighboring 8 | houses are of the same color. 9 | 10 | Given an N by K matrix where the nth row and kth column represents the cost to 11 | build the nth house with kth color, return the minimum cost which achieves 12 | this goal. 13 | 14 | Solution: 15 | This problem statment can be translated into Hungarian assignment problem. 16 | (min-cost flow problem) 17 | 18 | """ 19 | import math 20 | def mincost(arr,row,prevcol,n,k): 21 | if row == len(arr): 22 | return 0 23 | C = len(arr[row]) 24 | dp = [[math.inf for x in range(k+1)] for y in range(n)] 25 | if dp[row][prevcol+1] != math.inf: 26 | return dp[row][prevcol+1] 27 | res = math.inf 28 | for j in range(C): 29 | if j != prevcol: 30 | val = arr[row][j] + mincost(arr,row+1,j,n,k) 31 | res = min(res,val) 32 | dp[row][prevcol+1] = res 33 | return res 34 | 35 | if __name__ == '__main__': 36 | N,K = list(map(int,input().strip().split())) 37 | matrix = [[int(input()) for q in range(K)] for p in range(N)] 38 | print (mincost(matrix,0,-1,N,K)) -------------------------------------------------------------------------------- /DailyCodingProblem/minSteps.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #23 3 | 4 | This problem was asked by Google. 5 | 6 | You are given an M by N matrix consisting of booleans that represents a board. 7 | Each True boolean represents a wall. Each False boolean represents a tile you 8 | can walk on. 9 | 10 | Given this matrix, a start coordinate, and an end coordinate, return the 11 | minimum number of steps required to reach the end coordinate from the start. 12 | If there is no possible path, then return null. You can move up, left, down, 13 | and right. You cannot move through walls. You cannot wrap around the edges of the board. 14 | 15 | For example, given the following board: 16 | 17 | [[f, f, f, f], 18 | [t, t, f, t], 19 | [f, f, f, f], 20 | [f, f, f, f]] 21 | 22 | and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum 23 | number of steps required to reach the end is 7, since we would need to go 24 | through (1, 2) because there is a wall everywhere else on the second row. 25 | 26 | """ -------------------------------------------------------------------------------- /DailyCodingProblem/minSumRootToLeaf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #135 3 | 4 | This question was asked by Apple. 5 | 6 | Given a binary tree, find a minimum path sum from root to a 7 | leaf. 8 | 9 | For example, the minimum path in this tree is [10, 5, 1, -1], 10 | which has sum 15. 11 | 12 | 10 13 | / \ 14 | 5 5 15 | \ \ 16 | 2 1 17 | / 18 | -1 19 | """ 20 | import math 21 | class Node(object): 22 | def __init__(self,data): 23 | self.data = data 24 | self.left = None 25 | self.right = None 26 | 27 | root = Node(10) 28 | root.left = Node(5) 29 | root.left.right = Node(2) 30 | root.right = Node(5) 31 | root.right.right = Node(1) 32 | root.right.right.left = Node(-1) 33 | 34 | def min_sum(root): 35 | if root == None: 36 | return 0 37 | result = root.data 38 | leftresult = math.inf 39 | rightresult = math.inf 40 | if (root.left == None) and (root.right == None): 41 | return result 42 | else: 43 | if (root.left != None): 44 | leftresult = min_sum(root.left) 45 | if (root.right != None): 46 | rightresult = min_sum(root.right) 47 | if (leftresult < rightresult): 48 | result += leftresult 49 | else: 50 | result += rightresult 51 | return result 52 | 53 | print (min_sum(root)) 54 | 55 | root = Node(7) 56 | root.left = Node(3) 57 | root.right = Node(10) 58 | root.left.left = Node(1) 59 | root.left.left.left = Node(0) 60 | root.right.left = Node(8) 61 | 62 | print (min_sum(root)) -------------------------------------------------------------------------------- /DailyCodingProblem/minimumElementOlogN.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #203 3 | 4 | This problem was asked by Uber. 5 | 6 | Suppose an array sorted in ascending order is rotated at some pivot 7 | unknown to you beforehand. Find the minimum element in O(log N) time. 8 | You may assume the array does not contain duplicates. 9 | 10 | For example, given [5, 7, 10, 3, 4], return 3. 11 | 12 | """ 13 | 14 | def binary_search(arr): 15 | l = 0 16 | h = len(arr) - 1 17 | while (arr[l] > arr[h]): 18 | mid = (l + h)//2 19 | if arr[mid] > arr[h]: 20 | l = mid + 1 21 | else: 22 | h = mid 23 | return arr[l] 24 | 25 | print (binary_search([5,7,10,3,4])) -------------------------------------------------------------------------------- /DailyCodingProblem/minimumIntervalsToRemove.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #191 3 | 4 | This problem was asked by Stripe. 5 | 6 | Given a collection of intervals, find the minimum number 7 | of intervals you need to remove to make the rest of the intervals 8 | non-overlapping. 9 | 10 | Intervals can "touch", such as [0, 1] and [1, 2], but they won't 11 | be considered overlapping. 12 | 13 | For example, given the intervals (7, 9), (2, 4), (5, 8), 14 | return 1 as the last interval can be removed and the first two 15 | won't overlap. 16 | 17 | The intervals are not necessarily sorted in any order. 18 | 19 | """ 20 | 21 | def min_intervals_remove(intervals): 22 | counter = 0 23 | for i in range(len(intervals)): 24 | for j in range(i+1,len(intervals)): 25 | if intervals[i] == intervals[j]: 26 | continue 27 | a = set(range(intervals[i][0],intervals[i][1]+1)) 28 | b = set(range(intervals[j][0],intervals[j][1]+1)) 29 | if (len(a.intersection(b)) == 1) & \ 30 | (intervals[i][1] == intervals[j][0]): 31 | continue 32 | if (len(a.intersection(b)) >= 1): 33 | counter += 1 34 | return counter 35 | 36 | if __name__ == '__main__': 37 | arr = [] 38 | for tcase in range(int(input())): 39 | n = int(input()) 40 | for c in range(n): 41 | pair = list(map(int,input().strip().split())) 42 | arr.append((pair[0],pair[1])) 43 | print (min_intervals_remove(arr)) -------------------------------------------------------------------------------- /DailyCodingProblem/nearestKPoints.py: -------------------------------------------------------------------------------- 1 | """ 2 | This Problem was asked by LinkedIn 3 | 4 | Daily Coding Problem #150 5 | 6 | Given a list of points, a central point, and an integer k, find the nearest 7 | k points from the central point. 8 | 9 | For example, given the list of points [(0, 0), (5, 4), (3, 1)], the 10 | central point (1, 2), and k = 2, return [(0, 0), (3, 1)]. 11 | 12 | """ 13 | import math 14 | def nearestKPoints(arr,p,k): 15 | """ 16 | Parameters 17 | ---------- 18 | arr : list 19 | List of tuples containing all points 20 | p : tuple 21 | central point 22 | k : integer 23 | given integer 24 | 25 | Returns 26 | ------- 27 | List of k tuples which are nearest to given p 28 | 29 | """ 30 | darr = [] 31 | for c in arr: 32 | d = math.sqrt((c[0]-p[0])**2 + (c[1]-p[1])**2) 33 | darr.append(d) 34 | distance_map = zip(arr,darr) 35 | k_nearest = sorted(darr)[:k] 36 | return [x for x,y in distance_map if y in k_nearest] 37 | 38 | if __name__ == '__main__': 39 | for tcase in range(int(input())): 40 | m = int(input()) 41 | arr = [] 42 | while (m > 0): 43 | point = list(map(int,input().strip().split())) 44 | arr.append((point[0],point[1])) 45 | m -= 1 46 | central_point = list(map(int,input().strip().split())) 47 | central_point = (central_point[0],central_point[1]) 48 | k = int(input()) 49 | print (nearestKPoints(arr,central_point,k)) -------------------------------------------------------------------------------- /DailyCodingProblem/nextPermutationAbsoluteOrder.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #205 3 | 4 | This problem was asked by IBM. 5 | 6 | Given an integer, find the next permutation of it in absolute order. 7 | For example, given 48975, the next permutation would be 49578. 8 | 9 | Brute force approach: 10 | Find all permutations of given number then find the one number with 11 | which given number has minimum difference but permutation - original > 0 12 | """ 13 | 14 | import itertools 15 | def find_next_permutation(num): 16 | num_str = str(num) 17 | all_permutations = itertools.permutations(num_str,len(num_str)) 18 | differences = dict() 19 | for p in all_permutations: 20 | perm = int("".join(p)) 21 | if perm - num > 0: 22 | differences[(num,perm)] = perm - num 23 | #print (differences) 24 | differences = sorted(differences.items(),key=lambda x: x[1]) 25 | return differences[0][0][1] 26 | 27 | print (find_next_permutation(48975)) -------------------------------------------------------------------------------- /DailyCodingProblem/numberOfStepsToReach1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #419 3 | 4 | This problem was asked by PagerDuty. 5 | 6 | Given a positive integer N, find the smallest number of steps it 7 | will take to reach 1. 8 | 9 | There are two kinds of permitted steps: 10 | 11 | You may decrement N to N - 1. 12 | If a * b = N, you may decrement N to the larger of a and b. 13 | For example, given 100, you can reach 1 in five steps with the 14 | following route: 100 -> 10 -> 9 -> 3 -> 2 -> 1. 15 | 16 | """ 17 | import math 18 | def getMinDivisors(n) : 19 | # Note that this loop runs till square root 20 | i = 1 21 | all_max_divisors = [] 22 | while (i <= math.sqrt(n)): 23 | 24 | if (n % i == 0) : 25 | 26 | # If divisors are equal, print only one 27 | if (n // i == i) : 28 | if i not in all_max_divisors: 29 | all_max_divisors.append(i) 30 | else : 31 | # Otherwise print both 32 | max_d = max(i,n//i) 33 | all_max_divisors.append(max_d) 34 | i = i + 1 35 | return min(all_max_divisors) 36 | 37 | def minimum_steps(N): 38 | numofways = 0 39 | while (N > 1): 40 | X = getMinDivisors(N) 41 | #print (N-1, X) 42 | N = min(N-1,X) 43 | numofways += 1 44 | return numofways 45 | 46 | print (minimum_steps(100)) 47 | print (minimum_steps(10019)) 48 | print (minimum_steps(2883838)) 49 | print (minimum_steps(45)) -------------------------------------------------------------------------------- /DailyCodingProblem/numberOfUnivalSubTrees.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #8 3 | 4 | This problem was asked by Google. 5 | 6 | A unival tree (which stands for "universal value") is a tree where all 7 | nodes under it have the same value. 8 | 9 | Given the root to a binary tree, count the number of unival subtrees. 10 | 11 | For example, the following tree has 5 unival subtrees: 12 | 13 | 0 14 | / \ 15 | 1 0 16 | / \ 17 | 1 0 18 | / \ 19 | 1 1 20 | 21 | """ 22 | -------------------------------------------------------------------------------- /DailyCodingProblem/pairImplementation.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | # Daily Coding problem #5 4 | 5 | Good morning! Here's your coding interview problem for today. 6 | 7 | This problem was asked by Jane Street. 8 | 9 | cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the 10 | first and last element of that pair. For example, car(cons(3, 4)) 11 | returns 3, and cdr(cons(3, 4)) returns 4. 12 | 13 | Given this implementation of cons: 14 | 15 | def cons(a, b): 16 | def pair(f): 17 | return f(a, b) 18 | return pair 19 | Implement car and cdr 20 | 21 | """ 22 | 23 | def cons(a, b): 24 | def pair(f): 25 | return f(a, b) 26 | return pair 27 | 28 | def parse_pair(a,b): 29 | return (a,b) 30 | 31 | def car(pair): 32 | return pair(parse_pair)[0] 33 | 34 | def cdr(pair): 35 | return pair(parse_pair)[1] 36 | 37 | if __name__ == '__main__': 38 | a = 3 39 | b = 4 40 | upair = cons(a,b) 41 | print (car(upair)) 42 | print (cdr(upair)) -------------------------------------------------------------------------------- /DailyCodingProblem/partitionTheList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #143 3 | 4 | This problem was asked by Amazon. 5 | 6 | Given a pivot x, and a list lst, partition the list into 7 | three parts. 8 | 9 | The first part contains all elements in lst that are less 10 | than x 11 | The second part contains all elements in lst that are 12 | equal to x 13 | The third part contains all elements in lst that are 14 | larger than x 15 | 16 | Ordering within a part can be arbitrary. 17 | 18 | For example, given x = 10 and 19 | lst = [9, 12, 3, 5, 14, 10, 10], one partition may be 20 | [9, 3, 5, 10, 10, 12, 14]. 21 | 22 | """ 23 | 24 | def partition_list(lst,x): 25 | first = [] 26 | second = [] 27 | third = [] 28 | for u in lst: 29 | if u < x: 30 | first.append(u) 31 | elif u == x: 32 | second.append(u) 33 | else: 34 | third.append(u) 35 | return (first + second + third) 36 | 37 | 38 | if __name__ == '__main__': 39 | for tc in range(int(input())): 40 | lst = list(map(int,input().strip().split())) 41 | x = int(input()) 42 | print (partition_list(lst, x)) -------------------------------------------------------------------------------- /DailyCodingProblem/pascalTriangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem: Problem #429 3 | 4 | This problem was asked by Stitch Fix. 5 | 6 | Pascal's triangle is a triangular array of integers constructed with 7 | the following formula: 8 | 9 | The first row consists of the number 1. 10 | For each subsequent row, each element is the sum of the numbers 11 | directly above it, on either side. 12 | 13 | For example, here are the first few rows: 14 | 15 | 1 16 | 1 1 17 | 1 2 1 18 | 1 3 3 1 19 | 1 4 6 4 1 20 | 21 | Given an input k, return the kth row of Pascal's triangle. 22 | 23 | Bonus: Can you do this using only O(k) space? 24 | 25 | """ 26 | def binomialCoeff(n,k): 27 | res = 1 28 | if k > n - k: 29 | k = n - k 30 | for i in range(k): 31 | res *= (n-i) 32 | res = res//(i+1) 33 | return res 34 | 35 | #O(n**3) 36 | def getKthRowOfPascalTriangle(n): 37 | for line in range(n): 38 | for i in range(line + 1): 39 | print (binomialCoeff(line, i),end=" ") 40 | print ("\n") 41 | 42 | #O(n**2) 43 | def printPascal(n): 44 | for line in range(1,n+1): 45 | C = 1 46 | for i in range(1,line + 1): 47 | print (C, end= " ") 48 | C = C * (line - i)//i 49 | print ("\n") 50 | 51 | 52 | if __name__ == '__main__': 53 | n = 3 54 | getKthRowOfPascalTriangle(n) 55 | printPascal(n) 56 | n = 7 57 | getKthRowOfPascalTriangle(n) 58 | printPascal(n) -------------------------------------------------------------------------------- /DailyCodingProblem/problem195.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #195 3 | 4 | This problem was asked by Google. 5 | 6 | Let A be an N by M matrix in which every row and every column is sorted. 7 | 8 | Given i1, j1, i2, and j2, compute the number of elements of M smaller 9 | than M[i1, j1] and larger than M[i2, j2]. 10 | 11 | For example, given the following matrix: 12 | 13 | [[1, 3, 7, 10, 15, 20], 14 | [2, 6, 9, 14, 22, 25], 15 | [3, 8, 10, 15, 25, 30], 16 | [10, 11, 12, 23, 30, 35], 17 | [20, 25, 30, 35, 40, 45]] 18 | And i1 = 1, j1 = 1, i2 = 3, j2 = 3, return 15 as there are 15 numbers in 19 | the matrix smaller than 6 or greater than 23. 20 | 21 | """ 22 | #Naive solution 23 | def find_elements(arr,i1,j1,i2,j2): 24 | lbound = arr[i1][j1] 25 | ubound = arr[i2][j2] 26 | counter = 0 27 | for row in arr: 28 | for col in row: 29 | if (col <= lbound) or (col > ubound): 30 | counter += 1 31 | return counter 32 | 33 | arr = [[1, 3, 7, 10, 15, 20], 34 | [2, 6, 9, 14, 22, 25], 35 | [3, 8, 10, 15, 25, 30], 36 | [10, 11, 12, 23, 30, 35], 37 | [20, 25, 30, 35, 40, 45]] 38 | 39 | i1,j1,i2,j2 = 1,1,3,3 40 | print (find_elements(arr,i1,j1,i2,j2)) -------------------------------------------------------------------------------- /DailyCodingProblem/recordLastNOrderIDs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #16 3 | This problem was asked by Twitter. 4 | 5 | You run an e-commerce website and want to record the last N order ids in a log. 6 | Implement a data structure to accomplish this, with the following API: 7 | 1. record(order_id): adds the order_id to the log 8 | 2. get_last(i): gets the ith last element from the log. i is guaranteed to be smaller 9 | than or equal to N. 10 | 3. You should be as efficient with time and space as possible. 11 | 12 | 13 | Approach: Stack data structure seems like a good fit, let's try.. 14 | 15 | """ 16 | 17 | def record(order_id): 18 | stack.append(order_id) 19 | return 20 | 21 | def get_last(i): 22 | assert i <= N,"i is not less than or equal to N" 23 | ele = stack.pop(-1 * i) 24 | stack.insert(N - i,ele) 25 | return ele 26 | 27 | if __name__ == '__main__': 28 | N = int(input()) 29 | stack = [] 30 | for n in range(N): 31 | order_id = input() 32 | record(order_id) 33 | while True: 34 | print ("\n Please enter break to get out of loop") 35 | index = input() 36 | if index == 'break': 37 | break 38 | try: 39 | index = int(index) 40 | except: 41 | raise Exception("The index you entered is not valid") 42 | print (get_last(index)) -------------------------------------------------------------------------------- /DailyCodingProblem/recurringElement.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #159 3 | 4 | This problem was asked by Google. 5 | 6 | Given a string, return the first recurring character in it, 7 | or null if there is no recurring character. 8 | 9 | For example, given the string "acbbac", return "b". 10 | Given the string "abcdef", return null. 11 | 12 | """ 13 | 14 | import collections 15 | import random 16 | def find_recurring_element(string): 17 | all_recurring_elements = [] 18 | for c in string: 19 | if string.count(c) > 1: 20 | all_recurring_elements.append(c) 21 | if all_recurring_elements: 22 | return random.choice(all_recurring_elements) 23 | return 'null' 24 | 25 | def recurring_element(string): 26 | all_recurring_elements = [] 27 | mydict = collections.Counter(string) 28 | for k,v in mydict.items(): 29 | if v > 1: 30 | all_recurring_elements.append(k) 31 | if all_recurring_elements: 32 | return random.choice(all_recurring_elements) 33 | return "null" 34 | 35 | print (recurring_element('acbbac')) 36 | print (recurring_element("abcdef")) 37 | print () 38 | print (find_recurring_element("acbbac")) 39 | print (find_recurring_element("abcdef")) -------------------------------------------------------------------------------- /DailyCodingProblem/reverseBits.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #161 3 | 4 | This problem was asked by Facebook. 5 | 6 | Given a 32-bit integer, return the number with its bits 7 | reversed. 8 | 9 | For example, given the binary number 10 | 1111 0000 1111 0000 1111 0000 1111 0000, 11 | return 0000 1111 0000 1111 0000 1111 0000 1111. 12 | 13 | """ 14 | 15 | def reverse_bits(binary_string:str) -> str: 16 | result = [] 17 | for c in binary_string: 18 | if c != " ": 19 | if (c == '1') or (c == '0'): 20 | result.append(str(int(not int(c)))) 21 | elif c == " ": 22 | result.append(c) 23 | return "".join(result) 24 | 25 | print (reverse_bits("1111 0000 1111 0000 1111 0000 1111 0000")) -------------------------------------------------------------------------------- /DailyCodingProblem/rotateArrayInPlace.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #197 3 | 4 | This problem was asked by Amazon. 5 | 6 | Given an array and a number k that's smaller than the length of the 7 | array, rotate the array to the right k elements in-place. 8 | 9 | """ 10 | 11 | def rotate_inplace(arr,k): 12 | i = 1 13 | while (i <= k): 14 | arr.append(arr[i-1]) 15 | i += 1 16 | return arr[k:] 17 | 18 | print (rotate_inplace([1,2,3,4,5,5,6],4)) -------------------------------------------------------------------------------- /DailyCodingProblem/rotateListByKElements.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding problem #126 3 | 4 | This problem was asked by Facebook. 5 | 6 | Write a function that rotates a list by k elements. For example, 7 | [1, 2, 3, 4, 5, 6] rotated by two becomes [3, 4, 5, 6, 1, 2]. 8 | Try solving this without creating a copy of the list. How many swap 9 | or move operations do you need? 10 | 11 | """ 12 | 13 | def rotateList(arr,k): 14 | return (arr[k:] + arr[:k]) 15 | 16 | if __name__ == '__main__': 17 | for tcase in range(int(input())): 18 | arr = list(map(int,input().strip().split())) 19 | k = int(input()) 20 | print (rotateList(arr, k)) -------------------------------------------------------------------------------- /DailyCodingProblem/sortUsingReverse.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding Problem #147 3 | 4 | Given a list, sort it using this method: reverse(lst, i, j), 5 | which reverses lst from i to j. 6 | 7 | """ 8 | 9 | def reverse(lst,i,j): 10 | lst[i:j+1] = lst[i:j+1][::-1] 11 | return lst 12 | 13 | temp = 0 14 | def sort_list(arr): 15 | for m in range(len(arr)): 16 | for p in range(m+1,len(arr)): 17 | if arr[m] > arr[p]: 18 | arr = reverse(arr,m,p) 19 | return arr 20 | 21 | if __name__ == '__main__': 22 | T = int(input()) 23 | while (T > 0): 24 | arr = list(map(int,input().strip().split())) 25 | print (sort_list(arr)) 26 | T -= 1 -------------------------------------------------------------------------------- /DailyCodingProblem/squarerootOfRealNumber.py: -------------------------------------------------------------------------------- 1 | """ 2 | Daily Coding problem #129 3 | 4 | Given a real number n, find the square root of n. For example, 5 | given n = 9, return 3. 6 | 7 | """ 8 | 9 | import math 10 | def sqroot(n): 11 | return math.sqrt(n) 12 | 13 | if __name__ == '__main__': 14 | for tc in range(int(input())): 15 | n = float(input()) 16 | print (sqroot(n)) -------------------------------------------------------------------------------- /DailyCodingProblem/sumSubList.py: -------------------------------------------------------------------------------- 1 | """ 2 | This Problem was asked by Goldman Sachs 3 | 4 | Daily Coding Problem #149 5 | 6 | Given a list of numbers L, implement a method sum(i, j) which returns 7 | the sum from the sublist L[i:j] (including i, excluding j). 8 | 9 | For example, given L = [1, 2, 3, 4, 5], sum(1, 3) should return 10 | sum([2, 3]), which is 5. 11 | 12 | You can assume that you can do some pre-processing. sum() should be 13 | optimized over the pre-processing step. 14 | 15 | """ 16 | 17 | def sublist_sum(arr,p,q): 18 | if q is None: 19 | assert abs(p) <= len(arr)-1,"Given first index for slicing is not \ 20 | valid" 21 | return sum(arr[p:]) 22 | if p is None: 23 | assert abs(q) <= len(arr)-1,"Given second index for slicing is not \ 24 | valid" 25 | return sum(arr[:q]) 26 | cond = (abs(p) <= len(arr)-1) & (abs(q) <= len(arr)-1) 27 | assert cond,"Given indices are not valid" 28 | return sum(arr[p:q]) 29 | 30 | print (sublist_sum([1,2,3,4,5],1,3)) -------------------------------------------------------------------------------- /DynamicProgramming/EditDistanceReference.java: -------------------------------------------------------------------------------- 1 | public class EditDistance { 2 | public static void main(String[] args) { 3 | // TODO Auto-generated method stub 4 | String str1 = "march"; 5 | String str2 = "cart"; 6 | EditDistance ed = new EditDistance(); 7 | System.out.println(ed.getMinConversions(str1, str2)); 8 | } 9 | public int getMinConversions(String str1, String str2){ 10 | int dp[][] = new int[str1.length()+1][str2.length()+1]; 11 | for(int i=0;i<=str1.length();i++){ 12 | for(int j=0;j<=str2.length();j++){ 13 | if(i==0) 14 | dp[i][j] = j; 15 | else if(j==0) 16 | dp[i][j] = i; 17 | else if(str1.charAt(i-1) == str2.charAt(j-1)) 18 | dp[i][j] = dp[i-1][j-1]; 19 | else{ 20 | dp[i][j] = 1 + Math.min(dp[i-1][j], Math.min(dp[i][j-1], dp[i-1][j-1])); 21 | } 22 | } 23 | } 24 | return dp[str1.length()][str2.length()]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /DynamicProgramming/minimumConversionsBetween2Strings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Edit Distance: 3 | 4 | The problem statement is like if we are given two string str1 and str2 5 | then how many minimum number of operations can be performed on the str1 that 6 | it gets converted to str2. 7 | 8 | """ 9 | def getMinConversions(str1,str2): 10 | numRows = len(str1) + 1 11 | numCols = len(str2) + 1 12 | distanceTable = [[0 for i in range(numCols)] for j in range(numRows)] 13 | for m in range(0,numRows,1): 14 | for n in range(0,numCols,1): 15 | if (m==0): 16 | distanceTable[m][n] = n 17 | elif (n==0): 18 | distanceTable[m][n] = m 19 | elif (str1[m-1] == str2[n-1]): 20 | distanceTable[m][n] = distanceTable[m-1][n-1] 21 | else: 22 | distanceTable[m][n] = min (1 + distanceTable[m-1][n], 23 | 1 + distanceTable[m][n-1], 24 | 1 + distanceTable[m-1][n-1]) 25 | return distanceTable[numRows-1][numCols-1] -------------------------------------------------------------------------------- /GCC-2019/README.md: -------------------------------------------------------------------------------- 1 | ## 3 days Geeks Coding Challenge 2019 Solutions 2 | -------------------------------------------------------------------------------- /GFG_Practice/GraphAlgorithms/AdjacencyList.py: -------------------------------------------------------------------------------- 1 | def addEdge(adj:list,u:int,v:int): 2 | adj[u].append(v) 3 | adj[v].append(u) 4 | 5 | adj = None 6 | def main(v:int): 7 | global adj 8 | adj = [[] for _ in range(v)] 9 | addEdge(adj,0,1) 10 | addEdge(adj,0,2) 11 | addEdge(adj,1,2) 12 | addEdge(adj,1,3) 13 | 14 | main(4) 15 | print (adj) -------------------------------------------------------------------------------- /GFG_Practice/GraphAlgorithms/pyDFS_recursive.py: -------------------------------------------------------------------------------- 1 | 2 | ##Graph Data Structure## 3 | """ 4 | Using python dictionary to construct a graph. 5 | 1. Keys of a dictionary are used as nodes of a graph. 6 | 2. Values of each and every node are the list containing nodes 7 | with which edges are shared. 8 | """ 9 | 10 | #import queue 11 | 12 | graph ={'a':['c'],'b':['d'], 13 | 'c':['e'],'d':['a', 'd'], 14 | 'e':['b', 'c']} 15 | visited_array=[] 16 | result = [] 17 | def dfs_recursive(G,s,visited_array=[],rs=[]): 18 | #print (visited_array) 19 | visited_array.append(s) 20 | rs.append(visited_array) 21 | for w in G[s]: 22 | if w not in visited_array: 23 | dfs_recursive(G,w,visited_array=visited_array) 24 | return (rs[len(rs)-1]) 25 | 26 | print (dfs_recursive(graph,'a',visited_array=[],rs=[])) 27 | print (dfs_recursive(graph,'b',visited_array=[],rs=[])) 28 | print (dfs_recursive(graph,'c',visited_array=[],rs=[])) 29 | print (dfs_recursive(graph,'d',visited_array=[],rs=[])) 30 | print (dfs_recursive(graph,'e',visited_array=[],rs=[])) 31 | 32 | #Output 33 | #['a', 'c', 'e', 'b', 'd'] 34 | #['b', 'd', 'a', 'c', 'e'] 35 | #['c', 'e', 'b', 'd', 'a'] 36 | #['d', 'a', 'c', 'e', 'b'] 37 | #['e', 'b', 'c', 'd', 'a'] -------------------------------------------------------------------------------- /GFG_Practice/Matrix/Count_Zeros_Binary_Matrix.py: -------------------------------------------------------------------------------- 1 | ### count of Zeros in a matrix ##### 2 | 3 | def countZeros(matrix,n): 4 | totalCount = 0 5 | for e in range(n): 6 | totalCount += matrix[e].count(0) 7 | return (totalCount) 8 | 9 | if __name__ == '__main__': 10 | T = int(input()) 11 | for I in range(T): 12 | n = int(input().strip()) 13 | arr = list(map(int,input().strip().split())) 14 | matrix = [[0 for i in range(n)] for j in range(n)] 15 | k=0 16 | for i in range(n): 17 | for j in range(n): 18 | matrix[i][j] = arr[k] 19 | k += 1 20 | print (countZeros(matrix,n)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/Difference_Between_Diagnols_Of_Matrix.py: -------------------------------------------------------------------------------- 1 | def diagnolDifference(matrix,n): 2 | numRows = len(matrix) 3 | numCols = len(matrix[0]) 4 | d1 = 0 5 | d2 = 0 6 | for x in range(numRows): 7 | d1 += matrix[x][x] 8 | for y in range(numRows): 9 | d2 += matrix[y][numCols-1] 10 | numCols -= 1 11 | return (abs(d1-d2)) 12 | 13 | if __name__ == '__main__': 14 | T = int(input()) 15 | for I in range(T): 16 | n = int(input().strip()) 17 | arr = list(map(int,input().strip().split())) 18 | matrix = [[0 for i in range(n)] for j in range(n)] 19 | k=0 20 | for i in range(n): 21 | for j in range(n): 22 | matrix[i][j] = arr[k] 23 | k += 1 24 | print (diagnolDifference(matrix,n)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/IsSudokuValid.py: -------------------------------------------------------------------------------- 1 | def sudokuValidCheck(sudoku_matrix): 2 | rowUnique = [] 3 | for r in sudoku_matrix: 4 | row_Wise = [c for c in r if c!=0] 5 | rowUnique.append(row_Wise) 6 | rowCheck = [len(set(x))==len(x) for x in rowUnique] 7 | if False in rowCheck: 8 | return (0) 9 | else: 10 | return (1) 11 | 12 | if __name__ == '__main__': 13 | T = int(input()) 14 | for t in range(T): 15 | arr = list(map(int,input().strip().split())) 16 | sudoku_matrix = [] 17 | for p in range(0,len(arr),9): 18 | sudoku_matrix.append(arr[p:p+9]) 19 | print (sudokuValidCheck(sudoku_matrix)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/KingsMarch.py: -------------------------------------------------------------------------------- 1 | import allPathsInaMatrix as aPIM 2 | def KingsMarch(cb): 3 | aPIM.storePaths='' 4 | m = len(cb) 5 | n = len(cb[0]) 6 | aPIM.findPaths(cb,m,n) 7 | myPaths = aPIM.storePaths.split('|') 8 | myPaths.remove('') 9 | myPaths = [p for p in myPaths if 'x' not in p] 10 | myPaths = [list(map(int,list(a)[1:len(a)-1])) for a in myPaths] 11 | if myPaths: 12 | myMax = max([sum(u) for u in myPaths]) 13 | S = 0 14 | for H in myPaths: 15 | if sum(H)==myMax: 16 | S += 1 17 | return (myMax,S) 18 | else: 19 | return (0,len(myPaths)) 20 | 21 | if __name__ == '__main__': 22 | T = int(input()) 23 | for tcase in range(T): 24 | n = int(input()) 25 | chess_board = [] 26 | for x in range(n): 27 | arr = input().strip().split() 28 | chess_board.append(arr) 29 | print (KingsMarch(chess_board)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/KingsMarch1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/GFG_Practice/Matrix/KingsMarch1.png -------------------------------------------------------------------------------- /GFG_Practice/Matrix/KingsMarch2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/GFG_Practice/Matrix/KingsMarch2.png -------------------------------------------------------------------------------- /GFG_Practice/Matrix/SortedMatrix.py: -------------------------------------------------------------------------------- 1 | def sortedMatrix(matrix,n): 2 | row = matrix[0] 3 | for r in matrix[1:]: 4 | row = row + r 5 | sorted_matrix = sorted(row) 6 | return (sorted_matrix) 7 | 8 | 9 | if __name__ == '__main__': 10 | T = int(input()) 11 | for I in range(T): 12 | n = int(input().strip()) 13 | arr = list(map(int,input().strip().split())) 14 | matrix = [[0 for i in range(n)] for j in range(n)] 15 | k=0 16 | for i in range(n): 17 | for j in range(n): 18 | matrix[i][j] = arr[k] 19 | k += 1 20 | print (' '.join(str(i) for i in sortedMatrix(matrix,n))) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/Starting_Point.py: -------------------------------------------------------------------------------- 1 | def startPoint(X,Y,numPaths,pointsList): 2 | currLocation = [X,Y] 3 | XCoords = [i[0] for i in pointsList] 4 | YCoords = [i[1] for i in pointsList] 5 | sumX = sum(XCoords) 6 | sumY = sum(YCoords) 7 | return (' '.join([str(currLocation[0]-sumX),str(currLocation[1]-sumY)])) 8 | 9 | if __name__ == '__main__': 10 | T = int(input()) 11 | for tcase in range(T): 12 | X, Y = list(map(int,input().strip().split())) 13 | numPaths = int(input()) 14 | arr = list(map(int,input().strip().split())) 15 | pointsList = [] 16 | for p in range(0,len(arr),2): 17 | pointsList.append(arr[p:p+2]) 18 | print (startPoint(X,Y,numPaths,pointsList)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/Transpose_Of_Matrix.py: -------------------------------------------------------------------------------- 1 | def transposeMatrix(matrix,n): 2 | numRows = len(matrix) 3 | numCols = len(matrix[0]) 4 | result = '' 5 | c = 0 6 | for col in range(numCols): 7 | for row in range(numRows): 8 | result += ' ' + str(matrix[row][c]) 9 | c += 1 10 | result = result[1:] 11 | return (' '.join(result.split(' '))) 12 | 13 | if __name__ == '__main__': 14 | T = int(input()) 15 | for I in range(T): 16 | n = int(input().strip()) 17 | arr = list(map(int,input().strip().split())) 18 | matrix = [[0 for i in range(n)] for j in range(n)] 19 | k=0 20 | for i in range(n): 21 | for j in range(n): 22 | matrix[i][j] = arr[k] 23 | k += 1 24 | print (transposeMatrix(matrix,n)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/maxOf1s_In_a_Matrix.py: -------------------------------------------------------------------------------- 1 | import re 2 | def maxNumOf1s(R,C,entries): 3 | matrix = [] 4 | numof1s=[] 5 | for i in range(0,len(entries),C): 6 | matrix.append(entries[i:i+C]) 7 | for m in matrix: 8 | y = ''.join(str(i) for i in m) 9 | numof1s.append(len(re.findall('1',y))) 10 | max1s = max(numof1s) 11 | return (numof1s.index(max1s)) 12 | 13 | 14 | if __name__ == '__main__': 15 | T = int(input()) 16 | for tcase in range(T): 17 | R,C = list(map(int,input().strip().split())) 18 | entries = list(map(int,input().strip().split())) 19 | print (maxNumOf1s(R,C,entries)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/numPathsToOrigin.py: -------------------------------------------------------------------------------- 1 | import math 2 | def numPaths(n,m): 3 | Z = math.factorial(n+m) 4 | X = math.factorial(n) 5 | Y = math.factorial(m) 6 | return (Z//(X*Y)) 7 | 8 | 9 | if __name__ == '__main__': 10 | T = int(input()) 11 | for tcase in range(T): 12 | N, M = list(map(int,input().strip().split())) 13 | print (numPaths(N,M)) -------------------------------------------------------------------------------- /GFG_Practice/Matrix/numberOfPalindromicPaths.py: -------------------------------------------------------------------------------- 1 | import allPathsInaMatrix as aPIM 2 | 3 | if __name__ == '__main__': 4 | T = int(input()) 5 | for t in range(T): 6 | R, C = list(map(int,input().strip().split())) 7 | arr = input().strip().split() 8 | arrMatrix = [] 9 | for x in range(0,len(arr),C): 10 | arrMatrix.append(arr[x:x+C]) 11 | aPIM.findPaths(arrMatrix,R,C) 12 | myPaths = aPIM.storePaths.split('|') 13 | numPalindromicPaths = 0 14 | for cpath in myPaths[:len(myPaths)-1]: 15 | if cpath == cpath[::-1]: 16 | numPalindromicPaths += 1 17 | print (numPalindromicPaths) -------------------------------------------------------------------------------- /GFG_Practice/Queue/Reverse_First_K_Elements_Queue.py: -------------------------------------------------------------------------------- 1 | from queue_Implementation import Queue 2 | 3 | if __name__ == '__main__': 4 | T = int(input()) 5 | for t in range(T): 6 | N,K = list(map(int,input().strip().split())) 7 | seq = list(map(int,input().strip().split())) 8 | myQueue = Queue(seq) 9 | givenList = myQueue._seq[:K] 10 | otherList = myQueue._seq[K:] 11 | givenList = givenList[::-1] 12 | newQueue = Queue(givenList) 13 | print (newQueue._seq + otherList) 14 | -------------------------------------------------------------------------------- /GFG_Practice/Queue/Reverse_First_K_Elements_Queue_v02.py: -------------------------------------------------------------------------------- 1 | from queue_Implementation import Queue 2 | 3 | if __name__ == '__main__': 4 | T = int(input()) 5 | for t in range(T): 6 | N,K = list(map(int,input().strip().split())) 7 | seq = list(map(int,input().strip().split())) 8 | myQueue = Queue(seq) 9 | givenList = myQueue._seq[:K] 10 | otherList = myQueue._seq[K:] 11 | for v in range(len(seq)): 12 | myQueue.dequeue() 13 | for u in givenList[::-1]: 14 | myQueue.enqueue(u) 15 | print (myQueue._seq + otherList) -------------------------------------------------------------------------------- /GFG_Practice/Queue/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/GFG_Practice/Queue/__init__.py -------------------------------------------------------------------------------- /GFG_Practice/Queue/queue_Implementation.py: -------------------------------------------------------------------------------- 1 | class Queue(): 2 | 3 | def __init__(self,sequence): 4 | self._seq = sequence 5 | self._length = len(sequence) 6 | self.front = 0 7 | self.rear = len(sequence)-1 8 | 9 | def enqueue(self,X): 10 | if (self.rear>=self._length-1): 11 | print ("Queue Overflow") 12 | 13 | else: 14 | self._seq.append('') 15 | self.rear+=1 16 | self._seq[self.rear]=X 17 | 18 | def dequeue(self): 19 | if (len(self._seq)==0): 20 | print ('Queue is empty, No entity to dequeue') 21 | 22 | else: 23 | self._seq.pop(self.front) 24 | self.rear-=1 25 | 26 | def get_front(self): 27 | return (self.front) 28 | 29 | def get_rear(self): 30 | return (self.rear) 31 | 32 | def get_size(self): 33 | return (self.rear-self.front+1) 34 | 35 | def get_queue(self): 36 | return (self._seq) 37 | -------------------------------------------------------------------------------- /GFG_Practice/README.md: -------------------------------------------------------------------------------- 1 | # Questions from GeeksForGeeks (Computer science portal) - Practice. 2 | -------------------------------------------------------------------------------- /GFG_Practice/Recursion/SumOfDigits_Recursion.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | S = 0 3 | def recurSum(n,S,L=len(str(n))): 4 | if L==0: 5 | print (S) 6 | else: 7 | S += n%10 8 | n = n//10 9 | recurSum(n,S,L-1) 10 | 11 | recurSum(n,S) 12 | -------------------------------------------------------------------------------- /GFG_Practice/Recursion/SumOfDigits_Recursion_v2.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | def sumOfDigits(n): 3 | if n < 10: 4 | return n 5 | else: 6 | return (sumOfDigits(n//10) + n%10) 7 | 8 | print (sumOfDigits(253)) 9 | print (sumOfDigits(9987)) -------------------------------------------------------------------------------- /GFG_Practice/Recursion/maximumNumberOfPieceswith_abc.py: -------------------------------------------------------------------------------- 1 | # Python3 implementation of the approach 2 | import math 3 | 4 | # Function to return the maximum value 5 | # of (x + y + z) such that (ax + by + cz = n) 6 | def maxResult(n, a, b, c) : 7 | maxVal = 0 8 | 9 | # i represents possible values of a * x 10 | for i in range(0, n + 1, a) : 11 | 12 | # j represents possible values of b * y 13 | for j in range(0, n - i + 1, b) : 14 | z = (n - (i + j)) / c 15 | 16 | # If z is an integer 17 | if (math.floor(z) == math.ceil(z)) : 18 | x = i // a 19 | y = j // b 20 | maxVal = max(maxVal, x + y + int(z)) 21 | if maxVal == 0: 22 | return -1 23 | return maxVal 24 | 25 | # Driver code 26 | if __name__ == "__main__" : 27 | n,a,b,c = list(map(int,input().strip().split())) 28 | print(maxResult(n, a, b, c)); 29 | 30 | # This code is contributed by Vikas Chitturi -------------------------------------------------------------------------------- /GFG_Practice/Recursion/print1toN_Recursion.py: -------------------------------------------------------------------------------- 1 | #Initialize i = 1 in v1 2 | def print1toN_v1(n,i): 3 | if i > n: 4 | return 5 | else: 6 | print (i) 7 | print1toN_v1(n,i+1) 8 | 9 | print1toN_v1(24,1) 10 | 11 | def print1toN_v2(n): 12 | if n == 0: 13 | return 14 | else: 15 | print1toN_v2(n-1) 16 | print (n) 17 | 18 | print1toN_v2(24) -------------------------------------------------------------------------------- /GFG_Practice/Recursion/printNto1_Recursion.py: -------------------------------------------------------------------------------- 1 | def printNto1(n): 2 | if n < 1: 3 | return 4 | else: 5 | print (n) 6 | printNto1(n-1) -------------------------------------------------------------------------------- /GFG_Practice/Searching/longestContiguousSubArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of N integers. The task is to find the longest contiguous subarray so 3 | that the average of its elements is greater than or equal to a given number X. 4 | 5 | Examples: 6 | 7 | Input: arr = {1, 1, 2, -1, -1, 1}, X = 1 8 | Output: 3 9 | Length of longest subarray 10 | with average >= 1 is 3 i.e. 11 | ((1+1+2)/3)= 1.333 12 | 13 | Input: arr[] = {2, -3, 3, 2, 1}, x = 2 14 | Output: 3 15 | Length of Longest subarray is 3 having 16 | average 2 which is equal to x. 17 | 18 | """ 19 | def maxIndexDiff(arr,n): 20 | LMin = [None] * n 21 | RMax = [None] * n 22 | LMin[0] = arr[0] 23 | for i in range(1,n): 24 | LMin[i] = min(arr[i],LMin[i-1]) 25 | RMax[n-1] = arr[n-1] 26 | for j in range(n-2,-1,-1): 27 | RMax[j] = max(arr[j],RMax[j+1]) 28 | i,j,maxDiff = 0,0,-1 29 | while ((j < n) & (i < n)): 30 | if LMin[i] < RMax[j]: 31 | maxDiff = max(maxDiff,j - i) 32 | j += 1 33 | else: 34 | i += 1 35 | return (maxDiff + 1) 36 | 37 | def modifyArr(arr,n,x): 38 | for i in range(n): 39 | arr[i] = arr[i] - x 40 | 41 | def calcPrefix(arr,n): 42 | s = 0 43 | for i in range(n): 44 | s += arr[i] 45 | arr[i] = s 46 | 47 | def longestSubArray(arr,n,x): 48 | modifyArr(arr,n,x) 49 | calcPrefix(arr,n) 50 | return maxIndexDiff(arr,n) 51 | 52 | ### Testcases 53 | print (longestSubArray([1,1,2,-1,-1,1],6,1)) 54 | print (longestSubArray([2,-3,3,2,1],5,2)) -------------------------------------------------------------------------------- /GFG_Practice/Stack/SortAStack.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a stack, sort it using recursion. Use of any loop constructs like 3 | while, for..etc is not allowed. We can only use the following ADT 4 | functions on Stack S: 5 | 6 | is_empty(S) : Tests whether stack is empty or not. 7 | push(S) : Adds new element to the stack. 8 | pop(S) : Removes top element from the stack. 9 | top(S) : Returns value of the top element. Note that this 10 | function does not remove element from the stack. 11 | Example: 12 | 13 | Input: -3 <--- Top 14 | 14 15 | 18 16 | -5 17 | 30 18 | 19 | Output: 30 <--- Top 20 | 18 21 | 14 22 | -3 23 | -5 24 | """ 25 | 26 | #Recursion based algorithm 27 | def sortedInsert(q:list,element:int): 28 | if (len(q) == 0): 29 | q.append(element) 30 | return 31 | elif (len(q) != 0) and (element > q[-1]): 32 | q.append(element) 33 | return 34 | temp = q.pop() 35 | sortedInsert(q, element) 36 | q.append(temp) 37 | 38 | def sort_stack(q): 39 | if len(q) > 0: 40 | temp = q.pop() 41 | sort_stack(q) 42 | sortedInsert(q, temp) 43 | 44 | if __name__ == '__main__': 45 | q = [] 46 | q.append(30) 47 | q.append(-5) 48 | q.append(18) 49 | q.append(14) 50 | q.append(-3) 51 | print (q) 52 | sort_stack(q) 53 | print (q) -------------------------------------------------------------------------------- /GFG_Practice/Stack/stack_Implementation.py: -------------------------------------------------------------------------------- 1 | class Stack(): 2 | 3 | def __init__(self,sequence): 4 | 5 | self._seq = list(sequence) 6 | self._length = len(sequence) 7 | self.top=len(sequence)-1 8 | 9 | def push(self,X): 10 | if (self.top==self._length-1): 11 | print ('Stack Overflow Condition') 12 | else: 13 | self._seq.append('') 14 | self.top+=1 15 | self._seq[self.top]=X 16 | 17 | def pop(self): 18 | if (self.top==-1): 19 | print ('Stack is empty, Underflow Condition!!') 20 | else: 21 | self._seq.pop(self.top) 22 | self.top-=1 23 | 24 | def topElement(self): 25 | return self._seq[self.top] 26 | 27 | def size(self): 28 | return (self.top+1) 29 | 30 | def get_stack(self): 31 | return (self._seq) 32 | 33 | if __name__ == '__main__': 34 | stack1 = Stack([3,9,4,2,0,-3,65,72,1]) 35 | stack1.push(23) 36 | stack1.pop() 37 | stack1.pop() 38 | print (stack1.topElement()) 39 | print (stack1.size()) 40 | print (stack1.get_stack()) 41 | stack1.push(45) 42 | print (stack1.get_stack()) 43 | stack1.pop() 44 | stack1.pop() 45 | stack1.pop() 46 | stack1.pop() 47 | stack1.push(100) 48 | stack1.push(283) 49 | stack1.push(136) 50 | print (stack1.get_stack()) -------------------------------------------------------------------------------- /GFG_Practice/Trees/tree122.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/GFG_Practice/Trees/tree122.gif -------------------------------------------------------------------------------- /GFG_Publications/BitEvenArrays_v0.2.py: -------------------------------------------------------------------------------- 1 | def Bit_Even_Arrays(arr): 2 | for k,v in enumerate(arr): 3 | z=0 4 | if v == -1: 5 | y = k - 1 6 | z = arr[y] 7 | while True: 8 | S = bin(z)[2:][1::2] 9 | if (z%2==0) & (len(set(S))==1) & ('0' in set(S)): 10 | break 11 | else: 12 | z += 1 13 | arr[k]=z 14 | return (sum(arr)) 15 | 16 | 17 | if __name__ == '__main__': 18 | T = int(input()) 19 | for tcase in range(T): 20 | N = int(input()) 21 | arr = list(map(int,input().strip().split())) 22 | print (Bit_Even_Arrays(arr)) -------------------------------------------------------------------------------- /GFG_Publications/Bit_Even_Arrays_Question.md: -------------------------------------------------------------------------------- 1 | There is an array A of size N with entries as integers, some of the entries are -1. we need to replace -1's with numbers satisfying below criteria. 2 | The binary representation of number to be replaced with should have only 0's in its odd positions and the number has to be even. 3 | The array entries A[i] with which you replace -1's with are in such a way that A[i]>=A[i-1] and also for given array A[0]!=-1 4 | Find the minimum sum of array entries possible after the above operations are done. 5 | 6 | Input format: 7 | ``` 8 | First line T - number of test cases 9 | second line N - size of array 10 | Third line - N space separated integers 11 | ``` 12 | 13 | Sample Input: 14 | ``` 15 | 1 16 | 8 17 | 1 5 -1 25 -1 7 35 -1 18 | ``` 19 | 20 | Sample Output: 21 | `153` 22 | 23 | Explanation: 24 | ``` 25 | Index 2: Replacing -1 with 8 as its binary representation is 1000 which has 0 in its odd places and 8 is even and 8 >=5 26 | Index 4: Replacing -1 with 32 as its binary representation is 100000 which has 0 in its odd places and 32 is even and 32>=25 27 | Index 7: Replacing -1 with 40 as its binary representation is 101000 which has 0 in its odd places and 40 is even and 40>=35 28 | ``` 29 | -------------------------------------------------------------------------------- /GFG_Publications/GFG_Contributions_Pending/sumOf2Arrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | Form an array of distinct elements with each element as sum of an element from each 3 | array 4 | 5 | 6 | Given two arrays arr1[] and arr2[] of equal size which contains distinct elements, 7 | the task is to find another array with distinct elements such that elements of the 8 | third array are formed by the addition of the one-one element of the arr1[] and 9 | arr2[] 10 | 11 | Input: arr[] = {1, 7, 8, 3}, arr2[] = {6, 5, 10, 2} 12 | Output: 3 8 13 18 13 | Explantion: 14 | Index 0: 1 + 2 = 3 15 | Index 1: 3 + 5 = 8 16 | Index 2: 7 + 6 = 13 17 | Index 3: 8 + 10 = 18 18 | The elements of the array is distinct. 19 | 20 | Input: arr1[] = {15, 20, 3}, arr2[] = {5, 4, 3} 21 | Output: 6 19 25 22 | Explanation: 23 | Index 0: 3 + 3 = 6 24 | Index 1: 15 + 4 = 19 25 | Index 2: 20 + 5 = 25 26 | The elements of the array is distinct. 27 | 28 | """ 29 | 30 | def thirdArray(arrA,arrB,n): 31 | third_array = [0]*n 32 | #sort two arrays 33 | arrA = sorted(arrA) 34 | arrB = sorted(arrB) 35 | #Loop to find the array 36 | #such that each element is 37 | #sum of other two elements 38 | for i in range(n): 39 | third_array[i] = arrA[i] + arrB[i] 40 | return " ".join(str(q) for q in third_array) 41 | 42 | 43 | if __name__ == '__main__': 44 | a = [1,7,8,3] 45 | b = [6,5,10,2] 46 | size = len(a) 47 | print (thirdArray(a,b,size)) -------------------------------------------------------------------------------- /GFG_Publications/README.md: -------------------------------------------------------------------------------- 1 | # Link to Publications: 2 | https://auth.geeksforgeeks.org/user/Vikas%20Chitturi/articles#improvement 3 | -------------------------------------------------------------------------------- /GFG_Publications/Sub_Sequences_of_String.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a string str, the task is to print all the sub-sequences of str. 3 | A subsequence is a sequence that can be derived from another sequence by 4 | deleting some or no elements without changing the order of the remaining 5 | elements. 6 | 7 | Examples: 8 | 9 | Input: str = “abc” 10 | Output: a b ab c ac bc abc 11 | 12 | Input: str = “geek” 13 | Output: g e ge e ge ee gee k gk ek gek ek gek eek geek 14 | 15 | 16 | Approach: 17 | 18 | Write a recursive function that prints every sub-sequence of the 19 | sub-string starting from the second character str[1, n – 1] after appending 20 | the first character of the string str[0] in the beginning of every sub-sequence. 21 | Terminating condition will be when the passed string is empty, 22 | in that case the function will return an empty arraylist. 23 | 24 | """ 25 | 26 | 27 | import itertools 28 | 29 | def Sub_Sequences(STR): 30 | combs = [] 31 | for l in range(1,len(STR)+1): 32 | combs.append(list(itertools.combinations(STR,l))) 33 | for c in combs: 34 | for t in c: 35 | print (''.join(t),end=' ') 36 | 37 | 38 | if __name__ == '__main__': 39 | Sub_Sequences('geek') 40 | Sub_Sequences('geeks') 41 | Sub_Sequences('geeksforgeeks') 42 | Sub_Sequences('hackerrank') 43 | Sub_Sequences('hackerearth') 44 | Sub_Sequences('codechef') 45 | -------------------------------------------------------------------------------- /GFG_Publications/string_to_BinarySeq.py: -------------------------------------------------------------------------------- 1 | def stringToBinary(s): 2 | bin_conv = [] 3 | for c in s: 4 | ascii_val = ord(c) 5 | binary_val = bin(ascii_val) 6 | bin_conv.append(binary_val[2:]) 7 | return (' '.join(bin_conv)) 8 | 9 | if __name__ == '__main__': 10 | s = input() 11 | print (stringToBinary(s)) 12 | -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Block_Swap_Array_Rotation.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | d = int(input()) 4 | 5 | def swap(Arr,fi,si,d): 6 | for i in range(d): 7 | temp = Arr[fi + i] 8 | Arr[fi + i] = Arr[si + i] 9 | Arr[si + i] = temp 10 | i+=1 11 | return 12 | 13 | def leftRotate(array, d, n): 14 | if(d == 0 or d == n): 15 | return 16 | i = d 17 | j = n - d 18 | while (i != j): 19 | 20 | if(i < j): # A is shorter 21 | swap(array, d - i, d + j - i, i) 22 | j -= i 23 | else: # B is shorter 24 | swap(array, d - i, d, j) 25 | i -= j 26 | swap(array, d - i, d, i) 27 | return (array) 28 | 29 | if __name__ == '__main__': 30 | print (leftRotate(arr,d,n)) 31 | X = [1,2,3,4,5,6,7] 32 | print (leftRotate(X,d=2,n=len(X))) 33 | -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Cyclic_Rotation_Array_By_One.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | 4 | def cyclicRotation(arr,n): 5 | lastElement = arr[n-1] 6 | remaining_elements = arr[:n-1] 7 | new_array = [lastElement] + remaining_elements 8 | return (new_array) 9 | 10 | if __name__ == '__main__': 11 | print (cyclicRotation(arr,n)) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Find_Element_Rotated_Sorted_Array.py: -------------------------------------------------------------------------------- 1 | import math 2 | arr = list(map(int,input().strip().split())) 3 | n = len(arr) 4 | key = int(input()) 5 | 6 | def binarySearch(arr,value): 7 | arr = sorted(arr) 8 | low=0 9 | high = len(arr) 10 | if value in arr: 11 | while (low<=high): 12 | mid = math.floor((high+low)/2) 13 | if (arr[mid]value): 16 | high=mid-1 17 | else: 18 | return mid 19 | else: 20 | return -1 21 | 22 | def search_element(arr,key): 23 | diff = [x-arr[i-1] for i,x in enumerate(arr)][1:] 24 | sorted_diff = sorted(diff) 25 | ind = diff.index(sorted_diff[0]) 26 | leftArray,rightArray = arr[:(1+ind)],arr[(1+ind):] 27 | if key > leftArray[0]: 28 | return (binarySearch(leftArray,key)) 29 | else: 30 | return (binarySearch(rightArray,key) + len(leftArray)) 31 | 32 | if __name__ == '__main__': 33 | print (search_element(arr,key)) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Find_Pair_Given_Sum_Sorted_Rotated_Array.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | arr = list(map(int,input().strip().split())) 3 | n = len(arr) 4 | given_sum = int(input()) 5 | 6 | def findPair(arr,given_sum): 7 | inds=[] 8 | for a, b in itertools.combinations(arr,2): 9 | if a + b == given_sum: 10 | inds.append('True') 11 | else: 12 | inds.append('False') 13 | if 'True' in inds: 14 | return ('true') 15 | else: 16 | return ('false') 17 | 18 | if __name__ == '__main__': 19 | print ('\n') 20 | print (findPair(arr,given_sum)) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Maximum_Possible_Sum.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | arr = list(map(int,input().strip().split())) 3 | n = len(arr) 4 | def sum_arrayInd(array): 5 | sums=0 6 | for i,v in enumerate(array): 7 | sums = sums + (i*v) 8 | return (sums) 9 | def combination_sums(arr): 10 | comb_sums=[] 11 | arr_perms = list(itertools.permutations(arr,len(arr))) 12 | for x in arr_perms: 13 | comb_sums.append(sum_arrayInd(x)) 14 | return (max(comb_sums)) 15 | 16 | if __name__ == '__main__': 17 | print (combination_sums(arr)) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Maximum_Possible_Sum_Array_Only_Rotations_Allowed.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | 4 | def MPS_Rotations(arr,n): 5 | arrSum = sum(arr) 6 | currVal = 0 7 | for i, v in enumerate(arr): 8 | currVal += (i*v) 9 | maxVal = currVal 10 | for H in range(1,n): 11 | currVal = currVal + arrSum-(n*arr[n-H]) 12 | if currVal > maxVal: 13 | maxVal = currVal 14 | return (maxVal) 15 | 16 | if __name__ == '__main__': 17 | print (MPS_Rotations(arr, n)) 18 | -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Minimum_Rotations_String.py: -------------------------------------------------------------------------------- 1 | def min_rotations(s): 2 | char = s[0] 3 | t = s[1:] + char 4 | c = 1 5 | while (s!=t and len(s)==len(t)): 6 | char = t[0] 7 | t = t[1:] + char 8 | c += 1 9 | return (c) 10 | 11 | 12 | if __name__ == '__main__': 13 | S = input() 14 | print (min_rotations(S)) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Multiple_Left_Rotations_Array.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | k1 = int(input()) 4 | k2 = int(input()) 5 | k3 = int(input()) 6 | k4 = int(input()) 7 | 8 | def initialize(n): 9 | temp = ['']*(2*n) 10 | temp[0:n] = arr 11 | temp[n:] = arr 12 | return temp 13 | 14 | temp = initialize(n) 15 | def LeftRotate(n,k,temp): 16 | # Starting position of array after k 17 | # rotations in temp will be k % n 18 | start = k % n 19 | 20 | # Print array after k rotations 21 | for i in range(start, start + n): 22 | print(temp[i], end = " ") 23 | print("") 24 | 25 | if __name__ == '__main__': 26 | LeftRotate(n,k1,temp) 27 | LeftRotate(n,k2,temp) 28 | LeftRotate(n,k3,temp) 29 | LeftRotate(n,k4,temp) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Program_For_Array_Rotation.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | d = int(input()) 4 | def rotate(array,m): 5 | cutoff_arr = array[0:m] 6 | rotated_arr = array[m:] + cutoff_arr 7 | return (rotated_arr) 8 | 9 | if __name__ == '__main__': 10 | print (rotate(arr,d)) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Reversal_Algorithm_Array_Rotation.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | d = int(input()) 4 | 5 | def reversal_rotate(arr,m,n): 6 | A = arr[0:m] 7 | B = arr[m:n] 8 | rev_Ar = A[::-1] 9 | rev_Br = B[::-1] 10 | ArB = rev_Ar + B 11 | ArBr = rev_Ar + rev_Br 12 | BA = ArBr[::-1] 13 | return(BA) 14 | 15 | if __name__ == '__main__': 16 | print (reversal_rotate(arr,d,n)) 17 | X = [1,2,3,4,5,6,7] 18 | print (reversal_rotate(X,d,len(X))) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/Rotation_Count_Of_Array.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | 4 | def rotationCount(arr): 5 | sortedArr = sorted(arr) 6 | element = sortedArr[0] 7 | ind = arr.index(element) 8 | return (ind) 9 | 10 | if __name__ == '__main__': 11 | print (rotationCount(arr)) -------------------------------------------------------------------------------- /GeeksForGeeks_Arrays_Questions/Array_Rotations/maximize_sum_for_all_rotations_given_array.py: -------------------------------------------------------------------------------- 1 | arr = list(map(int,input().strip().split())) 2 | n = len(arr) 3 | 4 | def sum_arrayInd(array): 5 | sums=0 6 | for i,v in enumerate(array): 7 | sums = sums + (i*v) 8 | return (sums) 9 | 10 | def rotate(array,m): 11 | cutoff_arr = array[0:m] 12 | rotated_arr = array[m:] + cutoff_arr 13 | return (rotated_arr) 14 | 15 | def main(arr,n): 16 | list_of_sums = [] 17 | for i in range(n): 18 | rotatedArr = rotate(arr,i) 19 | sum_Arr = sum_arrayInd(rotatedArr) 20 | list_of_sums.append(sum_Arr) 21 | return (max(list_of_sums)) 22 | 23 | if __name__ == '__main__': 24 | print (main(arr, n)) -------------------------------------------------------------------------------- /Hackerearth/BYJU_Developer_Hiring_Challenge/Manhattan_Matrix.py: -------------------------------------------------------------------------------- 1 | 2 | def manhattanMatrix(arr,Sx,Sy,qArr): 3 | """ 4 | Write Code Here 5 | """ 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | if __name__ == '__main__': 14 | T = int(input()) 15 | for tcase in range(T): 16 | N,M = list(map(int,input().strip().split())) 17 | arr = [] 18 | for i in range(N): 19 | row = list(map(int,input().strip().split())) 20 | arr.append(row) 21 | Sx,Sy = list(map(int,input().strip().split())) 22 | Q = int(input()) 23 | qArr = [] 24 | for q in range(Q): 25 | xi,yi = list(map(int,input().strip().split())) 26 | qArr.append((xi,yi)) 27 | -------------------------------------------------------------------------------- /Hackerearth/BYJU_Developer_Hiring_Challenge/Manhattan_Matrix_Question_snip.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/BYJU_Developer_Hiring_Challenge/Manhattan_Matrix_Question_snip.JPG -------------------------------------------------------------------------------- /Hackerearth/BYJU_Developer_Hiring_Challenge/Manhattan_Matrix_Question_snip2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/BYJU_Developer_Hiring_Challenge/Manhattan_Matrix_Question_snip2.JPG -------------------------------------------------------------------------------- /Hackerearth/BYJU_Developer_Hiring_Challenge/Tournament_Q1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/BYJU_Developer_Hiring_Challenge/Tournament_Q1.JPG -------------------------------------------------------------------------------- /Hackerearth/BYJU_Developer_Hiring_Challenge/Tournament_Q2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/BYJU_Developer_Hiring_Challenge/Tournament_Q2.JPG -------------------------------------------------------------------------------- /Hackerearth/BYJU_Developer_Hiring_Challenge/tournament.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | def maxDrawRounds(s1,s2,n): 4 | assert len(s1)==n,"string length msimatch" 5 | assert len(s2)==n,"string length msimatch" 6 | s1_counter = collections.Counter(s1) 7 | s2_counter = collections.Counter(s2) 8 | common_keys = set(s1_counter.keys()) & set(s2_counter.keys()) 9 | ind_list = [] 10 | for k in common_keys: 11 | ind_list.append(s1_counter[k]==s2_counter[k]) 12 | sum_value = 0 13 | sum1=0 14 | sum2=0 15 | if len(common_keys)==0: 16 | return (0) 17 | if len(set(ind_list))==1 and list(set(ind_list))[0]==True: 18 | for k in common_keys: 19 | sum_value += s1_counter[k] #s2_counter or s1_counter 20 | return (sum_value) 21 | else: 22 | for k in common_keys: 23 | sum1 += s1_counter[k] 24 | sum2 += s2_counter[k] 25 | return (min(sum1,sum2)) 26 | 27 | if __name__ == '__main__': 28 | T = int(input()) 29 | for t in range(T): 30 | nrounds = int(input()) 31 | string1 = input() 32 | string2 = input() 33 | print (maxDrawRounds(string1,string2,nrounds)) -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/InfiniteArrays_image2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Capillary_Java_Hiring_Challenge/InfiniteArrays_image2.JPG -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/InfiniteArrays_image3.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Capillary_Java_Hiring_Challenge/InfiniteArrays_image3.JPG -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/Infinite_Arrays_Solution.py: -------------------------------------------------------------------------------- 1 | def solve (A, R, L): 2 | # write your code here 3 | LR_pairs = list(zip(L,R)) 4 | sum_arr = [] 5 | for x,y in LR_pairs: 6 | myrange = list(range(x-1,y)) 7 | req_arr=[] 8 | for a in myrange: 9 | for ind,val in enumerate(A): 10 | if ((a-ind)%len(A)==0): 11 | req_arr.append(val) 12 | else: 13 | continue 14 | sum_arr.append(sum(req_arr)) 15 | return (sum_arr) 16 | 17 | 18 | T = int(input()) 19 | for _ in range(T): 20 | N = int(input()) 21 | A = list(map(int, input().split())) 22 | Q = int(input()) 23 | L = list(map(int, input().split())) 24 | R = list(map(int, input().split())) 25 | 26 | out_ = solve(A, R, L) 27 | print (' '.join(map(str, out_))) -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/InfinityArrays_Image1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Capillary_Java_Hiring_Challenge/InfinityArrays_Image1.JPG -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/Nodes_In_a_SubTree_Count.py: -------------------------------------------------------------------------------- 1 | ''' 2 | # Sample code to perform I/O: 3 | 4 | name = input() # Reading input from STDIN 5 | print('Hi, %s.' % name) # Writing output to STDOUT 6 | 7 | # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 8 | ''' 9 | import collections 10 | L1 = [int(x) for x in input().split()] 11 | N, Q = L1[0], L1[1] 12 | 13 | treeValues = input() 14 | graph = collections.defaultdict(list) 15 | while(N-1 > 0): 16 | Input = input().split() 17 | graph[Input[0] + '-' + treeValues[int(Input[0])-1]].append(Input[1]+'-'+treeValues[int(Input[1])-1]) 18 | N = N - 1 19 | 20 | while(Q > 0): 21 | Input = input().split() 22 | C = 0 23 | if Input[0]+'-'+Input[1] in graph.keys(): 24 | C += len(graph[Input[0]+'-'+Input[1]]) 25 | if [Input[0]+'-'+Input[1]] in graph.values(): 26 | for key,item in graph.items(): 27 | if Input[0]+'-'+Input[1] in item: 28 | C += 1 29 | print (C) 30 | Q = Q - 1 31 | -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/Nodes_img3.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Capillary_Java_Hiring_Challenge/Nodes_img3.JPG -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/Nodes_in_a_SubTree_img1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Capillary_Java_Hiring_Challenge/Nodes_in_a_SubTree_img1.JPG -------------------------------------------------------------------------------- /Hackerearth/Capillary_Java_Hiring_Challenge/Nodes_in_a_SubTree_img2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Capillary_Java_Hiring_Challenge/Nodes_in_a_SubTree_img2.JPG -------------------------------------------------------------------------------- /Hackerearth/DynamicProgramming/InversionGraphs.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an array A with N elements. You create a graph G with 3 | N vertices using A as follows: 4 | 5 | For any pair of indices (i,j) where 1 <= i < j <= N , if A[i] > A[j], 6 | then add an undirected edge between vertices i and j . 7 | 8 | In graph G, find the maximum possible size of set S (of vertices in G) 9 | such that there exists an edge between every pair of vertices that are available 10 | in S. 11 | 12 | Input format 13 | 14 | The first line contains an integer N denoting the number of elements in A . 15 | The second line contains N space-separated integers denoting the elements of A. 16 | Output format 17 | 18 | Among all the vertices available in S, find the maximum possible size of S. 19 | 20 | Constraints 21 | 1 <= N <= 10**5 22 | 1 <= A[i] <= 10**6 23 | 24 | SAMPLE INPUT 25 | 3 26 | 2 1 3 27 | 28 | SAMPLE OUTPUT 29 | 2 30 | 31 | Explanation 32 | G will have 3 vertices and following edges : 1 - 2 33 | 34 | S = {1, 2 } , |S| = 2 is optimal choice. 35 | 36 | """ -------------------------------------------------------------------------------- /Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Flip_Bits_image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Flip_Bits_image1.png -------------------------------------------------------------------------------- /Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Flip_Bits_image2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Flip_Bits_image2.png -------------------------------------------------------------------------------- /Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Sid_and_his_Stone_game.py: -------------------------------------------------------------------------------- 1 | def minNumStones(n,m): 2 | S = 0 3 | for I in range(1,n+1): 4 | S += I 5 | if S >= m: 6 | break 7 | A = (n*(n+1))//2 8 | if S!=A and m < A: 9 | return (abs(m-A)) 10 | elif S==A and m==A: 11 | return (0) 12 | elif S==A and m > A: 13 | return (abs(m-A)) 14 | elif S==A and m < A: 15 | return (abs(m-A)) 16 | 17 | if __name__ == '__main__': 18 | T = int(input()) 19 | for tcase in range(T): 20 | N, M = list(map(int,input().strip().split())) 21 | print (minNumStones(N,M)) -------------------------------------------------------------------------------- /Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Sids_Stone_game.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Sids_Stone_game.png -------------------------------------------------------------------------------- /Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Sids_Stone_game2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Fallabella_ReactJS_Hiring_Challenge/Sids_Stone_game2.png -------------------------------------------------------------------------------- /Hackerearth/Fallabella_ReactJS_Hiring_Challenge/flip_the_bits.py: -------------------------------------------------------------------------------- 1 | def flipBits(arr1,arr2): 2 | bin_arr = arr1 3 | for q in arr2: 4 | for i in range(q[0]-1,q[1]): 5 | if bin_arr[i]==1: 6 | bin_arr[i]=0 7 | else: 8 | bin_arr[i]=1 9 | return (' '.join(str(i) for i in bin_arr)) 10 | 11 | if __name__ == '__main__': 12 | T = int(input()) 13 | for tcase in range(T): 14 | N,Q = list(map(int,input().strip().split())) 15 | arrN = list(map(int,input().strip().split())) 16 | arr_Q = [] 17 | for q in range(Q): 18 | arrQ = list(map(int,input().strip().split())) 19 | arr_Q.append(arrQ) 20 | print (flipBits(arrN,arr_Q)) -------------------------------------------------------------------------------- /Hackerearth/Full_Contact_Engineer_Hiring_Challenge/Circular_Permutation.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | def printPermutation(N,A): 4 | numOfElements = pow(2,N) 5 | bin_reps = [] 6 | for x in range(numOfElements): 7 | if len(bin(x).split('b')[1]) < 2: 8 | bin_reps.append(''.join(bin(x).split('b'))) 9 | else: 10 | bin_reps.append(bin(x).split('b')[1]) 11 | allPerms = list(itertools.permutations(bin_reps,numOfElements)) 12 | total = [] 13 | for xy in allPerms: 14 | total_sum = [] 15 | for ab in range(len(xy)-1): 16 | alpha = list(map(int,list(xy[ab]))) 17 | beta = list(map(int,list(xy[ab+1]))) 18 | total_sum.append(sum([abs(alpha[i]-beta[i]) for i in range(len(alpha))])) 19 | print (total_sum,xy) 20 | X = list(map(int,list(xy[0]))) 21 | Y = list(map(int,list(xy[len(xy)-1]))) 22 | firstnlastSum = sum([abs(X[i]-Y[i]) for i in range(len(X))]) 23 | if len(bin(A).split('b')[1]) < 2: 24 | k0 = ''.join(bin(A).split('b')) 25 | else: 26 | k0 = bin(A).split('b')[1] 27 | if (len(set(total_sum))==1) & (list(set(total_sum))[0] == 1) & (firstnlastSum == 1) & (xy[0]==k0) : 28 | total.append(xy) 29 | return (total) 30 | 31 | if __name__ == '__main__': 32 | N,A = list(map(int,input().strip().split())) 33 | ans = printPermutation(N,A) 34 | print (ans) 35 | for i in ans: 36 | perm = [int(a,2) for a in i] 37 | print (perm) -------------------------------------------------------------------------------- /Hackerearth/Full_Contact_Engineer_Hiring_Challenge/Circular_Permutation_Question_snip.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Full_Contact_Engineer_Hiring_Challenge/Circular_Permutation_Question_snip.JPG -------------------------------------------------------------------------------- /Hackerearth/Full_Contact_Engineer_Hiring_Challenge/cumulative_XOR_question.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Full_Contact_Engineer_Hiring_Challenge/cumulative_XOR_question.JPG -------------------------------------------------------------------------------- /Hackerearth/Full_Contact_Engineer_Hiring_Challenge/cumulative_XOR_question_example.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Full_Contact_Engineer_Hiring_Challenge/cumulative_XOR_question_example.JPG -------------------------------------------------------------------------------- /Hackerearth/Full_Contact_Engineer_Hiring_Challenge/findCumulativeXor.py: -------------------------------------------------------------------------------- 1 | # Python 3 arr dynamic programming solution 2 | # to finding the number of subsets having 3 | # xor of their elements as k 4 | import math 5 | def cumulative_Xor(N,K,A): 6 | #finding max element of A 7 | max_element = max(A) 8 | #maximum possible XOR Value 9 | m = (1 << (int)(math.log2(max_element) + 1)) - 1 10 | # The value of dp[i][j] is the number 11 | # of subsets having XOR of their elements 12 | # as j from the set arr[0...i-1] 13 | 14 | # Initializing all the values 15 | # of dp[i][j] as 0 16 | dp = [[0 for i in range(m + 1)] for i in range(N + 1)] 17 | # The xor of empty subset is 0 18 | dp[0][0] = 1 19 | 20 | # Fill the dp table 21 | for i in range(1, N + 1): 22 | for j in range(m + 1): 23 | dp[i][j] = (dp[i - 1][j] + dp[i - 1][j ^ A[i - 1]]) 24 | # The answer is the number of subset 25 | # from set arr[0..n-1] having XOR of 26 | # elements as k 27 | cnt1 = sum(dp[N][:K]) 28 | cnt2 = dp[N][K] 29 | cnt3 = sum(dp[N][K+1:]) 30 | return (cnt1,cnt2,cnt3) 31 | 32 | 33 | if __name__ =='__main__': 34 | T = int(input()) 35 | for t in range(T): 36 | N = int(input()) 37 | K = int(input()) 38 | A = list(map(int,input().strip().split())) 39 | ct1,ct2,ct3 = cumulative_Xor(N,K,A) 40 | print (ct1,ct2,ct3) 41 | numerator = pow(ct1 + ct2,2) + pow(ct2 + ct3,2) + pow(ct3 + ct1,2) - (ct1**2 + ct2**2 + ct3**2) 42 | print (numerator%(10**9 + 7)) 43 | -------------------------------------------------------------------------------- /Hackerearth/Full_Contact_Engineer_Hiring_Challenge/findCumulativeXor_BruteForce.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | 3 | def getXor(arr): 4 | xor = 0 5 | for i in arr: 6 | xor ^= i 7 | return xor 8 | 9 | 10 | def getCountBruteForce1(arr, k): 11 | arr.sort() 12 | countGreaterThanK = 0 13 | for r in range(0, len(arr)+1): 14 | for comb in combinations(arr, r): 15 | xor = getXor(comb) 16 | if xor > k: 17 | countGreaterThanK += 1 18 | return(countGreaterThanK) 19 | 20 | 21 | def getCountBruteForce2(arr, k): 22 | arr.sort() 23 | countLessThanK = 0 24 | for r in range(0, len(arr)+1): 25 | for comb in combinations(arr, r): 26 | xor = getXor(comb) 27 | if xor < k: 28 | countLessThanK += 1 29 | return(countLessThanK) -------------------------------------------------------------------------------- /Hackerearth/HSBC_Java_Hiring_Challenge/HelpJohn.py: -------------------------------------------------------------------------------- 1 | def helpJohn(arr): 2 | bag = [] 3 | xlen = len(arr) 4 | i = 0 5 | while (xlen > 0): 6 | a = arr[i] 7 | if len(bag)==0: 8 | print (' '.join(['-1','-1'])) 9 | else: 10 | lessArr = [i for i in bag if i < a] 11 | q1a = max(lessArr) if lessArr else -1 12 | moreArr = [i for i in bag if i > a] 13 | q2a = min(moreArr) if moreArr else -1 14 | print (' '.join([str(q1a),str(q2a)])) 15 | bag.append(a) 16 | i += 1 17 | xlen -= 1 18 | 19 | 20 | if __name__ == '__main__': 21 | N = int(input()) 22 | xint = [] 23 | for n in range(N): 24 | Int = int(input()) 25 | xint.append(Int) 26 | helpJohn(xint) -------------------------------------------------------------------------------- /Hackerearth/HSBC_Java_Hiring_Challenge/Help_John_img1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HSBC_Java_Hiring_Challenge/Help_John_img1.png -------------------------------------------------------------------------------- /Hackerearth/HSBC_Java_Hiring_Challenge/Help_John_img2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HSBC_Java_Hiring_Challenge/Help_John_img2.png -------------------------------------------------------------------------------- /Hackerearth/HSBC_Java_Hiring_Challenge/sam_height_img1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HSBC_Java_Hiring_Challenge/sam_height_img1.png -------------------------------------------------------------------------------- /Hackerearth/HSBC_Java_Hiring_Challenge/sam_height_img2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HSBC_Java_Hiring_Challenge/sam_height_img2.png -------------------------------------------------------------------------------- /Hackerearth/HSBC_Java_Hiring_Challenge/sam_height_img3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HSBC_Java_Hiring_Challenge/sam_height_img3.png -------------------------------------------------------------------------------- /Hackerearth/HaloDoc_Practice_test/Hackerearth_Practice_Test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HaloDoc_Practice_test/Hackerearth_Practice_Test.png -------------------------------------------------------------------------------- /Hackerearth/HaloDoc_Practice_test/Maximum_Mismatches_snip01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HaloDoc_Practice_test/Maximum_Mismatches_snip01.png -------------------------------------------------------------------------------- /Hackerearth/HaloDoc_Practice_test/Maximum_Mismatches_snip02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HaloDoc_Practice_test/Maximum_Mismatches_snip02.png -------------------------------------------------------------------------------- /Hackerearth/HaloDoc_Practice_test/String_Minimization_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HaloDoc_Practice_test/String_Minimization_01.png -------------------------------------------------------------------------------- /Hackerearth/HaloDoc_Practice_test/String_Minimization_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HaloDoc_Practice_test/String_Minimization_02.png -------------------------------------------------------------------------------- /Hackerearth/HaloDoc_Practice_test/countLikesDislikes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | # Sample code to perform I/O: 3 | 4 | name = input() # Reading input from STDIN 5 | print('Hi, %s.' % name) # Writing output to STDOUT 6 | 7 | # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 8 | ''' 9 | 10 | # Write your code here 11 | 12 | def count_likes_dislikes(str1,str2): 13 | C = 0 14 | for i in range(len(str1)): 15 | if str1[i] == str2[i]: 16 | C += 1 17 | return C 18 | 19 | 20 | if __name__ == '__main__': 21 | str1 = input() 22 | str2 = input() 23 | print (count_likes_dislikes(str1,str2)) -------------------------------------------------------------------------------- /Hackerearth/HaloDoc_Practice_test/maximumMismatches.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | def maximum_mismatches(s,n): 3 | if len(set(s)) == 1: 4 | return 0 5 | maxc = 0 6 | for str_c in set(itertools.permutations(s,n)): 7 | rev_str = str_c[::-1] 8 | counter = 0 9 | for i in range(n): 10 | if str_c[i] != rev_str[i]: 11 | counter += 1 12 | if maxc < counter: 13 | maxc = counter 14 | return maxc 15 | 16 | 17 | if __name__ == '__main__': 18 | T = int(input()) 19 | for tcs in range(T): 20 | S = input() 21 | N = len(S) 22 | print (maximum_mismatches(S,N)) -------------------------------------------------------------------------------- /Hackerearth/HourStorm#11/Deleting_Numbers.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import math 3 | def DeletingNumbers(n,k,arr): 4 | if len(set(arr)) == len(arr): 5 | max_score = 0 6 | for t in list(itertools.combinations(arr,k)): 7 | array = [item for item in arr if item not in t] 8 | middle = array[math.floor((1 + len(array))/2) - 1] 9 | if max_score < middle: 10 | max_score = middle 11 | else: 12 | sort_arr = sorted(arr,reverse=True) 13 | arr_len = len(arr) 14 | max_score = sort_arr[math.floor((arr_len+1)/2)-1] 15 | return (max_score) 16 | 17 | 18 | if __name__ == '__main__': 19 | n,k = list(map(int,input().strip().split())) 20 | arr = list(map(int,input().strip().split())) 21 | print (DeletingNumbers(n,k,arr)) -------------------------------------------------------------------------------- /Hackerearth/HourStorm#11/Deleting_Numbers_img1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HourStorm#11/Deleting_Numbers_img1.JPG -------------------------------------------------------------------------------- /Hackerearth/HourStorm#11/Deleting_Numbers_img2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HourStorm#11/Deleting_Numbers_img2.JPG -------------------------------------------------------------------------------- /Hackerearth/HourStorm#12/Minimum_Transactions_v2.py: -------------------------------------------------------------------------------- 1 | def mainf(): 2 | s = input().split(); 3 | n,m = int(s[0]),int(s[1]); 4 | d = {}; 5 | while(m>0): 6 | tran = input().split(); 7 | d[tran[0]] = d[tran[0]] + int(tran[2])*(-1) if tran[0] in d.keys() else int(tran[2])*(-1); 8 | d[tran[1]] = d[tran[1]] + int(tran[2]) if tran[1] in d.keys() else int(tran[2]); 9 | m-=1; 10 | sum = 0; 11 | for v in d.values(): 12 | sum+=v if v>0 else 0 13 | print(sum); 14 | 15 | mainf(); -------------------------------------------------------------------------------- /Hackerearth/HourStorm#12/minimum_transactions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HourStorm#12/minimum_transactions.png -------------------------------------------------------------------------------- /Hackerearth/HourStorm#12/minimum_transactions_img2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/HourStorm#12/minimum_transactions_img2.png -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/Smallest_Subset_img1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Infrrd_Python_Challenge/Smallest_Subset_img1.png -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/Smallest_Subset_img2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Infrrd_Python_Challenge/Smallest_Subset_img2.png -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/countMe.py: -------------------------------------------------------------------------------- 1 | def countMe(arrA,arrL,arrR,arrX): 2 | resultCount = [] 3 | for b in range(len(arrX)): 4 | targetX = arrX[b] 5 | p = arrL[b] 6 | q = arrR[b] 7 | resultCount.append(countOfNums(arrA[p-1:q],targetX)) 8 | return (" ".join(str(i) for i in resultCount)) 9 | 10 | def countOfNums(array,target): 11 | C = 0 12 | for x in array: 13 | if target%x == 0: 14 | C += 1 15 | return (C) 16 | 17 | if __name__ == '__main__': 18 | sizeOfA = int(input()) 19 | arrA = list(map(int,input().strip().split())) 20 | numQ = int(input()) 21 | arrL = list(map(int,input().strip().split())) 22 | arrR = list(map(int,input().strip().split())) 23 | arrX = list(map(int,input().strip().split())) 24 | print (countMe(arrA,arrL,arrR,arrX)) 25 | -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/maximize_palindromes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Infrrd_Python_Challenge/maximize_palindromes.png -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/maximize_palindromes_img2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Infrrd_Python_Challenge/maximize_palindromes_img2.png -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/maximize_palindromic_strings.py: -------------------------------------------------------------------------------- 1 | import collections 2 | def maxPalindStrings(s,p): 3 | cls1 = collections.Counter(p) 4 | cls2 = collections.Counter(s) 5 | sumcls1 = sum(cls1.values()) 6 | sumcls2 = sum([q for p,q in cls2.items() if p in cls1]) 7 | if sumcls2%sumcls1 == 0: 8 | return (sumcls2//sumcls1) 9 | else: 10 | return (int(sumcls2/sumcls1)) 11 | 12 | if __name__ == '__main__': 13 | sl,pl = list(map(int,input().strip().split())) 14 | s = input() 15 | p = input() 16 | print (maxPalindStrings(s,p)) -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/maximize_palindromic_strings_v2.py: -------------------------------------------------------------------------------- 1 | import re 2 | import itertools 3 | if __name__ == '__main__': 4 | sl,pl = list(map(int,input().strip().split())) 5 | s = input() 6 | p = input() 7 | x = [len(re.findall(p,''.join(i))) for i in list(itertools.permutations(s,len(s)))] 8 | print (max(x)) 9 | 10 | #### Memory Limit exceeded #### 11 | ### Exhaustive solution #### -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/problem01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Infrrd_Python_Challenge/problem01.png -------------------------------------------------------------------------------- /Hackerearth/Infrrd_Python_Challenge/problem02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Infrrd_Python_Challenge/problem02.png -------------------------------------------------------------------------------- /Hackerearth/July_Circuits_2019/Super_Balanced_Brackets.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/July_Circuits_2019/Super_Balanced_Brackets.JPG -------------------------------------------------------------------------------- /Hackerearth/July_Circuits_2019/Super_Balanced_Brackets_testcases.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/July_Circuits_2019/Super_Balanced_Brackets_testcases.JPG -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/DetermineWinner01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Circuits_2019/DetermineWinner01.png -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/DetermineWinner02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Circuits_2019/DetermineWinner02.png -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/DetermineWinner_v1.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import math 3 | def find_winner(n,k): 4 | players = ['A','D'] 5 | winnersList = [] 6 | for i in range(1,k+1): 7 | a = n/i 8 | if str(a).split('.')[1] == 0: 9 | gturns = list(itertools.islice(itertools.cycle(players),a+1)) 10 | winnersList.append(gturns[len(gturns)-1]) 11 | else: 12 | gturns = list(itertools.islice(itertools.cycle(players),math.ceil(a)+1)) 13 | winnersList.append(gturns[len(gturns)-1]) 14 | if len(set(winnersList))==1: 15 | if winnersList[0]=='A': 16 | return ('Dishant') 17 | else: 18 | return ('Arpa') 19 | else: 20 | if winnersList[len(winnersList)-1] == 'D': 21 | return ('Dishant') 22 | else: 23 | return ('Arpa') 24 | 25 | if __name__ == '__main__': 26 | T = int(input()) 27 | for tcase in range(T): 28 | n,k = list(map(int,input().strip().split())) 29 | print (find_winner(n,k)) -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/DetermineWinner_v2.py: -------------------------------------------------------------------------------- 1 | def find_winner(n,k): 2 | if n%(k+1)==0: 3 | return ('Dishant') 4 | else: 5 | return ('Arpa') 6 | 7 | if __name__ == '__main__': 8 | T = int(input()) 9 | for tcase in range(T): 10 | n,k = list(map(int,input().strip().split())) 11 | print (find_winner(n,k)) -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/README.md: -------------------------------------------------------------------------------- 1 | Looking for explanation on code borrowed from hackerearth submissions - [functionValue_v2.py](functionValue_v2.py) 2 | -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/functionValue01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Circuits_2019/functionValue01.png -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/functionValue02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Circuits_2019/functionValue02.png -------------------------------------------------------------------------------- /Hackerearth/June_Circuits_2019/functionValue_v1.py: -------------------------------------------------------------------------------- 1 | def recurEven(n): 2 | if n == 1: 3 | return (1) 4 | elif n == 2: 5 | return (1) 6 | else: 7 | return (2*recurEven(n-1) - recurEven(n-2) + 2) 8 | 9 | def recurOdd(n): 10 | if n==1: 11 | return (1) 12 | elif n==2: 13 | return (1) 14 | else: 15 | return (3*recurOdd(n-2)) 16 | 17 | def functionValue(L,R,P): 18 | U = R-L+1 19 | fvalues = [recurEven(L+i) if (L+i)%2==0 else recurOdd(L+i) for i in range(U)] 20 | return (sum(fvalues)%P) 21 | 22 | if __name__ == '__main__': 23 | T,P = list(map(int,input().strip().split())) 24 | for _ in range(T): 25 | L,R = list(map(int,input().strip().split())) 26 | print (functionValue(L,R,P)) -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/CostOfBalloons.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Easy_2019/CostOfBalloons.png -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/CostOfBalloons2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Easy_2019/CostOfBalloons2.png -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/CoverWithMosiaics.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Sample code to perform I/O: 3 | 4 | cin >> name; // Reading input from STDIN 5 | cout << "Hi, " << name << ".\n"; // Writing output to STDOUT 6 | 7 | // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 8 | */ 9 | 10 | // Write your code here 11 | #include 12 | using namespace std; 13 | const int maxn = 1000 + 10; 14 | bool b[maxn][maxn]; 15 | bool ps[maxn][maxn]; 16 | bool ar[maxn][maxn]; 17 | 18 | int main(){ 19 | int n, m, k; 20 | cin >> n >> m >> k; 21 | for(int i = 1; i <= n; i++) 22 | for(int j = 1; j <= m; j++) 23 | cin >> b[i][j]; 24 | int ans = 0; 25 | for(int i = 1; i <= n; i++) 26 | for(int j = 1; j <= m; j++){ 27 | ps[i][j] = ps[i - 1][j - 1] ^ ps[i][j] ^ ps[i - 1][j] ^ ps[i][j - 1]; 28 | if(ps[i][j] == b[i][j]){ 29 | if(i + k > n + 1 || j + k > m + 1) 30 | return cout << -1 << endl , 0; 31 | ps[i][j] ^= 1; 32 | ps[i + k][j] ^= 1; 33 | ps[i][j + k] ^= 1; 34 | ps[i + k][j + k] ^= 1; 35 | ans++; 36 | } 37 | } 38 | cout << ans << endl; 39 | } 40 | -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/Mosaics1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Easy_2019/Mosaics1.png -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/Mosaics2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Easy_2019/Mosaics2.png -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/Mosaics3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/June_Easy_2019/Mosaics3.png -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/medianGame_V2.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an array A of N integers. You perform this operation N-2 times: 3 | For each contiguous subarray of odd size greater than 2, you find the median of each subarray 4 | (Say medians obtained in a move are M1,M2,......Mk). In each move, you remove the first occurrence of value 5 | min(M1,M2,M3,.......Mk) from the original array. After removing the element the array size reduces by 1 and no void spaces are left. 6 | For example, if we remove element 2 from the array {1,2,3,4} , the new array will be {1,3,4}. 7 | 8 | Print a single integer denoting the sum of numbers that are left in the array after performing the operations. You need to do this for T test cases. 9 | 10 | Input Format 11 | 12 | The first line contains T denoting the number of test cases(1<=T<=10). 13 | 14 | The first line of each test case contains N denoting the number of integers in the array initially(4<=N<=10^5). 15 | 16 | The next line contains N space seperated integers denoting [A1,A2,A3,.....AN] (1<=Ai<=10^9) for all valid i 17 | 18 | Output Format 19 | 20 | Output a single integer denoting the sum of numbers left in the array after performing the operations for each test case on a new line. 21 | 22 | Sample Input 23 | 24 | 2 25 | 4 26 | 2 5 3 2 27 | 4 28 | 1 1 1 1 29 | 30 | Sample output 31 | 32 | 7 33 | 2 34 | 35 | """ 36 | 37 | for _ in range(int(input())): 38 | n = int(input()) 39 | arr = list(map(int,input().split())) 40 | print(max(arr)+min(arr)) -------------------------------------------------------------------------------- /Hackerearth/June_Easy_2019/minimumPurchasingCost.py: -------------------------------------------------------------------------------- 1 | def minimumCost(status_arr,cg,cp,num): 2 | s1 = 0 3 | s2 = 0 4 | for i in status_arr: 5 | s1 += (i[0]*cg + i[1]*cp) 6 | s2 += (i[0]*cp + i[1]*cg) 7 | return (min(s1,s2)) 8 | 9 | 10 | if __name__ == '__main__': 11 | T = int(input()) 12 | for tcase in range(T): 13 | cost_g,cost_p = list(map(int,input().strip().split())) 14 | num_par = int(input()) 15 | status_arr = [] 16 | for par in range(num_par): 17 | x,y = list(map(int,input().strip().split())) 18 | status_arr.append([x,y]) 19 | print (minimumCost(status_arr,cost_g,cost_p,num_par)) -------------------------------------------------------------------------------- /Hackerearth/Largest_SubSeq.py: -------------------------------------------------------------------------------- 1 | #''' 2 | # Sample code to perform I/O: 3 | 4 | #name = input() # Reading input from STDIN 5 | #print 'Hi, %s.' % name # Writing output to STDOUT 6 | 7 | # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 8 | #''' 9 | 10 | def choose_max(intel_levels): 11 | seq_ordered = sorted(intel_levels) 12 | break_points = [] 13 | for I in range(len(seq_ordered)-1): 14 | if (abs(seq_ordered[I]-seq_ordered[I+1])>1): 15 | break_points.append(I) 16 | 17 | if break_points==[]: 18 | return (len(intel_levels)) 19 | 20 | elif len(break_points)==1: 21 | f = len(intel_levels[:break_points[0]+1]) 22 | s = len(intel_levels[break_points[0]+1:]) 23 | return (max(f,s)) 24 | 25 | elif len(break_points)>1: 26 | sub_seq_len = [] 27 | for b in range(len(break_points)-1): 28 | sub_seq_len.append(len(intel_levels[break_points[b]+1:break_points[b+1]+1])) 29 | sub_seq_len.append(len(intel_levels[:break_points[0]+1])) 30 | sub_seq_len.append(len(intel_levels[break_points[0]+1:])) 31 | return (max(sub_seq_len)) 32 | 33 | 34 | if __name__ == '__main__': 35 | 36 | T = int(input()) 37 | for t in range(T): 38 | N = int(input()) 39 | intelligence_levels = list(map(int,input().strip().split())) 40 | print (choose_max(intelligence_levels)) 41 | -------------------------------------------------------------------------------- /Hackerearth/Machine-Learning/basic_probability.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Mike wants to go fishing this weekend to nearby lake. His neighbour 3 | Alice (is the one Mike was hoping to ask out since long time) is also planing to go to the same spot for fishing this weekend. 4 | The probability that it will rain this weekend is p1.There are two possible ways to reach the fishing spot (bus or train). 5 | The probability that Mike will take the bus is Pmb and that Alice will take the bus is Pab. 6 | Travel plans of both are independent of each other and rain. 7 | 8 | What is the probability Prs that Mike and Alice meet each other only (should not meet in bus or train) 9 | in a romantic setup (on a lake in rain)? 10 | 11 | Input format 12 | 13 | FIrst line: Pmb 14 | 15 | Second line: Pab 16 | 17 | Third line: p1 18 | 19 | Output format 20 | 21 | Prs, rounded up to six decimal places. 22 | ''' 23 | 24 | import math 25 | 26 | pmb = float(input().strip()) 27 | pab = float(input().strip()) 28 | p1 = float(input().strip()) 29 | 30 | # Probability that Mike and Alice meet each other only (should not meet in bus or train) in a romantic setup (on a lake in rain) 31 | prs = p1 * ((pmb * (1 - pab)) + ((1 - pmb) * pab)) 32 | print ("%.6f" % (prs)) 33 | -------------------------------------------------------------------------------- /Hackerearth/Machine-Learning/conditional_probability.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Bob has an important meeting tomorrow and he has to reach office on time in morning. His general mode of transport is by car 3 | and on a regular day (no car trouble) the probability that he will reach on time is Pot. 4 | The probability that he might have car trouble is Pct. 5 | If the car runs into trouble he will have to take a train and only 2 trains out of the available N trains will get him 6 | to office on time. 7 | 8 | What are the chances that he will reach office on time tomorrow? 9 | 10 | Input format 11 | 12 | First line: Pct 13 | 14 | Second line: Pot 15 | 16 | Third line: N 17 | 18 | Output format 19 | 20 | Probability he will reach in time, rounded to six decimal digits 21 | ''' 22 | 23 | Pct = float(input().strip()) 24 | Pot = float(input().strip()) 25 | N = int(input().strip()) 26 | 27 | # X is the event of reaching office on time 28 | # Y is the event of car working fine. 29 | # P(X) = P(X and Y) + P(X and Y') 30 | # P(X) = P(X/Y) * P(Y) + P(X/Y') * P(Y') 31 | 32 | Px = ((1 - Pct) * Pot) + (Pct * 2/N) 33 | print ("%.6f" % (Px)) 34 | -------------------------------------------------------------------------------- /Hackerearth/Micro_Array_Update.py: -------------------------------------------------------------------------------- 1 | def update_array(ARR,k): 2 | time_array=[] 3 | for i in range(len(ARR)): 4 | t=0 5 | while (ARR[i] < k): 6 | ARR[i]=ARR[i]+1 7 | t=t+1 8 | time_array.append(t) 9 | return (max(time_array)) 10 | 11 | 12 | if __name__=='__main__': 13 | T=int(input()) 14 | for tcase in range(T): 15 | N,K = list(map(int,input().strip().split())) 16 | arr = list(map(int,input().strip().split())) 17 | print (update_array(arr,K)) -------------------------------------------------------------------------------- /Hackerearth/Print_Array_In_Reverse.py: -------------------------------------------------------------------------------- 1 | ''' 2 | # Sample code to perform I/O: 3 | 4 | name = input() # Reading input from STDIN 5 | print('Hi, %s.' % name) # Writing output to STDOUT 6 | 7 | # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 8 | ''' 9 | 10 | # Write your code here 11 | if __name__=='__main__': 12 | 13 | N = int(input()) 14 | xarr=[] 15 | for H in range(N): 16 | x = int(input()) 17 | xarr.append(x) 18 | 19 | for k in xarr[::-1]: 20 | print (k) -------------------------------------------------------------------------------- /Hackerearth/README.md: -------------------------------------------------------------------------------- 1 | # Problems solved from Hackerearth platform 2 | -------------------------------------------------------------------------------- /Hackerearth/Samsung_Developer_Hiring_Challenge/BitEvenArrays_v0.1.py: -------------------------------------------------------------------------------- 1 | def odd_checker(u): 2 | binrep = bin(u)[2:] 3 | checker = [True if i == '0' else False for i in binrep[1::2]] 4 | if True in checker and False not in checker: 5 | return (1) 6 | else: 7 | return (0) 8 | 9 | def Bit_Even_Arrays(arr): 10 | miss_keys = [] 11 | for key,val in enumerate(arr): 12 | if val == -1: 13 | miss_keys.append(key) 14 | for x in miss_keys: 15 | y = x - 1 16 | z = arr[y] 17 | while True: 18 | if z%2==0 and odd_checker(z)==1: 19 | break 20 | else: 21 | z += 1 22 | arr[x]=z 23 | return (sum(arr)) 24 | 25 | 26 | if __name__ == '__main__': 27 | T = int(input()) 28 | for tcase in range(T): 29 | N = int(input()) 30 | arr = list(map(int,input().strip().split())) 31 | print (Bit_Even_Arrays(arr)) 32 | -------------------------------------------------------------------------------- /Hackerearth/Samsung_Developer_Hiring_Challenge/BitEvenArrays_v0.2.py: -------------------------------------------------------------------------------- 1 | def Bit_Even_Arrays(arr): 2 | for k,v in enumerate(arr): 3 | z=0 4 | if v == -1: 5 | y = k - 1 6 | z = arr[y] 7 | while True: 8 | S = bin(z)[2:][1::2] 9 | if (z%2==0) & (len(set(S))==1) & ('0' in set(S)): 10 | break 11 | else: 12 | z += 1 13 | arr[k]=z 14 | return (sum(arr)) 15 | 16 | 17 | if __name__ == '__main__': 18 | T = int(input()) 19 | for tcase in range(T): 20 | N = int(input()) 21 | arr = list(map(int,input().strip().split())) 22 | print (Bit_Even_Arrays(arr)) -------------------------------------------------------------------------------- /Hackerearth/Samsung_Developer_Hiring_Challenge/Bit_Even_Arrays_Question.md: -------------------------------------------------------------------------------- 1 | There is an array A of size N with entries as integers, some of the entries are -1. we need to replace -1's with numbers satisfying below criteria. 2 | The binary representation of number to be replaced with should have only 0's in its odd positions and the number has to be even. 3 | The array entries A[i] with which you replace -1's with are in such a way that A[i]>=A[i-1] and also for given array A[0]!=-1 4 | Find the minimum sum of array entries possible after the above operations are done. 5 | 6 | Input format: 7 | ``` 8 | First line T - number of test cases 9 | second line N - size of array 10 | Third line - N space separated integers 11 | ``` 12 | 13 | Sample Input: 14 | ``` 15 | 1 16 | 8 17 | 1 5 -1 25 -1 7 35 -1 18 | ``` 19 | 20 | Sample Output: 21 | `153` 22 | 23 | Explanation: 24 | ``` 25 | Index 2: Replacing -1 with 8 as its binary representation is 1000 which has 0 in its odd places and 8 is even and 8 >=5 26 | Index 4: Replacing -1 with 32 as its binary representation is 100000 which has 0 in its odd places and 32 is even and 32>=25 27 | Index 7: Replacing -1 with 40 as its binary representation is 101000 which has 0 in its odd places and 40 is even and 40>=35 28 | ``` 29 | -------------------------------------------------------------------------------- /Hackerearth/Vimeo_Full_Stack_Developer_Challenge/Vimeo_question_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Vimeo_Full_Stack_Developer_Challenge/Vimeo_question_01.png -------------------------------------------------------------------------------- /Hackerearth/Vimeo_Full_Stack_Developer_Challenge/Vimeo_question_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Vimeo_Full_Stack_Developer_Challenge/Vimeo_question_02.png -------------------------------------------------------------------------------- /Hackerearth/Vimeo_Full_Stack_Developer_Challenge/Vimeo_question_03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/Vimeo_Full_Stack_Developer_Challenge/Vimeo_question_03.png -------------------------------------------------------------------------------- /Hackerearth/countPositionsOfPartitions.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | def countPositions(S,K): 4 | partitions=[] 5 | for i in range(len(S)-1): 6 | partitions.append((S[:i+1],S[i+1:])) 7 | C=0 8 | for x in partitions: 9 | first = collections.Counter(x[0]) 10 | second = collections.Counter(x[1]) 11 | firstKeys = first.keys() 12 | secondKeys = second.keys() 13 | commonKeys = set(firstKeys).intersection(set(secondKeys)) 14 | if len(commonKeys) >= K: 15 | P = {a:first[a] for a in commonKeys} 16 | Q = {b:second[b] for b in commonKeys} 17 | if P==Q: 18 | C+=1 19 | return (C) 20 | 21 | if __name__ == '__main__': 22 | K = int(input()) 23 | S = input() 24 | print (countPositions(S,K)) -------------------------------------------------------------------------------- /Hackerearth/isPerfectNumber.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function that decides whether a given number is perfect number or not 3 | 4 | Definition: 5 | A perfect number is a number whose sum of divisors except for number itself 6 | is equal to itself (proper divisors) 7 | 8 | Ex: 6 = 1 + 2 + 3 (6 is a perfect number) 9 | 5 != 1 (5 is not a perfect number) 10 | 14 = 1 + 2 + 7 (Not a perfect number) 11 | 28 = 1 + 2 + 4 + 7 + 14 (28 is a perfect number) 12 | ''' 13 | 14 | # Write your code here 15 | def is_perfect_number(n): 16 | total = 1 17 | i = 2 18 | while (i*i <= n): 19 | if (n%i) == 0: 20 | if (i*i != n): 21 | total += (i + n//i) 22 | else: 23 | total += i 24 | i += 1 25 | if (total == n) and (n != 1): 26 | return 1 27 | else: 28 | return 0 29 | 30 | if __name__ == '__main__': 31 | T = int(input()) 32 | for tcase in range(T): 33 | N = int(input()) 34 | if is_perfect_number(N): 35 | print ("YES") 36 | else: 37 | print ("NO") -------------------------------------------------------------------------------- /Hackerearth/practice_problems/BalancedPartition.py: -------------------------------------------------------------------------------- 1 | def balanced_partition(points,persons): 2 | total_pe = sum(persons) 3 | h = {} 4 | for i in range(len(points)): 5 | h[points[i][0]-points[i][1]] = h.get(points[i][0]-points[i][1],0) + persons[i] 6 | avg = total_pe / 2 7 | t = 0 8 | for key in sorted(h.keys()): 9 | t += h[key] 10 | if t >= avg: 11 | if t > avg: 12 | if total_pe == 2*t - h[key]: 13 | return ("YES") 14 | else: 15 | return ("NO") 16 | else: 17 | return ("YES") 18 | break 19 | 20 | 21 | if __name__ == '__main__': 22 | t = int(input()) 23 | for _ in range(t): 24 | n = int(input()) 25 | points = [] 26 | persons = [] 27 | for l in range(n): 28 | p,q,m = list(map(int,input().strip().split())) 29 | points.append([p,q]) 30 | persons.append(m) 31 | print (balanced_partition(points,persons)) -------------------------------------------------------------------------------- /Hackerearth/practice_problems/Balanced_Partition_image1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/practice_problems/Balanced_Partition_image1.JPG -------------------------------------------------------------------------------- /Hackerearth/practice_problems/Balanced_Partition_image2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/practice_problems/Balanced_Partition_image2.JPG -------------------------------------------------------------------------------- /Hackerearth/practice_problems/Balanced_Partition_image3.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/practice_problems/Balanced_Partition_image3.JPG -------------------------------------------------------------------------------- /Hackerearth/practice_problems/Largest_CoPrime.py: -------------------------------------------------------------------------------- 1 | import math 2 | def largest_coP(n): 3 | max_coP = 0 4 | for r in range(1,n-1): 5 | if math.gcd(r,n) == 1: 6 | if max_coP < r: 7 | max_coP = r 8 | return (max_coP) 9 | 10 | if __name__ == '__main__': 11 | n = int(input()) 12 | print (largest_coP(n)) -------------------------------------------------------------------------------- /Hackerearth/practice_problems/largest_CoPrime.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Hackerearth/practice_problems/largest_CoPrime.png -------------------------------------------------------------------------------- /Hackerearth/sumOflargestOddDivisiorsModuloM.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given a positive integer N. f(N) is the greatest odd divisor of N. 3 | 4 | Find the sum (f(1)+f(2)+f(3)+f(4)+......f(N))%M. 5 | 6 | Input format 7 | 8 | The first line of the input contains a single integer T (T <= 100) 9 | denoting the number of test cases. The description of T test cases follows. 10 | The first line of each test case contains two integers N and M. 11 | 12 | Output format 13 | 14 | For each value of N, print the value of (f(1)+f(2)+f(3)+f(4)+......f(N))%M 15 | in a separate line. 16 | 17 | SAMPLE INPUT 18 | 5 19 | 1 100 20 | 110 30 21 | 12345 100000007 22 | 10 28383 23 | 100 5 24 | 25 | SAMPLE OUTPUT 26 | 1 27 | 18 28 | 50804693 29 | 36 30 | 4 31 | 32 | """ 33 | def greatestOddDivisor(n): 34 | if n%2 == 1: 35 | return n 36 | else: 37 | while(n%2 == 0): 38 | n = n//2 39 | return n 40 | 41 | def summoduloM(N,M): 42 | result = 0 43 | for u in range(1,N+1): 44 | result += greatestOddDivisor(u) 45 | return (result%M) 46 | 47 | if __name__ == '__main__': 48 | T = int(input()) 49 | for tcase in range(T): 50 | N,M = list(map(int,input().strip().split())) 51 | print (summoduloM(N,M)) -------------------------------------------------------------------------------- /Hackerrank/Mark_and_Toys.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | import itertools 9 | 10 | # Complete the maximumToys function below. 11 | def maximumToys(prices, k): 12 | prices_len = len(prices) 13 | suitable = [] 14 | for l in range(1,prices_len+1): 15 | for combination in itertools.combinations(prices,l): 16 | if sum(combination) <= k: 17 | suitable.append(len(combination)) 18 | return (max(suitable)) 19 | 20 | if __name__ == '__main__': 21 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 22 | 23 | nk = input().split() 24 | 25 | n = int(nk[0]) 26 | 27 | k = int(nk[1]) 28 | 29 | prices = list(map(int, input().rstrip().split())) 30 | 31 | result = maximumToys(prices, k) 32 | 33 | fptr.write(str(result) + '\n') 34 | 35 | fptr.close() 36 | -------------------------------------------------------------------------------- /Hackerrank/Marks_and_Toys_v2.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | import itertools 9 | 10 | # Complete the maximumToys function below. 11 | def maximumToys(prices, k): 12 | total = 0 13 | count = 0 14 | prices = sorted(prices) 15 | for p in prices: 16 | total += p 17 | if total <= k: 18 | count += 1 19 | return (count) 20 | 21 | if __name__ == '__main__': 22 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 23 | 24 | nk = input().split() 25 | 26 | n = int(nk[0]) 27 | 28 | k = int(nk[1]) 29 | 30 | prices = list(map(int, input().rstrip().split())) 31 | 32 | result = maximumToys(prices, k) 33 | 34 | fptr.write(str(result) + '\n') 35 | 36 | fptr.close() 37 | -------------------------------------------------------------------------------- /Hackerrank/OneMonthPreparationKit/PlusMinus.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | /* 8 | * Complete the 'plusMinus' function below. 9 | * 10 | * The function accepts INTEGER_ARRAY arr as parameter. 11 | */ 12 | 13 | func plusMinus(arr []int32) { 14 | // Write your code here 15 | cnt_positive := 0 16 | cnt_negative := 0 17 | cnt_zeros := 0 18 | for _, item := range arr { 19 | if item > 0 { 20 | cnt_positive++ 21 | } else if item < 0 { 22 | cnt_negative++ 23 | } else { 24 | cnt_zeros++ 25 | } 26 | } 27 | fmt.Printf("%.6f\n", float64(cnt_positive)/float64(len(arr))) 28 | fmt.Printf("%.6f\n", float64(cnt_negative)/float64(len(arr))) 29 | fmt.Printf("%.6f\n", float64(cnt_zeros)/float64(len(arr))) 30 | } 31 | -------------------------------------------------------------------------------- /Hackerrank/OneMonthPreparationKit/go.mod: -------------------------------------------------------------------------------- 1 | module OneMonthPreparationKit 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /Hackerrank/OneMonthPreparationKit/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func main() { 12 | reader := bufio.NewReaderSize(os.Stdin, 16*1024*1024) 13 | 14 | nTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64) 15 | checkError(err) 16 | n := int32(nTemp) 17 | 18 | arrTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ") 19 | 20 | var arr []int32 21 | 22 | for i := 0; i < int(n); i++ { 23 | arrItemTemp, err := strconv.ParseInt(arrTemp[i], 10, 64) 24 | checkError(err) 25 | arrItem := int32(arrItemTemp) 26 | arr = append(arr, arrItem) 27 | } 28 | 29 | plusMinus(arr) 30 | } 31 | 32 | func readLine(reader *bufio.Reader) string { 33 | str, _, err := reader.ReadLine() 34 | if err == io.EOF { 35 | return "" 36 | } 37 | 38 | return strings.TrimRight(string(str), "\r\n") 39 | } 40 | 41 | func checkError(err error) { 42 | if err != nil { 43 | panic(err) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Hackerrank/README.md: -------------------------------------------------------------------------------- 1 | # Problems solved from Hackerrank Platform 2 | -------------------------------------------------------------------------------- /Hackerrank/SQL/Placements.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | https://www.hackerrank.com/challenges/placements 4 | 5 | Solution: Oracle 6 | 7 | */ 8 | 9 | select name from 10 | ( 11 | select s1.id as id, 12 | s2.id as friend_id, 13 | s1.name as name, 14 | s2.name as friend_name, 15 | p1.salary as salary, 16 | p2.salary as friend_salary 17 | from students s1 18 | cross join students s2 19 | join packages p1 on ( 20 | s1.id = p1.id 21 | ) 22 | join packages p2 on ( 23 | s2.id = p2.id 24 | ) 25 | where s1.id != s2.id and (cast(s1.id as varchar(10)) || '_' || cast(s2.id as varchar(10))) in ( 26 | select cast(id as varchar(10)) || '_' || cast(friend_id as varchar(10)) from friends 27 | ) 28 | ) where friend_salary > salary order by friend_salary asc; 29 | -------------------------------------------------------------------------------- /Hackerrank/SQL/SymmetricPairs.sql: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | https://www.hackerrank.com/challenges/symmetric-pairs/problem 4 | 5 | Oracle Solution 6 | 7 | */ 8 | 9 | with find_x_eq_y as ( 10 | select x, 11 | y, 12 | count(*) 13 | from functions 14 | where x = y 15 | group by x, 16 | y 17 | having count(*) = 1 18 | ) 19 | select distinct f.x, 20 | f.y 21 | from functions f 22 | cross join functions other_f 23 | where ( 24 | f.x = other_f.y 25 | and f.y = other_f.x 26 | ) 27 | and (f.x <= f.y) 28 | and ( 29 | cast(f.x as varchar(10)) || '_' || cast(f.y as varchar(10)) 30 | ) not in ( 31 | select distinct cast(x as varchar(10)) || '_' || cast(y as varchar(10)) 32 | from find_x_eq_y 33 | ) 34 | order by f.x asc; 35 | -------------------------------------------------------------------------------- /Hackerrank/countInversions_MergeSort.py: -------------------------------------------------------------------------------- 1 | def countInversions(arr,n): 2 | numInversions = 0 3 | i = 0 4 | while (i < len(arr)-1): 5 | if (arr[i] > arr[i+1]): 6 | tmp = arr[i] 7 | arr[i] = arr[i+1] 8 | arr[i+1] = tmp 9 | i+=1 10 | numInversions+=1 11 | else: 12 | i+=1 13 | return (numInversions,arr) 14 | 15 | if __name__ == '__main__': 16 | d = int(input()) 17 | num_iterations = int(input()) 18 | for xcase in range(d): 19 | n = int(input()) 20 | arr = list(map(int,input().strip().split())) 21 | Total_Inversions = 0 22 | for X in range(num_iterations): 23 | numInversions,array = countInversions(arr,n) 24 | Total_Inversions += numInversions 25 | print (Total_Inversions) -------------------------------------------------------------------------------- /InterviewBit/Add_Number_One.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return a list of integers 4 | def plusOne(self, A): 5 | num_string = ''.join(str(i) for i in A) 6 | num = int(num_string) 7 | num = num + 1 8 | num = str(num) 9 | final_arr = list(num) 10 | return (final_arr) 11 | 12 | if __name__ == '__main__': 13 | A = list(map(int,input().strip().split())) 14 | solution = Solution() 15 | print (solution.plusOne(A)) -------------------------------------------------------------------------------- /InterviewBit/ObjectiveQuestion_Arrays.py: -------------------------------------------------------------------------------- 1 | def performOps(A): 2 | m = len(A) 3 | n = len(A[0]) 4 | B = [] 5 | for i in range(len(A)): 6 | B.append([0] * n) 7 | for j in range(len(A[i])): 8 | B[i][n - 1 - j] = A[i][j] 9 | return B 10 | 11 | A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 12 | 13 | B = performOps(A) 14 | for i in range(len(B)): 15 | for j in range(len(B[i])): 16 | print (B[i][j]) 17 | 18 | 19 | #Answer : 4 3 2 1 8 7 6 5 12 11 10 9 -------------------------------------------------------------------------------- /InterviewBit/minSteps_in_InfiniteGrid.py: -------------------------------------------------------------------------------- 1 | #Traversing from one point to another point 2 | #storing the minimum number of steps 3 | def traversal_steps(A,B): 4 | points = list(zip(A,B)) 5 | minSteps = 0 6 | for p in range(len(points)-1): 7 | #taking the manhattan distance between x and y-coordinates 8 | d1 = abs(points[p][0] - points[p+1][0]) 9 | d2 = abs(points[p][1] - points[p+1][1]) 10 | #adding the maximum among the two to the running steps parameter 11 | minSteps += max(d1,d2) 12 | return (minSteps) 13 | 14 | #Main Driver Code 15 | if __name__ == '__main__': 16 | A = list(map(int,input().strip().split())) 17 | B = list(map(int,input().strip().split())) 18 | print (traversal_steps(A,B)) -------------------------------------------------------------------------------- /KadanesAlgorithm.py: -------------------------------------------------------------------------------- 1 | 2 | ARR = list(map(int,input().strip().split())) 3 | 4 | def Kadanes_Algorithm(arr): 5 | indicator_array = [True if i >=0 else False for i in arr] 6 | if True in indicator_array: 7 | max_so_far=max_ending_here=0 8 | for a in range(len(arr)): 9 | max_ending_here = max_ending_here + arr[a] 10 | if max_ending_here < 0: 11 | max_ending_here = 0 12 | if max_so_far < max_ending_here: 13 | max_so_far = max_ending_here 14 | return (max_so_far) 15 | elif False in indicator_array and True not in indicator_array: 16 | return (max(arr)) 17 | 18 | print (Kadanes_Algorithm(ARR)) -------------------------------------------------------------------------------- /Last_Occurence_of_element_in_Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | # Sample code to perform I/O: 3 | 4 | name = input() # Reading input from STDIN 5 | print('Hi, %s.' % name) # Writing output to STDOUT 6 | 7 | # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail 8 | ''' 9 | 10 | N, M = list(map(int,input().strip().split())) 11 | 12 | arr = list(map(int,input().strip().split())) 13 | 14 | if M in arr: 15 | inds = [] 16 | for i in range(len(arr)): 17 | if (arr[i] == M): 18 | inds.append(i+1) 19 | print (max(inds)) 20 | else: 21 | print (-1) 22 | 23 | 24 | -------------------------------------------------------------------------------- /LeetCode/GCDOf2Strings.py: -------------------------------------------------------------------------------- 1 | # For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t 2 | # (i.e., t is concatenated with itself one or more times). 3 | 4 | # Given two strings str1 and str2, return the largest string x such that x divides 5 | # both str1 and str2. 6 | 7 | # Example 1: 8 | 9 | # Input: str1 = "ABCABC", str2 = "ABC" 10 | # Output: "ABC" 11 | # Example 2: 12 | 13 | # Input: str1 = "ABABAB", str2 = "ABAB" 14 | # Output: "AB" 15 | # Example 3: 16 | 17 | # Input: str1 = "LEET", str2 = "CODE" 18 | # Output: "" 19 | 20 | # Constraints: 21 | 22 | # 1 <= str1.length, str2.length <= 1000 23 | # str1 and str2 consist of English uppercase letters. 24 | 25 | class Solution: 26 | def gcdOfStrings(self, str1: str, str2: str) -> str: 27 | if str1 + str2 != str2 + str1: 28 | return "" 29 | def gcd(a, b): 30 | while b: 31 | a, b = b, a % b 32 | return a 33 | return str1[:gcd(len(str1), len(str2))] -------------------------------------------------------------------------------- /LeetCode/NUEL.py: -------------------------------------------------------------------------------- 1 | def lunchProcess(sandwiches:int, students:int) -> int: 2 | assert len(sandwiches) == len(students), "Error in sizes of arrays" 3 | sandwiches_array = sandwiches.copy() 4 | students_array = students.copy() 5 | while True: 6 | if len(students_array) == 0: 7 | return 0 8 | if len(set(students_array)) == 1: 9 | ele = list(set(students_array))[0] 10 | if ele != sandwiches_array[0]: 11 | return len(students_array) 12 | if students_array[0] == sandwiches_array[0]: 13 | sandwiches_array.pop(0) 14 | students_array.pop(0) 15 | else: 16 | students_array = students_array[1:] + [students_array[0]] 17 | 18 | 19 | if __name__ == '__main__': 20 | sandwiches = [0,1,0,1] 21 | students = [1,1,0,0] 22 | print (lunchProcess(sandwiches,students)) 23 | 24 | sandwiches = [1,0,0,0,1,1] 25 | students = [1,1,1,0,0,1] 26 | 27 | print (lunchProcess(sandwiches,students)) -------------------------------------------------------------------------------- /LeetCode/ProgrammingInGo/MergeAlternately/MergeAlternately.go: -------------------------------------------------------------------------------- 1 | /* 2 | Leetcode 75 3 | You are given two strings word1 and word2. Merge the strings by adding letters in alternating 4 | order, 5 | starting with word1. If a string is longer than the other, append the additional letters 6 | onto the end of the merged string. 7 | 8 | Return the merged string. 9 | 10 | Example 1: 11 | 12 | Input: word1 = "abc", word2 = "pqr" 13 | Output: "apbqcr" 14 | Explanation: The merged string will be merged as so: 15 | word1: a b c 16 | word2: p q r 17 | merged: a p b q c r 18 | Example 2: 19 | 20 | Input: word1 = "ab", word2 = "pqrs" 21 | Output: "apbqrs" 22 | Explanation: Notice that as word2 is longer, "rs" is appended to the end. 23 | word1: a b 24 | word2: p q r s 25 | merged: a p b q r s 26 | Example 3: 27 | 28 | Input: word1 = "abcd", word2 = "pq" 29 | Output: "apbqcd" 30 | Explanation: Notice that as word1 is longer, "cd" is appended to the end. 31 | word1: a b c d 32 | word2: p q 33 | merged: a p b q c d 34 | 35 | Constraints: 36 | 37 | 1 <= word1.length, word2.length <= 100 38 | word1 and word2 consist of lowercase English letters. 39 | */ 40 | 41 | package MergeAlternately 42 | 43 | func MergeAlternate(word1 string, word2 string) string { 44 | result := "" 45 | for i := 0; i < len(word1) || i < len(word2); i++ { 46 | if i < len(word1) { 47 | result += string(word1[i]) 48 | } 49 | if i < len(word2) { 50 | result += string(word2[i]) 51 | } 52 | } 53 | return result 54 | } -------------------------------------------------------------------------------- /LeetCode/ProgrammingInGo/README.md: -------------------------------------------------------------------------------- 1 | # Leetcode 75 Solutions in Go - https://leetcode.com/studyplan/leetcode-75/ 2 | -------------------------------------------------------------------------------- /LeetCode/ProgrammingInGo/dataengineering/removeduplicates/removeduplicates.go: -------------------------------------------------------------------------------- 1 | package removeduplicates 2 | 3 | func RemoveDuplicates(nums []int) int { 4 | if len(nums) == 0 { 5 | return 0 6 | } 7 | unique_index := 0 8 | for i := 1; i < len(nums); i++ { 9 | if nums[i] != nums[unique_index] { 10 | unique_index++ 11 | nums[unique_index] = nums[i] 12 | } 13 | } 14 | return unique_index + 1 15 | } 16 | -------------------------------------------------------------------------------- /LeetCode/ProgrammingInGo/dataengineering/secondlargestelement/findsecondlargestelement.go: -------------------------------------------------------------------------------- 1 | package secondlargestelement 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func FindSecondLargestElement(arr []int) any { 8 | const string1 = "No second largest element found" 9 | const string2 = "Array does not have enough elements" 10 | if len(arr) < 2 { 11 | return string2 12 | } 13 | var first int = math.MinInt64 14 | var second int = math.MinInt64 15 | for i := 0; i < len(arr); i++ { 16 | if arr[i] > first { 17 | second = first 18 | first = arr[i] 19 | } else if arr[i] > second && arr[i] != first { 20 | second = arr[i] 21 | } 22 | } 23 | if second == math.MinInt64 { 24 | return string1 25 | } 26 | return second 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode/ProgrammingInGo/gcd/gcdofstrings.go: -------------------------------------------------------------------------------- 1 | // Leetcode 75 2 | // Greatest Common Divisor (Largest String that divides given 2 strings) 3 | 4 | package gcd 5 | 6 | func gcd_util(a int, b int) int { 7 | for b != 0 { 8 | t := b 9 | b = a % b 10 | a = t 11 | } 12 | return a 13 | } 14 | func GCDofStrings(str1 string, str2 string) string { 15 | null_str := "" 16 | if (str1 + str2) != (str2 + str1) { 17 | return null_str 18 | } 19 | return str1[0:gcd_util(len(str1), len(str2))] 20 | } -------------------------------------------------------------------------------- /LeetCode/ProgrammingInGo/go.mod: -------------------------------------------------------------------------------- 1 | module ProgrammingInGo 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /LeetCode/SQL50/FixNamesInTable.sql: -------------------------------------------------------------------------------- 1 | -- Table: Users 2 | 3 | -- +----------------+---------+ 4 | -- | Column Name | Type | 5 | -- +----------------+---------+ 6 | -- | user_id | int | 7 | -- | name | varchar | 8 | -- +----------------+---------+ 9 | -- user_id is the primary key (column with unique values) for this table. 10 | -- This table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters. 11 | 12 | 13 | -- Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase. 14 | 15 | -- Return the result table ordered by user_id. 16 | 17 | -- The result format is in the following example. 18 | 19 | 20 | 21 | -- Example 1: 22 | 23 | -- Input: 24 | -- Users table: 25 | -- +---------+-------+ 26 | -- | user_id | name | 27 | -- +---------+-------+ 28 | -- | 1 | aLice | 29 | -- | 2 | bOB | 30 | -- +---------+-------+ 31 | -- Output: 32 | -- +---------+-------+ 33 | -- | user_id | name | 34 | -- +---------+-------+ 35 | -- | 1 | Alice | 36 | -- | 2 | Bob | 37 | -- +---------+-------+ 38 | 39 | -- Write your PostgreSQL query statement below 40 | -- Solution 41 | 42 | select user_id, 43 | upper(left(name,1)) || lower(right(name,length(name)-1)) as name 44 | from Users order by user_id; 45 | -------------------------------------------------------------------------------- /LeetCode/SQL50/InvalidTweets.sql: -------------------------------------------------------------------------------- 1 | -- Write your PostgreSQL query statement below 2 | select tweet_id from tweets where length(content) > 15; 3 | -------------------------------------------------------------------------------- /LeetCode/SQL50/TriangleJudgement.sql: -------------------------------------------------------------------------------- 1 | -- Table: Triangle 2 | 3 | -- +-------------+------+ 4 | -- | Column Name | Type | 5 | -- +-------------+------+ 6 | -- | x | int | 7 | -- | y | int | 8 | -- | z | int | 9 | -- +-------------+------+ 10 | -- In SQL, (x, y, z) is the primary key column for this table. 11 | -- Each row of this table contains the lengths of three line segments. 12 | 13 | -- Report for every three line segments whether they can form a triangle. 14 | 15 | -- Return the result table in any order. 16 | 17 | -- The result format is in the following example. 18 | 19 | -- Example 1: 20 | 21 | -- Input: 22 | -- Triangle table: 23 | -- +----+----+----+ 24 | -- | x | y | z | 25 | -- +----+----+----+ 26 | -- | 13 | 15 | 30 | 27 | -- | 10 | 20 | 15 | 28 | -- +----+----+----+ 29 | -- Output: 30 | -- +----+----+----+----------+ 31 | -- | x | y | z | triangle | 32 | -- +----+----+----+----------+ 33 | -- | 13 | 15 | 30 | No | 34 | -- | 10 | 20 | 15 | Yes | 35 | -- +----+----+----+----------+ 36 | 37 | 38 | 39 | -- Write your PostgreSQL query statement below 40 | -- Solution 41 | 42 | select x, 43 | y, 44 | z, 45 | case when (x + y > z and 46 | y + z > x and 47 | z + x > y) then 'Yes' 48 | else 'No' 49 | end as triangle 50 | from Triangle; 51 | -------------------------------------------------------------------------------- /LinearSearch.py: -------------------------------------------------------------------------------- 1 | #Linear Search in indexed interables - Lists, Tuples, Sets 2 | 3 | arr = [2,10,8,0,-4,72,37,10,-3,10,2,3,4,8] 4 | 5 | x = 8 6 | 7 | def linearSearch(arr,x): 8 | if (arr.count(x)==1): 9 | return (arr.index(x)) 10 | elif x not in arr: 11 | print ('Element does not exist') 12 | elif (arr.count(x)>1): 13 | inds = [i for i in range(len(arr)) if arr[i]==x] 14 | return (inds) -------------------------------------------------------------------------------- /LinkedLists/Creation_of_Linked_List.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self,dataVal): 3 | self.data = dataVal 4 | self.next = None 5 | 6 | def getData(self): 7 | return (self.data) 8 | 9 | def setData(self,val): 10 | self.data = val 11 | 12 | def getNextNode(self): 13 | return (self.next) 14 | 15 | def setNextNode(self,nextVal): 16 | self.next = nextVal 17 | 18 | class LinkedList(object): 19 | def __init__(self,head=None): 20 | self.head = head 21 | self.lastNode = None 22 | self.size = 0 23 | 24 | def getSize(self): 25 | return self.size 26 | 27 | def insertNode(self,data): 28 | if self.head == None: 29 | self.head = Node(data) 30 | self.lastNode = self.head 31 | self.size+=1 32 | else: 33 | newNode = Node(data) 34 | self.lastNode.next = newNode 35 | self.lastNode = newNode 36 | self.size+=1 37 | 38 | def traversal(self): 39 | T = self.head 40 | while T is not None: 41 | print (T.data,end = " ") 42 | T = T.next -------------------------------------------------------------------------------- /LinkedLists/create_linked_list_of_n_nodes.py: -------------------------------------------------------------------------------- 1 | from Creation_of_Linked_List import * 2 | 3 | num_nodes = int(input()) 4 | arr = list(map(int,input().strip().split())) 5 | 6 | if __name__ == '__main__': 7 | linkedList = LinkedList() 8 | for i in range(num_nodes): 9 | linkedList.insertNode(arr[i]) 10 | linkedList.traversal() -------------------------------------------------------------------------------- /Skillenza/KingsMarch.py: -------------------------------------------------------------------------------- 1 | import allPathsInaMatrix as aPIM 2 | def KingsMarch(cb): 3 | aPIM.storePaths='' 4 | m = len(cb) 5 | n = len(cb[0]) 6 | aPIM.findPaths(cb,m,n) 7 | myPaths = aPIM.storePaths.split('|') 8 | myPaths.remove('') 9 | myPaths = [p for p in myPaths if 'x' not in p] 10 | myPaths = [list(map(int,list(a)[1:len(a)-1])) for a in myPaths] 11 | if myPaths: 12 | myMax = max([sum(u) for u in myPaths]) 13 | S = 0 14 | for H in myPaths: 15 | if sum(H)==myMax: 16 | S += 1 17 | return (myMax,S) 18 | else: 19 | return (0,len(myPaths)) 20 | 21 | if __name__ == '__main__': 22 | T = int(input()) 23 | for tcase in range(T): 24 | n = int(input()) 25 | chess_board = [] 26 | for x in range(n): 27 | arr = input().strip().split() 28 | chess_board.append(arr) 29 | print (KingsMarch(chess_board)) -------------------------------------------------------------------------------- /Skillenza/KingsMarch1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Skillenza/KingsMarch1.png -------------------------------------------------------------------------------- /Skillenza/KingsMarch2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/Skillenza/KingsMarch2.png -------------------------------------------------------------------------------- /SortingAlgorithms/BubbleSort.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | Array = [0]*n 3 | temp=0 4 | for i in range(n): 5 | Array[i] = int(input()) 6 | print (Array) 7 | for k in range(n-1): 8 | for m in range(n-k-1): 9 | ##swap case 10 | if Array[m] > Array[m+1]: 11 | temp=Array[m] 12 | Array[m] = Array[m+1] 13 | Array[m+1]=temp 14 | m+=1 15 | k+=1 16 | 17 | print (Array) 18 | ##Time complexity = O(n**2) -------------------------------------------------------------------------------- /SortingAlgorithms/InsertionSort.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | Array = [0]*n 3 | for i in range(n): 4 | Array[i] = int(input()) 5 | print (Array) 6 | 7 | for v in range(n): 8 | temp = Array[v] 9 | u = v 10 | while ((u > 0) & (temp < Array[u-1])): 11 | Array[u] = Array[u-1] 12 | u-=1 13 | Array[u] = temp 14 | 15 | print (Array) -------------------------------------------------------------------------------- /SortingAlgorithms/MergeSort.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | Array = [0]*n 3 | for i in range(n): 4 | Array[i] = int(input()) 5 | print (Array) 6 | 7 | def merge(arr, l, m, r): 8 | n1 = m - l + 1 9 | n2 = r- m 10 | # create temp arrays 11 | L = [0] * (n1) 12 | R = [0] * (n2) 13 | # Copy data to temp arrays L[] and R[] 14 | for i in range(0 , n1): 15 | L[i] = arr[l + i] 16 | for j in range(0 , n2): 17 | R[j] = arr[m + 1 + j] 18 | # Merge the temp arrays back into arr[l..r] 19 | i = 0 # Initial index of first subarray 20 | j = 0 # Initial index of second subarray 21 | k = l # Initial index of merged subarray 22 | while i < n1 and j < n2 : 23 | if L[i] <= R[j]: 24 | arr[k] = L[i] 25 | i += 1 26 | else: 27 | arr[k] = R[j] 28 | j += 1 29 | k += 1 30 | # Copy the remaining elements of L[], if there 31 | # are any 32 | while i < n1: 33 | arr[k] = L[i] 34 | i += 1 35 | k += 1 36 | # Copy the remaining elements of R[], if there 37 | # are any 38 | while j < n2: 39 | arr[k] = R[j] 40 | j += 1 41 | k += 1 42 | 43 | def mergeSort(arr, start, end): 44 | if (start < end): 45 | mid = (start + end - 1)//2 46 | mergeSort(arr,start,mid) 47 | mergeSort(arr,mid+1,end) 48 | merge(arr,start,mid,end) 49 | return (arr) 50 | 51 | print (mergeSort(Array)) -------------------------------------------------------------------------------- /SortingAlgorithms/QuickSort.py: -------------------------------------------------------------------------------- 1 | { 2 | #Initial Template for Python 3 3 | if __name__ == "__main__": 4 | t=int(input()) 5 | for i in range(t): 6 | n=int(input()) 7 | arr=list(map(int,input().split())) 8 | quickSort(arr,0,n-1) 9 | for i in range(n): 10 | print(arr[i],end=" ") 11 | print() 12 | 13 | } 14 | ''' This is a function problem.You only need to complete the function given below ''' 15 | #User function Template for python3 16 | def quickSort(arr,low,high): 17 | if low < high: 18 | 19 | # pi is partitioning index, arr[p] is now 20 | # at right place 21 | pi = partition(arr,low,high) 22 | 23 | # Separately sort elements before 24 | # partition and after partition 25 | quickSort(arr, low, pi-1) 26 | quickSort(arr, pi+1, high) 27 | 28 | def partition(arr,low,high): 29 | #add code here 30 | tmp = 0 31 | pivot = arr[high] 32 | i = low - 1 33 | for j in range(low,high): 34 | if arr[j] <= pivot: 35 | i += 1 36 | tmp = arr[i] 37 | arr[i] = arr[j] 38 | arr[j] = tmp 39 | tmp = arr[i+1] 40 | arr[i+1] = arr[high] 41 | arr[high] = tmp 42 | return i+1 -------------------------------------------------------------------------------- /SortingAlgorithms/SelectionSort.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | Array = [0]*n 3 | for i in range(n): 4 | Array[i] = int(input()) 5 | print (Array) 6 | 7 | temp_minimum=0 8 | TEMP=0 9 | for i in range(n-1): 10 | temp_minimum=i 11 | for j in range(i+1,n): 12 | if Array[j] < Array[temp_minimum]: 13 | temp_minimum=j 14 | TEMP=Array[temp_minimum] 15 | Array[temp_minimum]=Array[i] 16 | Array[i]=TEMP 17 | print (Array) 18 | #Time Complexity= O(n**2) 19 | -------------------------------------------------------------------------------- /SortingAlgorithms/SelectionSort_v2.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | Array = [0]*n 3 | for i in range(n): 4 | Array[i] = int(input()) 5 | print(Array) 6 | 7 | temp = 0 8 | for m in range(n): 9 | for p in range(m+1,n): 10 | if Array[m] > Array[p]: 11 | temp = Array[m] 12 | Array[m] = Array[p] 13 | Array[p] = temp 14 | print (Array) 15 | 16 | #Time Complexity = O(n**2) -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /binary_to_string.py: -------------------------------------------------------------------------------- 1 | strg = input().strip().split() 2 | bin_to_string = '' 3 | for s in strg: 4 | bin_to_string = bin_to_string + chr(int(s,2)) 5 | print (bin_to_string) 6 | 7 | -------------------------------------------------------------------------------- /clooTrack_Python_Challenge/Python_Coding_Assignment.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/clooTrack_Python_Challenge/Python_Coding_Assignment.docx -------------------------------------------------------------------------------- /clooTrack_Python_Challenge/tweet_frequency.py: -------------------------------------------------------------------------------- 1 | def tweet_analyzer(TWEETS): 2 | names=[] 3 | tweet_ids = [] 4 | for t in TWEETS: 5 | names.append(t.split()[0]) 6 | tweet_ids.append(t.split()[1]) 7 | 8 | name_freq={} 9 | for N in names: 10 | if N in name_freq: 11 | name_freq[N]+=1 12 | else: 13 | name_freq[N]=1 14 | distinct_len = len(list(set(list(name_freq.values())))) 15 | length = len(list(name_freq.values())) 16 | if (distinct_len==length): 17 | KEY = [k for k,v in name_freq.items() if v==max(list(name_freq.values()))] 18 | print (KEY[0],max(list(name_freq.values()))) 19 | else: 20 | for k in sorted(name_freq): 21 | print (k,name_freq[k]) 22 | 23 | 24 | if __name__ == '__main__': 25 | T=int(input()) 26 | for t_c in range(T): 27 | N_tw = int(input()) 28 | tweets = [] 29 | for n in range(N_tw): 30 | tweet = input() 31 | tweets.append(tweet) 32 | tweet_analyzer(tweets) 33 | -------------------------------------------------------------------------------- /fibonacci_progression.py: -------------------------------------------------------------------------------- 1 | def fibonacciSeries(a,b,n): 2 | i=0 3 | fib = [a,b] 4 | while (i<=n): 5 | c = a+b 6 | a=b 7 | b=c 8 | fib.append(c) 9 | print (c) 10 | i+=1 11 | return (fib) 12 | 13 | N = int(input()) 14 | a,b=1,1 15 | fibonacciSeries(a,b,N) -------------------------------------------------------------------------------- /find2Numbers_DivisiorsGiven.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | arr = list(map(int,input().strip().split())) 4 | Fmax = max(arr) 5 | element_freqs = Counter(arr) 6 | for k,v in element_freqs.items(): 7 | if Fmax%k==0: 8 | element_freqs[k]-=1 9 | 10 | sorted_freqs = sorted(element_freqs.items(),key=lambda x:x[1], 11 | reverse=True) 12 | Smax = sorted_freqs[1][0] 13 | print (Fmax,Smax) -------------------------------------------------------------------------------- /interviewing.io/Airbnb/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /interviewing.io/Airbnb/reverseString.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a quick function that reverses a given string 3 | 4 | """ 5 | 6 | 7 | #Index based method 8 | def reverse_string(s): 9 | return s[::-1] 10 | 11 | #Using built-in reverse method on class list 12 | def reverse_string1(s): 13 | h = list(s) 14 | h.reverse() 15 | return "".join(h) 16 | 17 | 18 | #Using O(n) auxiliary space 19 | def reverse_string2(s): 20 | v = len(s) 21 | u = [''] * v 22 | for c in range(v): 23 | u[v-c-1] = s[c] 24 | return ''.join(u) 25 | 26 | #Two pointer approach to swap the characters 27 | #O(1) space as nothing is stored here 28 | def reverse_string3(s): 29 | if len(s) > 1: 30 | start = 0 31 | end = len(s) - 1 32 | s = list(s) 33 | while (start != end): 34 | temp = s[start] 35 | s[start]=s[end] 36 | s[end] = temp 37 | start += 1 38 | end -= 1 39 | return "".join(s) 40 | else: 41 | return s 42 | 43 | 44 | if __name__ == '__main__': 45 | string = "competitive" 46 | print (reverse_string(string)) 47 | print (reverse_string1(string)) 48 | print (reverse_string2(string)) 49 | print (reverse_string3(string)) 50 | print (reverse_string3('g')) -------------------------------------------------------------------------------- /interviewing.io/Linkedin/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /interviewing.io/README.md: -------------------------------------------------------------------------------- 1 | # Interviewing.io: Please checkout `interviewing.io` youtube channel for these problems (Difference is my own solutions are added here). 2 | 1. See the question from the video. 3 | 2. pause the video. 4 | 3. Try it on your own. 5 | 4. Compare your solution with solution presented. 6 | 7 | ## Google Interview Questions: 8 | 9 | 1. Explain the asymptotic way of analyzing the insert and delete operations in array and linked-list data structures? 10 | -------------------------------------------------------------------------------- /interviewing.io/Salesforce/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /interviewing.io/Salesforce/check_rotation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two strings: 3 | 4 | string1 = "abcde" 5 | string2 = "cdeab" 6 | 7 | write a function that returns True if string2 can be obtained by rotating 8 | string1 if not return False (rotation can be done by any number of elements) 9 | 10 | """ 11 | def rotate(array,m): 12 | cutoff_arr = array[0:m] 13 | rotated_arr = array[m:] + cutoff_arr 14 | return (rotated_arr) 15 | 16 | def check_rotation(str1,str2): 17 | if len(str1) != len(str2): 18 | return False 19 | for i in range(1,len(str1)): 20 | if rotate(str1,i) == string2: 21 | return True 22 | return False 23 | 24 | 25 | def check_rotation2(str1,str2): 26 | if len(str1) != len(str2): 27 | return False 28 | union = str1 * 2 29 | if str2 in union: 30 | return True 31 | return False 32 | 33 | if __name__ == '__main__': 34 | string1 = 'abcde' 35 | string2 = 'cdeab' 36 | print (check_rotation(string1,string2)) 37 | print (check_rotation2(string1,string2)) 38 | 39 | string3 = "abcde" 40 | string4 = "eabcdf" 41 | print (check_rotation(string3,string4)) 42 | print (check_rotation2(string3,string4)) -------------------------------------------------------------------------------- /interviewing.io/Salesforce/findTheElementOccurringOnce.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array with odd number of elements in which all elements occurring twice in 3 | the array except for one element which occurs only once. 4 | 5 | Find that element 6 | 7 | Few solutions: 8 | 1. Brute force approach (looping over the whole array and perform extensive search) 9 | 2. Use a hashmap (store the frequencies of all the elements) 10 | 3. Using bit-magic 11 | 12 | """ 13 | 14 | import collections 15 | def findThatElement(array): 16 | n = len(array) 17 | if n%2 != 1: 18 | return "no element is occurring once" 19 | freqs = collections.Counter(array) 20 | for k,v in freqs.items(): 21 | if v == 1: 22 | return k 23 | 24 | def findThatElement2(array): 25 | x = 0 26 | for num in array: 27 | x ^= num 28 | return x 29 | 30 | if __name__ == '__main__': 31 | array = [1,1,2] 32 | array2 = [1,1,2,2,11,11,3] 33 | 34 | print (findThatElement(array)) 35 | print (findThatElement2(array)) 36 | 37 | print (findThatElement(array2)) 38 | print (findThatElement2(array2)) -------------------------------------------------------------------------------- /minDiff_powerof2_N.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | 3 | import math 4 | def min_diff_N_pow2(N): 5 | power=math.log(N,2) 6 | lower_bound = math.floor(power) 7 | upper_bound = math.ceil(power) 8 | lower_diff = abs(pow(2,lower_bound)-N) 9 | upper_diff = abs(pow(2,upper_bound)-N) 10 | return (min(lower_diff,upper_diff)) 11 | 12 | 13 | print (min_diff_N_pow2(N)) -------------------------------------------------------------------------------- /modulo_expression.py: -------------------------------------------------------------------------------- 1 | #(a * b) % m = ( (a % m) * (b % m) ) % m 2 | 3 | #(b ^ -1) % m = (b ^ m-2) % m (Fermat's little theorem) 4 | 5 | #( (A mod m) * ( power(B, m-2) % m) ) % m 6 | 7 | #Python program without Recursion 8 | 9 | A, B = list(map(int,input().strip().split())) 10 | 11 | m = 1000000007 12 | 13 | def mod(p,q): 14 | return (p%q) 15 | 16 | z = mod(A,m) 17 | w = pow(B,m-2) 18 | s = mod(w,m) 19 | r = mod(z*s,m) 20 | 21 | print (r) 22 | 23 | -------------------------------------------------------------------------------- /remAnagram.py: -------------------------------------------------------------------------------- 1 | # Python 3 program to find minimum 2 | # number of characters 3 | # to be removed to make two 4 | # strings anagram. 5 | import string 6 | CHARS = len(string.ascii_lowercase) 7 | # function to calculate minimum 8 | # numbers of characters 9 | # to be removed to make two 10 | # strings anagram 11 | def remAnagram(str1, str2): 12 | 13 | # make hash array for both string 14 | # and calculate 15 | # frequency of each character 16 | count1 = [0]*CHARS 17 | count2 = [0]*CHARS 18 | 19 | # count frequency of each character 20 | # in first string 21 | i = 0 22 | while i < len(str1): 23 | count1[ord(str1[i])-ord('a')] += 1 24 | i += 1 25 | 26 | # count frequency of each character 27 | # in second string 28 | i = 0 29 | while i < len(str2): 30 | count2[ord(str2[i])-ord('a')] += 1 31 | i += 1 32 | 33 | # traverse count arrays to find 34 | # number of characters 35 | # to be removed 36 | result = 0 37 | for i in range(26): 38 | result += abs(count1[i] - count2[i]) 39 | return result 40 | 41 | # Driver program to run the case 42 | if __name__ == "__main__": 43 | str1 = "hdhsklalahhuueahhsl" 44 | str2 = "jkoorppnnnskkl" 45 | print(remAnagram(str1, str2)) -------------------------------------------------------------------------------- /sample_question.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implement a group_by_owners function that: 3 | 1. Accepts a dictionary containing the file owner name for each file name. 4 | 2. Returns a dictionary containing a list of file names for each owner name, in any order. 5 | 6 | For example, for dictionary {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'} 7 | the group_by_owners function should return {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}. 8 | 9 | """ 10 | ''' 11 | edited by Shouvik Dutta 12 | reason-suppose, we ask to answer if a particular user is able to handle a particular file. 13 | Then we have to iterarte over the return dict. 14 | i.e. if 'Output.txt' in my_dict[i].....tc=>O(n) 15 | otherwise if we use set, tc=>O(1) 16 | if counted needed, 17 | then make defaultdict(int) 18 | ''' 19 | import collections 20 | def group_by_owners(input_dict): 21 | #output_dict = collections.defaultdict(list) 22 | my_dict=collections.defaultdict(set) 23 | for k,v in input_dict.items(): 24 | #output_dict[v].append(k) 25 | my_dict[v].add(k) 26 | return dict(my_dict) 27 | 28 | if __name__ == '__main__': 29 | x = {'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy'} 30 | print (group_by_owners(x)) 31 | -------------------------------------------------------------------------------- /simplAssignment/SQL_Query_PY.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import pandas as pd 3 | import itertools 4 | 5 | with open('C:/Users/cvikas10/Desktop/sampleData.txt','r') as csvFile: 6 | csvReader = csv.reader(csvFile,delimiter=',') 7 | csvData = [row for row in csvReader] 8 | 9 | csvData_df = pd.DataFrame(csvData[1:],columns = csvData[0]) 10 | new = csvData_df['month_year'].str.split('_',n = 1,expand=True) 11 | csvData_df['month'] = new[0] 12 | csvData_df['year'] = new[1] 13 | csvData_df.drop('month_year',axis=1,inplace=True) 14 | 15 | csvData_df['salary'] = csvData_df['salary'].astype(int) 16 | csvData_df['year'] = csvData_df['year'].astype(int) 17 | 18 | #csvData_df.assign(rn=csvData_df.sort_values(['salary'], ascending=False).groupby(['city','employee']).cumcount() + 1).query('rn <= 5').sort_values(['city','employee','rn']) 19 | 20 | cities = list(set(csvData_df['city'])) 21 | years = list(set(csvData_df['year'])) 22 | for p,q in list(itertools.product(cities,years)): 23 | sub_df = csvData_df[(csvData_df['city'] == p) & (csvData_df['year'] == q)] 24 | X = sorted(sub_df['salary'],reverse=True) 25 | if len(X) >= 5: 26 | print (p,q,X[4]) 27 | elif len(X) < 5 and len(X) > 0: 28 | print (p,q,X[len(X)-1]) 29 | elif len(X) == 0: 30 | print (p,q,None) -------------------------------------------------------------------------------- /simplAssignment/sampleData.txt: -------------------------------------------------------------------------------- 1 | employee,month_year,salary,city 2 | Ravi,Jan_2017,45000,Hyderabad 3 | John,Aug_2017,67000,Hyderabad 4 | Jennifer,Dec_2016,80000,Bangalore 5 | James,Jan_2018,80000,Hyderabad 6 | cranston,Mar_2018,73000,Bangalore 7 | bryan,June_2018,21000,Bangalore 8 | Catherine,Nov_2018,35000,Bangalore 9 | Adam,May_2018,100000,Bangalore 10 | Alex,Oct_2017,81000,Hyderabad 11 | Kinston,July_2017,56000,Hyderabad 12 | Morrison,Feb_2017,80000,Hyderabad -------------------------------------------------------------------------------- /simplAssignment/simplAssignemnt.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/absognety/Competitive-Coding-Platforms/004a5768fdf9bbdabe3bf696c15e9e5718922395/simplAssignment/simplAssignemnt.zip -------------------------------------------------------------------------------- /sortedArray_Occurrence-nby2.py: -------------------------------------------------------------------------------- 1 | # Python 3 code to find 2 | # majority element in a 3 | # sorted array 4 | 5 | def findMajority(arr, n): 6 | return arr[int(n/2)] 7 | 8 | # Driver Code 9 | arr = [1, 2, 2, 3] 10 | n = len(arr) 11 | print(findMajority(arr, n)) 12 | 13 | --------------------------------------------------------------------------------