├── 01_Fizz Buzz ├── Editorial │ └── fizzBuzzEditorial.md ├── Ideal Solutions │ ├── fizzBuzz.cpp │ ├── fizzBuzz.java │ └── fizzBuzz.py └── Problem Statement │ └── fizzBuzz.md ├── 02_Check for prime ├── Editorial │ └── checkForPrimeEditorial.md ├── Ideal Solutions │ ├── checkPrime.cpp │ ├── checkPrime.java │ └── checkPrime.py └── Problem Statement │ └── Check for prime.md ├── 03_Binary Representation of a Number ├── Editorial │ └── binaryRepresentationOfANumberEditorial.md ├── Ideal Solutions │ ├── binaryRepresentation.cpp │ ├── binaryRepresentation.java │ └── binaryRepresentation.py └── Problem Statement │ └── Binary Representation of a Number.md ├── 04_Binary Representation to Number ├── Editorial │ └── binaryRepresentationToNumberEditorial.md ├── Ideal Solutions │ ├── binaryToNumber.cpp │ ├── binaryToNumber.java │ └── binaryToNumber.py └── Problem Statement │ └── Binary Representation to Number .md ├── 05_Check for anagram ├── Editorial │ └── checkForAnagramEditorial.md ├── Ideal Solutions │ ├── anagram.py │ ├── checkAnagram.cpp │ └── checkAnagram.java └── Problem Statement │ └── anagram.md ├── 06_Check for palindrome ├── Editorial │ └── detectPalindromeEditorial.md ├── Ideal Solutions │ ├── checkPalindrome.cpp │ ├── checkPalindrome.java │ └── checkPalindrome.py └── Problem Statement │ └── checkForPalindrome.md ├── 07_Power of two ├── Editorial │ └── powerOfTwoEditorial.md ├── Ideal Solutions │ ├── powerOfTwo.cpp │ ├── powerOfTwo.java │ └── powerOfTwo.py └── Problem Statement │ └── powerOfTwo.md ├── 08_Bubble sort ├── Editorial │ └── bubbleSortAlgorithmEditorial.md ├── Ideal Solutions │ ├── bubbleSort.cpp │ ├── bubbleSort.java │ └── bubbleSort.py └── Problem Statement │ └── bubbleSort.md ├── 09_Sort Array Using Quick Sort ├── Editorial │ └── Sort Array Using Quick Sort Editorial.md ├── Ideal Solutions │ ├── quickSort.java │ ├── quickSort.py │ └── sortUsingQuicksort.cpp └── Problem Statement │ └── Sort Using Quick Sort .md ├── 10_Balanced Parenthesis ├── Editorial │ └── balancedParenthesisEditorial.md ├── Ideal Solutions │ ├── balancedParanthesis.java │ ├── balancedParanthesis.py │ └── balancedParenthesis.cpp └── Problem Statement │ └── balancedParenthesis.md ├── 11_Find Duplicates in array ├── Editorial │ └── findDuplicatesEditorial.md ├── Ideal Solutions │ ├── findDuplicatesInArray.cpp │ ├── findDuplicatesInArray.java │ └── findDuplicatesInArray.py └── Problem Statement │ └── findDuplicates.md ├── 12_Infix-Postfix ├── Editorial │ └── infixPostfixEditorial.md ├── Ideal Solutions │ ├── infixPostfix.cpp │ ├── infixPostfix.java │ └── infixPostfix.py └── Problem Statement │ └── infixPostfix.md ├── 13_Min Stack ├── Editorial │ └── minStackEditorial.md ├── Ideal Solutions │ ├── minStack.cpp │ ├── minStack.java │ └── minStack.py └── Problem Statement │ └── Min Stack.md ├── 14_Queue Using Two Stacks ├── Editorial │ └── queueUsingTwoStacksEditorial.md ├── Ideal Solutions │ ├── queueUsingStacks.py │ ├── queueUsingTwoStacks.cpp │ └── queueUsingTwoStacks.java └── Problem Statement │ └── queueUsingTwoStacks.md ├── 15_Stacksusing two Queues ├── Editorial │ └── stackUsingTwoQueuesEditorial.md ├── Ideal Solutions │ ├── stackUsingQueues.py │ ├── stackUsingTwoQueues.cpp │ └── stackUsingTwoQueues.java └── Problem Statement │ └── stackUsingTwoQueues.md ├── 16_Nearest smaller neighbour ├── Editorial │ └── nearestSmallerNeighbourEditorial.md ├── Ideal Solutions │ ├── nearestSmallerNeighbour.cpp │ ├── nearestSmallerNeighbour.java │ └── nearestSmallestNeighbour.py └── Problem Statement │ └── nearestSmallerNeighbour.md ├── 17_Sort An Array of 0's. 1's and 2's ├── Editorial │ └── sortAnArrayOf012Editorial.md ├── Ideal Solutions │ ├── sortAnArrayOf012.cpp │ ├── sortAnArrayOf012.java │ └── sortArray.py └── Problem Statement │ └── sortAnArray.md ├── 18_Matrix rotation ├── Editorial │ └── matrixRotationEditorial.md ├── Ideal Solutions │ ├── matrixRotation.cpp │ ├── matrixRotation.java │ └── matrixRotation.py └── Problem Statement │ └── matrixRotation.md ├── 19_Add Two Linked List ├── Editorial │ └── addTwoLinkedListEditorial.md ├── Ideal Solutions │ ├── addTwoLinkedList.java │ ├── addTwoList.cpp │ └── addTwoList.py └── Problem Statement │ └── addTwoLinkedList.md ├── 20_Reverse a Linked List ├── Editorials │ └── reverseLinkedListEditorial.md ├── Ideal Solutions │ ├── reverseALinkedList.cpp │ ├── reverseLinkedList.java │ └── reverseList.py └── Problem Statement │ └── reverseLinkedList.md ├── 21_Detect Loop in a Linked List ├── Editorial │ └── detectLoopInLinkedListEditorial.md ├── Ideal Solutions │ ├── detectLoop.cpp │ ├── detectLoop.py │ └── detectLoopInLinkedList.java └── Problem Statement │ └── loopInALinkedList.md ├── 22_Palindrome Linked List ├── Editorial │ └── palindromeLinkedListEditorial.md ├── Ideal Solutions │ ├── palindromeLinkedList.cpp │ ├── palindromeLinkedList.java │ └── palindromeList.py └── Problem Statement │ └── plaindromeLinkedList.md ├── 23_Container With Most Water ├── Editorial │ └── containerWithMostWaterEditorial.md ├── Ideal Solutions │ ├── containerWithMostWater.java │ ├── mostWaterContainer.cpp │ └── mostWaterContainer.py └── Problem Statement │ └── containerWithMostWater.md ├── 24_Sliding Window Maximum ├── Editorial │ └── Sliding Window Maximum Editorial.md ├── Ideal Solutions │ ├── slidingWindowMaximum.cpp │ ├── slidingWindowMaximum.java │ └── slidingWindowMaximum.py └── Problem Statement │ └── Sliding Window Maximum.md ├── 25_Two Numbers in Sorted Array whose sum is K ├── Editorial │ └── twoNumbersInSortedArrayEditorial.md ├── Ideal Solutions │ ├── twoNumbersInSortedArraySumK.cpp │ ├── twoSum.java │ └── twoSum.py └── Problem Statement │ └── twoNumbersInSortedArray.md ├── 26_GCD ├── Editorial │ └── gcd Editorial.md ├── Ideal Solutions │ ├── greatestCommonDivisor.cpp │ ├── greatestCommonDivisor.java │ └── greatestCommonDivisor.py └── Problem Statement │ └── gcd.md ├── 27_Nth Fibonacci ├── Editorial │ ├── Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09.md │ └── Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09 │ │ ├── fib_code.png │ │ ├── fib_complexity.png │ │ ├── fibonacci.png │ │ ├── fibonacci2.png │ │ └── fibonacci_eqn.png ├── Ideal Solutions │ ├── nthFibonacci.cpp │ ├── nthFibonacci.java │ └── nthFibonacci.py └── Problem Statement │ └── fibonacci.md ├── 28_Permutations with Largest Sum ├── Editorial │ └── Permutations with Largest Sum Editorial.md ├── Ideal Solutions │ ├── permutationWithLargestSum.cpp │ ├── permutationWithLargestSum.java │ └── permutationWithLargestSum.py └── Problem Statement │ └── Permutation with Largest Sum.md ├── 29_Print All Permutations of an Array ├── Editorial │ └── Print All Permutations of an Array Editorial.md ├── Ideal Solutions │ ├── permutationsOfArray.java │ ├── permutationsOfArray.py │ └── printAllPermutationsOfAnArray.cpp └── Problem Statement │ └── Print all Permutations of an Array.md ├── 30_Print all Subsequences of a String ├── Editorial │ └── Print all Subsequence of a String Editorial.md ├── Ideal Solutions │ ├── allSbsequenceOfString.py │ ├── allSubsequencesOfAString.cpp │ └── allSubsequencesOfAString.java └── Problem Statement │ └── Print all subsequences of a string.md ├── 31_N-Queens ├── Editorial │ └── N-Queens Editorial.md ├── Ideal Solutions │ ├── nQueens.cpp │ ├── nQueens.java │ └── nQueens.py └── Problem Statement │ └── N-Queens.md ├── 32_Binary Search ├── Editorial │ └── Binary Search Editorial.md ├── Ideal Solutions │ ├── binarySearch.cpp │ ├── binarySearch.java │ └── binarySearch.py └── Problem Statement │ └── Binary Search.md ├── 33_Frequency in Sorted Array ├── Editorial │ └── Frequency In Sorted Array - Editorial.md ├── Ideal Solutions │ ├── frequencyInSortedArray.cpp │ ├── frequencyInSortedArray.java │ └── frequencyInSortedArray.py └── Problem Statement │ └── Frequency in Sorted Array .md ├── 34_Find Peak Element ├── Editorial │ └── Find Peak Element - Editorial 5ee64a12eeab48b79536611228629447.md ├── Ideal Solutions │ ├── findPeakElement.cpp │ ├── findPeakElement.java │ └── findPeakElement.py └── Problem Statement │ └── findPeakElement.md ├── 35_Search in Rotated & Sorted Array ├── Editorial │ └── Search in rotated and sorted array - Editorial.md ├── Ideal Solutions │ ├── rotatedSortedArraySearch.py │ ├── searchInRotatedAndSortedArray.cpp │ └── searchInRotatedSortedArray.java └── Problem Statement │ └── searchInRotatedSortedArray.md ├── 36_Minimum in Rotated & Sorted Array ├── Editorial │ └── Minimum in sorted & rotated array - Editorial.md ├── Ideal Solutions │ ├── minRotatedSortedArray.cpp │ ├── minRotatedSortedArray.py │ └── minimumInSorted&RotatedArray.java └── Problem Statement │ └── minimumInSorted&RotatedArray.md ├── 37_Square Root of an Integer ├── Editorial │ └── Square Root of an integer - Editorial.md ├── Ideal Solution │ ├── squareRootOfAnInteger.cpp │ ├── squareRootOfAnInteger.java │ └── squareRootOfInteger'.py └── Problem Statement │ └── Square Root of an Integer.md ├── 38_Painter's Partition Problem ├── Editorial │ └── Painter's Partition Problem - Editorial.md ├── Ideal Solutions │ ├── painterPartition.py │ ├── painterPartitionProblem.cpp │ └── paintersPartitionProblem.java └── Problem Statement │ └── Painter's Partition .md ├── 39_Best Time to Buy and Sell Stock ├── Editorial │ └── bestTimeToBuyAndSellStockEditorial.md ├── Ideal Solutions │ ├── bestTimeToBuySellStock.cpp │ ├── bestTimeToBuySellStock.java │ └── bestTimeToBuySellStock.py └── Problem Statement │ └── bestTimeToBuyAndSellStock.md ├── 40_Gas Stations ├── Editorial │ └── gasStationsEditorial.md ├── Ideal Solutions │ ├── gasStations.cpp │ ├── gasStations.java │ └── gasStations.py └── Problem Statement │ └── Gas Stations.md ├── 41_Meeting Rooms ├── Editorial │ └── meetingRoomsEditorial.md ├── Ideal Solutions │ ├── meetingRooms.cpp │ ├── meetingRooms.java │ └── meetingRooms.py └── Problem Statement │ └── Meeting Rooms.md ├── 42_Longest Common Subsequence ├── Editorial │ └── Longest Common Subsequence 698eeff6d5d24168b2d1bd645ef7cd0f.md ├── Ideal Solutions │ ├── longestCommonSubsequence.cpp │ ├── longestCommonSubsequence.java │ └── longestCommonSubsequence.py └── Problem Statement │ └── longestCommonSubsequence.md ├── 43_Longest Increasing Subsequence ├── Editorial │ ├── Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2.md │ └── Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2 │ │ ├── LISEqn.png │ │ ├── LongestSubTree.jpg │ │ └── includeExclude.jpg ├── Ideal Solutions │ ├── longestIncreasingSubsequence.cpp │ ├── longestIncreasingSubsequence.java │ └── longestIncreasingSubsequence.py └── Problem Statement │ └── longestIncreasingSubsequence.md ├── 44_Longest Palindromic Substring ├── Editorial │ ├── Longest Palindromic Substring 6b2c169974f34e56b43fd31e9c9e43d1.md │ └── Longest Palindromic Substring 6b2c169974f34e56b43fd31e9c9e43d1 │ │ ├── LPS.jpg │ │ ├── Recurrence_relation.jpg │ │ └── base_case.jpg ├── Ideal Solutions │ ├── longestPalindromeSubstring.py │ ├── longestPalindromicSubstring.cpp │ └── longestPalindromicSubstring.java └── Problem Statement │ └── longestPalindromicSubstring.md ├── 45_Minimum Jumps To Reach The End ├── Editorials │ ├── Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a.md │ └── Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a │ │ ├── OptimizeArray.jpg │ │ ├── Org_Chart_(1).jpg │ │ └── timeComplexity.jpg ├── Ideal Solutions │ ├── minJumpsToEnd.cpp │ ├── minJumpsToEnd.py │ └── minJumpsToTheEnd.java └── Problem Statement │ └── minimumJumpsToReachEnd.md ├── 46_Maximum_Sum_Subarray ├── Editorial │ └── maximumSumSubarrayEditorial.md ├── Ideal Solutions │ ├── maximumSumSubArray.py │ ├── maximumSumSubarray.cpp │ └── maximumSumSubarray.java └── Problem Statement │ └── maximumSumSubarray.md ├── 47_Money and Shopping ├── Editorial │ └── Money and Shopping Editorial.md ├── Ideal Solutions │ ├── money&Shopping.java │ ├── moneyAndShopping.cpp │ └── moneyAndShopping.py └── Problem Statement │ └── money&Shopping.md ├── 48_0-1 Knapsack Problem ├── Editorials │ └── 01KnapsackEditorial.md ├── Ideal Solutions │ ├── Editorial │ │ └── 0-1KnapsackEditorial │ ├── Ideal Solutions │ │ ├── zeroOneKnapsack.cpp │ │ ├── zeroOneKnapsack.java │ │ └── zeroOneKnapsack.py │ ├── Problem Statement │ │ └── 0-1KnapsackProblem.md │ ├── zeroOneKnapsack.cpp │ ├── zeroOneKnapsack.java │ └── zeroOneKnapsack.py └── Problem Statement │ └── 01knapsackProblem.md ├── 49_Coin Change Problem ├── Editorial │ ├── Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8.md │ └── Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8 │ │ ├── Psuedo_Code_Coin.png │ │ ├── breaking_CoinChange.png │ │ └── coinChange_recrrence.png ├── Ideal Solutions │ ├── coinChange.cpp │ ├── coinChange.java │ └── coinChange.py └── Problem Statement │ └── coinChange.md ├── 50_Subset Sum Problem ├── Editorial │ ├── Subset Sum Problem 4a45aeb2aaf44038bb7536c833a60e3d.md │ └── Subset Sum Problem 4a45aeb2aaf44038bb7536c833a60e3d │ │ ├── SubsetSumBcktracking.jpg │ │ ├── code1.png │ │ ├── code2.png │ │ ├── recurrence.png │ │ └── ss1.jpg ├── Ideal Solutions │ ├── subsetProblem.py │ ├── subsetSumProblem.cpp │ └── subsetSumProblem.java └── Problem Statement │ └── subsetSumProblem.md ├── 51_Rod Cutting Problem ├── Editorial │ ├── Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504.md │ └── Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504 │ │ ├── RecursionTree_rod.png │ │ ├── Rod_Recursion.jpg │ │ ├── Rods_cut.jpg │ │ ├── loopEqn.png │ │ ├── rod_eqn.png │ │ └── time_rod.png ├── Ideal Solution │ ├── rodCuttingProblem.cpp │ ├── rodCuttingProblem.java │ └── rodCuttingProblem.py └── Problem Statement │ └── rodCuttingProblem.md ├── DSA_Image.png └── README.md /01_Fizz Buzz/Ideal Solutions/fizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void fizzBuzz(int n) { 4 | // Function to implement Fizz Buzz 5 | for (int i = 1; i <= n; i++) { 6 | if (i % 3 == 0 && i % 5 != 0) 7 | cout << "Fizz" << " "; 8 | if (i % 5 == 0 && i % 3 != 0) 9 | cout << "Buzz" << " "; 10 | if (i % 5 == 0 && i % 3 == 0) 11 | cout << "FizzBuzz" << " "; 12 | if (i % 5 != 0 && i % 3 != 0) 13 | cout << i << " "; 14 | } 15 | } 16 | int main() { 17 | int n = 10; 18 | fizzBuzz(n); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /01_Fizz Buzz/Ideal Solutions/fizzBuzz.java: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function prints the elements according to the condition mentioned in the question. 8 | public static void fizzBuzz(int n){ 9 | for (int i=1;i<=n;i++){ 10 | if (i % 3 == 0 && i % 5 == 0) System.out.print("FizzBuzz" + " "); 11 | else if (i % 3 == 0) System.out.print("Fizz" + " "); 12 | else if (i % 5 == 0) System.out.print("Buzz" + " "); 13 | else{ 14 | System.out.print(i + " "); 15 | } 16 | } 17 | } 18 | //Main Function 19 | public static void main(String[] args){ 20 | int n = 10; 21 | fizzBuzz(n); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /01_Fizz Buzz/Ideal Solutions/fizzBuzz.py: -------------------------------------------------------------------------------- 1 | # Print "Fizz" for multiple of 3 and print "Buzz" for multiple of 5 2 | def fizzBuzz(N): 3 | for value in range(1, N + 1): 4 | 5 | # For multiple of 3 ----> Print "Fizz" 6 | if value % 3 == 0: 7 | print("Fizz") 8 | continue 9 | 10 | # For multiple of 5 ----> Print "Buzz" 11 | if value % 5 == 0: 12 | print("Buzz") 13 | continue 14 | 15 | print(value) 16 | 17 | 18 | if __name__ == "__main__": 19 | 20 | # Static Input 21 | N = 7 22 | 23 | fizzBuzz(N) 24 | -------------------------------------------------------------------------------- /01_Fizz Buzz/Problem Statement/fizzBuzz.md: -------------------------------------------------------------------------------- 1 | ## **Fizz Buzz** 2 | Given an integer N. Print the numbers from 1 to N and for multiples of ‘3’ print “Fizz” instead of the number, for the multiples of ‘5’ print “Buzz” and for multiples of both 5 and 3 print "FizzBuzz" 3 | 4 | #### **Sample Input** 5 | input: N = 10 6 | 7 | #### **Sample Output** 8 | Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 9 | 10 | #### **Sample Explanation** 11 | Self explanatory. 12 | 13 | #### **Expected Time Complexity** 14 | __O__(N) 15 | 16 | #### **Expected Space Complexity** 17 | __O__(1), i.e., constant space complexity. 18 | 19 | #### **Constraints** 20 | 1 <= N <= 100000 21 | -------------------------------------------------------------------------------- /02_Check for prime/Ideal Solutions/checkPrime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool checkPrime(int n) { 4 | // Function to check if a number is prime or not 5 | 6 | // Corner Case 7 | if (n <= 1) 8 | return 0; 9 | for (int i = 2; i * i <= n; i++) { 10 | if (n % i == 0) 11 | return false; 12 | } 13 | return true; 14 | } 15 | int main() { 16 | int N = 7; 17 | if (checkPrime(N)) 18 | cout << "Yes" << endl; 19 | else 20 | cout << "No" << endl; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /02_Check for prime/Ideal Solutions/checkPrime.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function checks wether a particular number is prime or not. 8 | public static boolean checkPrime(int n){ 9 | for (int i=2;i<=Math.sqrt(n);i++){ 10 | if (n % i == 0) return false; 11 | } 12 | return true; 13 | } 14 | //Main Function. 15 | public static void main(String[] args){ 16 | int n = 10; 17 | if (checkPrime(n)) System.out.println("Yes"); 18 | else{ 19 | System.out.println("No"); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /02_Check for prime/Ideal Solutions/checkPrime.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | # Cheking Whether the number is prime or not 5 | def checkPrime(Number): 6 | for i in range(2, int(math.sqrt(Number)) + 1): 7 | if Number % i == 0: 8 | return "No" 9 | return "Yes" 10 | 11 | 12 | if __name__ == "__main__": 13 | array = [] 14 | 15 | # Static Input 16 | Number = 7 17 | 18 | print(checkPrime(Number)) 19 | -------------------------------------------------------------------------------- /02_Check for prime/Problem Statement/Check for prime.md: -------------------------------------------------------------------------------- 1 | ## **Check for prime** 2 | Given an integer N. Check whether N is prime or not. 3 | 4 | #### **Sample Input** 5 | input: N = 10 6 | 7 | #### **Sample Output** 8 | Output: No 9 | 10 | #### **Sample Input** 11 | input: N = 7 12 | 13 | #### **Sample Output** 14 | Output: Yes 15 | 16 | #### **Sample Explanation** 17 | Self explanatory. 18 | 19 | #### **Expected Time Complexity** 20 | __O__(sqrt{N}) 21 | 22 | #### **Expected Space Complexity** 23 | __O__(1), i.e., constant space complexity. 24 | 25 | #### **Constraints** 26 | 1 <= N <= 1000000000 27 | -------------------------------------------------------------------------------- /03_Binary Representation of a Number/Ideal Solutions/binaryRepresentation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void binaryRepresentation(int N) { 4 | // Function to print the binary representation of a 32-bit integer 5 | 6 | // For a 32 bit integer bit positions are 0-31 bits 7 | for (int i = 31; i >= 0; i--) { 8 | if (N & (1 << i)) 9 | cout << 1; 10 | else 11 | cout << 0; 12 | } 13 | cout << endl; 14 | } 15 | int main() { 16 | int N; 17 | N = 7; 18 | binaryRepresentation(N); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /03_Binary Representation of a Number/Ideal Solutions/binaryRepresentation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function changes the array into the string. 8 | public static String arrayToString(int[] arr){ 9 | StringBuffer ans = new StringBuffer(); 10 | for(int i=0;i 0){ 19 | int temp = n % 2; 20 | arr[len] = temp; 21 | len--; 22 | n = n/2; 23 | } 24 | String ans = arrayToString(arr); 25 | return ans; 26 | 27 | } 28 | //Main Function 29 | public static void main(String[] args){ 30 | int n = 7; 31 | String ans = binaryRepresentation(n); 32 | System.out.println(ans); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /03_Binary Representation of a Number/Ideal Solutions/binaryRepresentation.py: -------------------------------------------------------------------------------- 1 | 2 | # Convert the number into its Binary Representation 3 | def binaryRepresentation(Number): 4 | 5 | for i in range(31, -1, -1): 6 | if Number & (1 << i): 7 | print("1", end="") 8 | else: 9 | print("0", end="") 10 | 11 | 12 | if __name__ == "__main__": 13 | 14 | # Static Input 15 | N = 7 16 | 17 | binaryRepresentation(N) 18 | -------------------------------------------------------------------------------- /03_Binary Representation of a Number/Problem Statement/Binary Representation of a Number.md: -------------------------------------------------------------------------------- 1 | ## **Binary Representation of a Number** 2 | Write a program to print Binary representation of a given number. 3 | 4 | 5 | #### **Sample Input** 6 | N = 7 7 | 8 | #### **Sample Output** 9 | 00000000000000000000000000000111 10 | #### **Sample Explanation** 11 | Self Explanatory 12 | #### **Expected Time Complexity** 13 | __O__(1), constant time complexity 14 | #### **Expected Space Complexity** 15 | __O__(1), constant space complexity 16 | 17 | #### **Constraints** 18 | 0<= N <= (2^32)-1 19 | 20 | -------------------------------------------------------------------------------- /04_Binary Representation to Number/Ideal Solutions/binaryToNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binaryToNumber(string str) 5 | { 6 | // Function to convert binary to decimal 7 | int number = 0, base = 1, len = str.length(); 8 | for (int i = len - 1; i >= 0; i--) { 9 | if (str[i] == '1') 10 | number += base; 11 | base = base * 2; 12 | } 13 | return number; 14 | } 15 | 16 | int main() { 17 | string num = "00000000000000000000000000000111"; // Binary Representation of a Number 18 | cout << binaryToNumber(num) << endl; 19 | } 20 | -------------------------------------------------------------------------------- /04_Binary Representation to Number/Ideal Solutions/binaryToNumber.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function converts string to array. 8 | public static int[] stringToArray(String a){ 9 | int[] arr = new int[a.length()]; 10 | for (int i=0;i=0;i--){ 20 | if (arr[i] == 1){ 21 | value += (int)Math.pow(2,j); 22 | } 23 | j++; 24 | } 25 | return value; 26 | } 27 | //Main function 28 | public static void main(String[] args){ 29 | String a = "00000000000000000000000000000111"; 30 | int[] arr = stringToArray(a); 31 | int value = binaryToNumber(arr); 32 | System.out.println(value); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /04_Binary Representation to Number/Ideal Solutions/binaryToNumber.py: -------------------------------------------------------------------------------- 1 | 2 | # Convert binary to number 3 | def binaryToNumber(nums): 4 | 5 | number = 0 6 | base = 1 7 | size = len(nums) 8 | 9 | for i in range(size-1, -1, -1): 10 | if nums[i] == '1': 11 | number += base 12 | base = base*2 13 | 14 | return number 15 | 16 | 17 | if __name__ == "__main__": 18 | 19 | # Static Input 20 | nums = "00000000000000000000000000111" 21 | 22 | print(binaryToNumber(nums)) 23 | -------------------------------------------------------------------------------- /04_Binary Representation to Number/Problem Statement/Binary Representation to Number .md: -------------------------------------------------------------------------------- 1 | ## **Binary Representation to Number** 2 | Given a binary string, output the integer so formed. 3 | 4 | __Note__: Output the number so formed after converting the binary representation to the Integer 5 | 6 | #### **Sample Input** 7 | 00000000000000000000000000000111 8 | #### **Sample Output** 9 | 7 10 | #### **Sample Explanation** 11 | Self Explanatory 12 | #### **Expected Time Complexity** 13 | __O__(1), constant time complexity 14 | #### **Expected Space Complexity** 15 | __O__(1), constant space complexity 16 | 17 | #### **Constraints** 18 | 1<= length of binary string <= 32 19 | 20 | -------------------------------------------------------------------------------- /05_Check for anagram/Ideal Solutions/anagram.py: -------------------------------------------------------------------------------- 1 | # Given Two Strings, Check whether they are anagrams of each other 2 | def checkAnagram(X, Y): 3 | # If length of String X not equal to length of String Y, then Two strings must not be a anagram 4 | if len(X) != len(Y): 5 | return False 6 | 7 | # Saving the char count in a Dictionary of String X 8 | countX = dict() 9 | for char in X: 10 | try: 11 | countX[char] += 1 12 | except: 13 | countX[char] = 1 14 | 15 | # Saving the char count in a Dictionary of String Y 16 | countY = dict() 17 | for char in Y: 18 | try: 19 | countY[char] += 1 20 | except: 21 | countY[char] = 1 22 | 23 | # Comparing Char count of String X and Y 24 | for char in countX: 25 | try: 26 | if countX[char] != countY[char]: 27 | return False 28 | except: 29 | return False 30 | 31 | return True 32 | 33 | 34 | if __name__ == "__main__": 35 | 36 | # Input 37 | X = "abcd" 38 | Y = "dacb" 39 | 40 | print(checkAnagram(X, Y)) 41 | -------------------------------------------------------------------------------- /05_Check for anagram/Ideal Solutions/checkAnagram.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool checkAnagram(string x, string y, int n, int m) { 4 | // Function to check if two strings are anagram or not 5 | 6 | // Using two arrays of contant size to count the frequency of each character present in the string. 7 | int freq1[27], freq2[27]; 8 | memset(freq1, 0, sizeof(freq1)); // Setting initial values in the freq1 array to be 0 9 | memset(freq2, 0, sizeof(freq2)); // Setting initial values in the freq2 array to be 0 10 | for (int i = 0; i < n; i++) 11 | { 12 | int c = (int)x[i] - 96; 13 | freq1[c]++; 14 | } 15 | for (int i = 0; i < m; i++) 16 | { 17 | int c = (int)y[i] - 96; 18 | freq2[c]++; 19 | } 20 | 21 | // Checking if the frequency of each character is same or not 22 | for (int i = 1; i <= 26; i++) 23 | if (freq1[i] != freq2[i]) 24 | return false; 25 | return true; 26 | } 27 | int main() { 28 | int N = 4, M = 4; // Length of the strings 29 | string X = "abcd"; 30 | string Y = "dacb"; 31 | if (checkAnagram(X, Y, N, M)) 32 | cout << "Yes" << endl; 33 | else 34 | cout << "No" << endl; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /05_Check for anagram/Ideal Solutions/checkAnagram.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | 6 | 7 | class Main{ 8 | //This function checks if the two arrays are equal or not. 9 | public static boolean equalArrays(char[] arr1, char[] arr2){ 10 | if (arr1.length != arr2.length) return false; 11 | for (int i=0;i 2 | using namespace std; 3 | bool checkPalindrome(string x, int n) { 4 | // Function to check if the string is palindrome or not 5 | int i = 0, j = n - 1; 6 | while (i < j) 7 | { 8 | if (x[i] != x[j]) 9 | return false; 10 | i++; 11 | j--; 12 | } 13 | return true; 14 | } 15 | int main() { 16 | int N = 9; // Length of the string 17 | string X = "malayalam"; 18 | if (checkPalindrome(X, N)) 19 | cout << "Yes" << endl; 20 | else 21 | cout << "No" << endl; 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /06_Check for palindrome/Ideal Solutions/checkPalindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | 6 | 7 | class Main{ 8 | //This function checks if the given string is a palindrome or not. 9 | public static boolean checkPalindrome(String a){ 10 | int left = 0; 11 | int right = a.length()-1; 12 | while(left <= right){ 13 | if (a.charAt(left) != a.charAt(right)) return false; 14 | left++; 15 | right--; 16 | } 17 | return true; 18 | } 19 | //Main Function 20 | public static void main(String[] args){ 21 | int n = 9; 22 | String a = "malayalam"; 23 | if (checkPalindrome(a)) System.out.println("Yes"); 24 | else{ 25 | System.out.println("No"); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /06_Check for palindrome/Ideal Solutions/checkPalindrome.py: -------------------------------------------------------------------------------- 1 | # Function that checks whether input string is palindrome or not 2 | def checkPalindrome(inputString): 3 | midLength = int(len(inputString) / 2) # Finds Mid Length Of String 4 | totalLength = int(len(inputString)) # Total Length of String 5 | 6 | # Compares Beginning Characters with the last characters, Till middle Length 7 | for index in range(0, midLength): 8 | if inputString[index] != inputString[totalLength - index - 1]: 9 | return False 10 | 11 | return True # If All characters Matches , Return True 12 | 13 | 14 | if __name__ == "__main__": 15 | 16 | # Static Input : 17 | inputString = "madam" 18 | 19 | if checkPalindrome(inputString): 20 | print("Yes") 21 | else: 22 | print("No") 23 | -------------------------------------------------------------------------------- /06_Check for palindrome/Problem Statement/checkForPalindrome.md: -------------------------------------------------------------------------------- 1 | ## **Check for palindrome** 2 | Given a string of length N. Check if the given string is a palindrome without using any built-in functionality. 3 | 4 | #### **Sample Input** 5 | input: N = 9, string: malayalam 6 | 7 | #### **Sample Output** 8 | Output: Yes 9 | 10 | #### **Sample Input** 11 | input: N = 5, string: masai 12 | 13 | #### **Sample Output** 14 | Output: No 15 | 16 | #### **Sample Explanation** 17 | Self explanatory. 18 | 19 | #### **Expected Time Complexity** 20 | __O__(N), where N is the size of the string 21 | 22 | #### **Expected Space Complexity** 23 | __O__(1), i.e., constant space complexity. 24 | 25 | #### **Constraints** 26 | 1 <= N <= 100000 27 | -------------------------------------------------------------------------------- /07_Power of two/Ideal Solutions/powerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to check if N is power of 2 5 | 6 | bool isPowerOfTwo(int N){ 7 | 8 | // Repeated division by 2 9 | 10 | while( N%2 == 0) 11 | N/= 2; 12 | 13 | 14 | if(N == 1) 15 | return true; 16 | 17 | else 18 | return false; 19 | 20 | 21 | } 22 | 23 | 24 | int main(){ 25 | 26 | int N = 4; 27 | 28 | if( isPowerOfTwo(N) ) 29 | cout<<"Yes"<<"\n"; 30 | 31 | else 32 | cout<<"No"<<"\n"; 33 | 34 | return 0; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /07_Power of two/Ideal Solutions/powerOfTwo.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function finds out if the given number is a power of two or not. 8 | public static boolean powerOfTwo(int n){ 9 | int count = 0; 10 | while(n > 0){ 11 | if (n % 2 == 1) count++; 12 | n = n/2; 13 | } 14 | return count == 1; 15 | } 16 | //Main Function 17 | public static void main(String[] args){ 18 | int n = 4; 19 | if (powerOfTwo(n)) System.out.println("Yes"); 20 | else{ 21 | System.out.println("No"); 22 | } 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /07_Power of two/Ideal Solutions/powerOfTwo.py: -------------------------------------------------------------------------------- 1 | 2 | # Checking whether the number is power of 2 or not 3 | def powerOfTwo(Number): 4 | if Number == 0: 5 | return False 6 | 7 | while Number != 1: 8 | if Number % 2 != 0: 9 | return "No" 10 | Number = Number // 2 11 | 12 | return "Yes" 13 | 14 | 15 | if __name__ == "__main__": 16 | 17 | # Static Input 18 | N = 4 19 | 20 | print(powerOfTwo(N)) 21 | -------------------------------------------------------------------------------- /07_Power of two/Problem Statement/powerOfTwo.md: -------------------------------------------------------------------------------- 1 | ## **Power of 2** 2 | Given a positive integer N. Check if it is a power of two or not. 3 | 4 | #### **Sample Input** 5 | input: N = 4 6 | 7 | #### **Sample Output** 8 | Output: Yes 9 | 10 | 11 | #### **Sample Explanation** 12 | 4 can be represented as 2*2. Hence it's prime factorisation includes no prime except 2. Hence it can be represented as a power of 2. 13 | 14 | #### **Expected Time Complexity** 15 | __O__(log(N)), where N is the positive integer. 16 | 17 | #### **Expected Space Complexity** 18 | __O__(1), i.e., constant space complexity. 19 | 20 | #### **Constraints** 21 | 1 <= N <= 10000000000000 22 | -------------------------------------------------------------------------------- /08_Bubble sort/Ideal Solutions/bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void bubbleSort(int arr[], int n) 4 | { 5 | // A function to implement bubble sort 6 | for (int i = 0; i < n - 1; i++) { 7 | 8 | for (int j = 0; j < n - i - 1; j++) { 9 | if (arr[j] > arr[j + 1]) 10 | swap(arr[j], arr[j + 1]); 11 | } 12 | } 13 | 14 | // Printing the sorted array 15 | for (int i = 0; i < n; i++) 16 | cout << arr[i] << " "; 17 | cout << endl; 18 | } 19 | int main() { 20 | int n = 5; 21 | int arr[] = {5, 1, 6, 3, 7}; 22 | bubbleSort(arr, n); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /08_Bubble sort/Ideal Solutions/bubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | class bubbleSort{ 6 | //This function swaps two elements in the array. 7 | public static void swap(int[] arr,int i,int j){ 8 | int temp = arr[i]; 9 | arr[i] = arr[j]; 10 | arr[j] = temp; 11 | } 12 | //This function implements bubble sort. 13 | public static int[] bubbleSort(int[] arr,int n){ 14 | for (int i=0;i arr[j+1]){ 18 | swap(arr,j,j+1); 19 | count++; 20 | } 21 | } 22 | if (count == 0){ 23 | return arr; 24 | } 25 | } 26 | return arr; 27 | } 28 | //Main Function 29 | public static void main(String[] args){ 30 | int n = 5; 31 | int[] arr = {5,1,6,3,7}; 32 | bubbleSort(arr,n); 33 | for (Integer i : arr) System.out.print(i + " "); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /08_Bubble sort/Ideal Solutions/bubbleSort.py: -------------------------------------------------------------------------------- 1 | 2 | # Swap the elements of array present in first and second location. 3 | def swap(arr, first, second): 4 | arr[first], arr[second] = arr[second], arr[first] 5 | 6 | 7 | 8 | 9 | # Bubble Sort Function which will sort the given input array of length N. 10 | def bubbleSort(arr, N): 11 | 12 | for i in range(N-1): 13 | for j in range(0, N-i-1): 14 | 15 | # If adjacent elements are not in increasing order, Then swap the elements 16 | if arr[j] > arr[j+1]: 17 | swap(arr, j, j+1) 18 | 19 | 20 | 21 | # MAIN FUNCTION 22 | if __name__ == "__main__": 23 | 24 | # Inputs 25 | N = 5 26 | arr = [5, 1, 6, 3, 7] 27 | 28 | bubbleSort(arr, N) 29 | 30 | # Printing Elements of array 31 | print(arr) 32 | 33 | 34 | -------------------------------------------------------------------------------- /08_Bubble sort/Problem Statement/bubbleSort.md: -------------------------------------------------------------------------------- 1 | ## **Bubble sort** 2 | Given an array A having N positive integers. Sort the array A using bubble sort. 3 | 4 | #### **Sample Input** 5 | input: N = 5 6 | A : 5 1 6 3 7 7 | 8 | #### **Sample Output** 9 | A: 1 3 5 6 7 10 | 11 | #### **Sample Explanation** 12 | Self explanatory. 13 | 14 | #### **Expected Time Complexity** 15 | __O__(N*N) 16 | 17 | #### **Expected Space Complexity** 18 | __O__(1), i.e., constant space complexity. 19 | 20 | #### **Constraints** 21 | 1 <= N <= 1000 22 | -------------------------------------------------------------------------------- /09_Sort Array Using Quick Sort/Ideal Solutions/quickSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main{ 6 | //This is the partition function of quick sort 7 | static int partition(int[] arr, int low, int high){ 8 | int p_index=low; 9 | int pivot = arr[high]; 10 | for(int i=low; i 2 | using namespace std; 3 | 4 | // Function for partition 5 | 6 | int partition (int arr[], int lo, int hi){ 7 | 8 | int pivot = arr[hi]; // pivot 9 | 10 | int idx = (lo - 1); // Index of smaller element and indicates the right position of pivot found so far 11 | 12 | for (int j = lo; j <= hi - 1; j++){ 13 | 14 | // If current element is smaller than the pivot 15 | if (arr[j] < pivot) 16 | { 17 | idx++; // increment index of smaller element 18 | 19 | swap(arr[idx], arr[j]); 20 | } 21 | } 22 | swap(arr[idx + 1], arr[hi]); 23 | 24 | return (idx + 1); 25 | } 26 | 27 | // Function for quick sort 28 | 29 | void quickSort(int arr[], int lo, int hi){ 30 | 31 | if ( lo < hi ){ 32 | 33 | // partitioning index 34 | 35 | int pi = partition(arr, lo, hi); 36 | 37 | // sort all elements before partition index 38 | quickSort(arr, lo, pi - 1); 39 | 40 | //sort all elements after partition index 41 | quickSort(arr, pi + 1, hi); 42 | 43 | } 44 | } 45 | 46 | int main(){ 47 | 48 | int N = 6; 49 | 50 | int arr[] = {2, 6, 3, 0, 4, 1}; 51 | 52 | quickSort(arr, 0, N - 1); 53 | 54 | for(int i = 0; i < N ; i++) 55 | cout< map = new HashMap<>(); 9 | map.put('(',')'); 10 | map.put('[',']'); 11 | map.put('{','}'); 12 | Stack stack = new Stack<>(); 13 | for (int i=0;i 2 | using namespace std; 3 | int findDuplicateInArray(int arr[], int n) { 4 | // Function to find the number which is present more than once in the array 5 | int sum = 0; 6 | for (int i = 0; i < n; i++) { 7 | sum += arr[i]; 8 | } 9 | int N = n - 1; 10 | int value = (N * (N + 1)) / 2; // Formula to find sum of natural numbers upto N 11 | return abs(value - sum); 12 | } 13 | int main() { 14 | int n = 5; // Size of the array 15 | int arr[] = {1, 3, 3, 2, 4}; 16 | cout << findDuplicateInArray(arr, n) << endl; 17 | return 0; 18 | } -------------------------------------------------------------------------------- /11_Find Duplicates in array/Ideal Solutions/findDuplicatesInArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main{ 6 | //This function returns the sum of first N natural numbers. 7 | public static int sumOfNaturalNumbers(int N){ 8 | int sum = N * (N + 1); 9 | return sum/2; 10 | } 11 | //This function finds out the duplicate element in the array 12 | public static int findDuplicatesInArray(int[] arr,int n){ 13 | int S1 = 0; 14 | for (int i=0;i0, then make it negative for tracking 20 | else: 21 | array[value-1] = array[value-1] * -1 22 | 23 | print(result) 24 | 25 | 26 | 27 | if __name__ == "__main__": 28 | 29 | array = [] 30 | 31 | # 1. Dynamic Input 32 | # N = int(input("Enter the size of array : ")) 33 | # for i in range(0, N): 34 | # ele = int(input()) 35 | # array.append(ele) 36 | 37 | # 2. Static Input : 38 | array = [1, 2, 3, 6, 3, 6, 1] 39 | N = 7 40 | 41 | findDuplicatesInArray(array, N) 42 | -------------------------------------------------------------------------------- /11_Find Duplicates in array/Problem Statement/findDuplicates.md: -------------------------------------------------------------------------------- 1 | ## **FIND DUPLICATE IN AN ARRAY** 2 | Given an array A of N elements that contains elements from 1 to N-1. All elements occur once except one which occurs twice. Find the repeating element. 3 | 4 | #### **Sample Input** 5 | N = 5, A = [1, 3, 3, 2, 4]. 6 | 7 | #### **Sample Output** 8 | Output: 3 9 | 10 | #### **Sample Explanation** 11 | Element 3 appears twice in the array. Hence it is the only repeating element. 12 | 13 | ## **Expected Time Complexity** 14 | __O__(N), where N is the size of the array 15 | 16 | ## **Expected Space Complexity** 17 | __O__(1), i.e., constant space complexity. 18 | 19 | ## **Constraints** 20 | 1 <= N <= 100000 21 | 22 | -------------------------------------------------------------------------------- /12_Infix-Postfix/Ideal Solutions/infixPostfix.py: -------------------------------------------------------------------------------- 1 | OPERATORS = ['+', '-', '*', '/', '(', ')', '^'] 2 | PRIORITY = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} 3 | 4 | # Convert Infix Expression to Postfix Expression 5 | def infixPostfix(expression): 6 | stack = [] 7 | result = '' 8 | 9 | for ch in expression: 10 | if ch not in OPERATORS: 11 | result += ch 12 | elif ch == '(': 13 | stack.append('(') 14 | elif ch == ')': 15 | while stack and stack[-1] != '(': 16 | result += stack.pop() 17 | else: 18 | while stack and stack[-1] != '(' and PRIORITY[ch] <= PRIORITY[stack[-1]]: 19 | result += stack.pop() 20 | stack.append(ch) 21 | 22 | while stack: 23 | result += stack.pop() 24 | 25 | return result 26 | 27 | 28 | if __name__ == "__main__": 29 | 30 | # Input 31 | array = [1, 2, 1, 3, 5, 6, 4] 32 | N = 10 33 | M = 6 34 | 35 | expression = "a+b-c+d*(e-f)/g+(h*(i/j))" 36 | print(infixPostfix(expression)) 37 | -------------------------------------------------------------------------------- /12_Infix-Postfix/Problem Statement/infixPostfix.md: -------------------------------------------------------------------------------- 1 | ## **Infix Postfix** 2 | Infix Expression- Operators are written in-between their operands. This is the usual way we write expressions. 3 | 4 | Example- a+b-c 5 | 6 | Postfix Expression- If the operator appears in the expression after the operands. 7 | 8 | Example- Postfix of the above expression would be ab+c- 9 | 10 | The compiler scans the expression either from left to right or from right to left. 11 | 12 | Consider the below expression: a + b * c + d 13 | 14 | The compiler first scans the expression to evaluate the expression b * c, then again scan the expression to add a to it. The result is then added to d after another scan. 15 | 16 | The repeated scanning makes it very in-efficient. It is better to convert the expression to postfix(or prefix) form before evaluation. 17 | 18 | The postfix expression of this would be- abc * + d+ 19 | 20 | This expression is much easy to evaluate than its infix counterpart. 21 | 22 | **Remember** Brackets too can be used in the input and postfix notation doesn't have brackets. 23 | 24 | 25 | 26 | 27 | #### **Sample Input** 28 | a+b-c+d*(e-f)/g+(h*(i/j)) 29 | 30 | 31 | 32 | #### **Sample Output** 33 | ab+c-def-*g/+hij/*+ 34 | 35 | #### **Sample Explanation** 36 | The postfix expression for the expression given in the sample input is given by the ouptut. 37 | 38 | #### **Expected Time Complexity** 39 | __O__(N^2), where N is the size of the expression. 40 | 41 | #### **Expected Space Complexity** 42 | __O__(M), where M is the number of operators in string. 43 | 44 | #### **Constraints** 45 | Number of operands <= 26 46 | -------------------------------------------------------------------------------- /13_Min Stack/Ideal Solutions/minStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class MinStack { 4 | public: 5 | int arr[100010], minimum[100010]; 6 | int cur, mincur; 7 | MinStack() { 8 | cur = -1; 9 | mincur = -1; 10 | } 11 | 12 | void push(int x) { 13 | if (mincur == -1 || x <= minimum[mincur]) 14 | { 15 | mincur++; 16 | minimum[mincur] = x; 17 | } 18 | cur++; 19 | arr[cur] = x; 20 | } 21 | 22 | void pop() { 23 | //assert(cur<=1234567); 24 | if (cur == -1) 25 | return; 26 | if (arr[cur] == minimum[mincur]) 27 | mincur--; 28 | cur--; 29 | } 30 | 31 | int top() { 32 | if (cur == -1) 33 | return -1; 34 | return arr[cur]; 35 | } 36 | 37 | int getMin() { 38 | if (mincur == -1) 39 | return -1; 40 | return minimum[mincur]; 41 | } 42 | }; 43 | // Driver Code 44 | int main() 45 | { 46 | MinStack st; 47 | st.push(3); 48 | st.push(5); 49 | st.push(1); 50 | cout << st.getMin() << endl; 51 | st.pop(); 52 | cout << st.getMin() << endl; 53 | return 0; 54 | } -------------------------------------------------------------------------------- /13_Min Stack/Ideal Solutions/minStack.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | //This class implements the minstack functionality, using two stacks. 7 | class MinStack{ 8 | Stack stack; 9 | Stack minstack; 10 | int min = Integer.MAX_VALUE; 11 | public MinStack(){ 12 | stack = new Stack<>(); 13 | minstack = new Stack<>(); 14 | } 15 | 16 | public void push(int x){ 17 | stack.push(x); 18 | if (x <= min){ 19 | min = x; 20 | minstack.push(x); 21 | } 22 | } 23 | public void pop(){ 24 | if(!stack.isEmpty()){ 25 | int temp = stack.pop(); 26 | if (temp == min){ 27 | minstack.pop(); 28 | } 29 | if (minstack.isEmpty()){ 30 | min = Integer.MAX_VALUE; 31 | }else{ 32 | min = minstack.peek(); 33 | } 34 | } 35 | } 36 | public int getMin(){ 37 | if (!stack.isEmpty()) return min; 38 | return -1; //If the stack is empty. 39 | } 40 | public int top(){ 41 | if (!stack.isEmpty()) return stack.peek(); 42 | return -1; //If the stack is empty. 43 | } 44 | } 45 | 46 | class Main{ 47 | //Main Function 48 | public static void main(String[] args){ 49 | MinStack object = new MinStack(); 50 | object.push(3); 51 | object.push(5); 52 | object.push(1); 53 | System.out.println(object.getMin()); 54 | object.pop(); 55 | System.out.println(object.getMin()); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /13_Min Stack/Ideal Solutions/minStack.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class MinStack: 4 | 5 | # Intialiazing the data structure 6 | def __init__(self): 7 | self.myList = [] 8 | self.min = math.inf 9 | 10 | # Pushing the element into stack 11 | def push(self, x: int) -> None: 12 | self.myList.append(x) 13 | if x < self.min: 14 | self.min = x 15 | 16 | # Popping the element from the stack 17 | def pop(self)->None: 18 | self.myList.pop() 19 | 20 | if self.myList: 21 | self.min = min(self.myList) 22 | else: 23 | self.min = math.inf 24 | 25 | # Getting the top element from the stack 26 | def top(self) -> int: 27 | return self.myList[-1] 28 | 29 | # Getting the minimum value from the stack 30 | def getMin(self) -> int: 31 | return self.min 32 | 33 | 34 | if __name__ == "__main__": 35 | 36 | # Creating Object 37 | element = MinStack() 38 | 39 | # Successive Stack operations 40 | element.push(2) 41 | element.push(6) 42 | element.push(1) 43 | element.push(8) 44 | element.pop() 45 | 46 | print(element.getMin()) 47 | -------------------------------------------------------------------------------- /13_Min Stack/Problem Statement/Min Stack.md: -------------------------------------------------------------------------------- 1 | ## **Min Stack in O(1)** 2 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant O(1) time. 3 | 4 | __Note__ : You need to implement these functions on the stack : 5 | push(x) — Push element x into the stack. 6 | pop() — Removes the element from top of the stack. 7 | top() — Get the top element. 8 | getMin() — Retrieve the minimum element in the stack in O(1) time 9 | 10 | #### **Sample Input** 11 | push(3) 12 | push(5) 13 | push(1) 14 | getMin() 15 | pop() 16 | getMin() 17 | #### **Sample Output** 18 | Output: 19 | 1 20 | 3 21 | #### **Sample Explanation** 22 | Stack = [3,5,1] 23 | getMin() -> 1 24 | After pop 25 | Stack = [3,5] 26 | getMin() -> 3 27 | #### **Expected Time Complexity** 28 | __O__(1), for each operation 29 | #### **Expected Space Complexity** 30 | __O__(1), Constant extra space 31 | 32 | #### **Constraints** 33 | 1 <= N <= 100000 34 | -------------------------------------------------------------------------------- /14_Queue Using Two Stacks/Ideal Solutions/queueUsingStacks.py: -------------------------------------------------------------------------------- 1 | # Queue using Stacks 2 | 3 | class Queue: 4 | 5 | # Intialization 6 | def __init__(self): 7 | self.stack1 = [] 8 | self.stack2 = [] 9 | 10 | # Enqueue in queue : Move All Elements of Stack 1 to Stack 2 11 | def enqueue(self, element): 12 | 13 | while len(self.stack1) != 0: 14 | self.stack2.append(self.stack1[-1]) 15 | self.stack1.pop() 16 | 17 | self.stack1.append(element) 18 | 19 | while len(self.stack2) != 0: 20 | self.stack1.append(self.stack2[-1]) 21 | self.stack2.pop() 22 | 23 | # Dequeue item from queue 24 | def dequeue(self): 25 | 26 | if len(self.stack1) == 0: 27 | print("Queue is empty") 28 | 29 | element = self.stack1[-1] 30 | self.stack1.pop() 31 | return element 32 | 33 | 34 | if __name__ == "__main__": 35 | # Intialiaze 36 | q = Queue() 37 | 38 | q.enqueue(7) 39 | q.enqueue(8) 40 | q.enqueue(9) 41 | q.enqueue(10) 42 | 43 | print(q.dequeue()) 44 | print(q.dequeue()) 45 | -------------------------------------------------------------------------------- /14_Queue Using Two Stacks/Ideal Solutions/queueUsingTwoStacks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Queue { 5 | 6 | stack s1, s2; 7 | 8 | public: 9 | // Enqueue an item to the queue 10 | void enQueue(int x){ 11 | 12 | // Push into stack S1 13 | this->s1.push(x); 14 | } 15 | 16 | // Dequeue an item from the queue 17 | int deQueue(){ 18 | 19 | 20 | // if s2 is empty, then pop all elements of s1 and 21 | // push them to s2 in the order they are popped 22 | 23 | if (s2.empty()) { 24 | while (!s1.empty()) { 25 | this->s2.push(s1.top()); 26 | this->s1.pop(); 27 | } 28 | } 29 | 30 | // Top of S2 is the required front of the queue 31 | 32 | int X = this->s2.top(); 33 | this->s2.pop(); 34 | return X; 35 | } 36 | }; 37 | 38 | 39 | int main(){ 40 | 41 | Queue q; 42 | 43 | int queries; 44 | cin>>queries; 45 | 46 | while(queries--){ 47 | int type; 48 | cin>>type; 49 | 50 | if(type == 1){ 51 | int X; 52 | cin>>X; 53 | q.enQueue(X); 54 | } 55 | 56 | else{ 57 | cout< s1 = new Stack(); 9 | Stack s2 = new Stack(); 10 | 11 | private void enqueue(int x){ 12 | while (!s1.isEmpty()){ 13 | s2.push(s1.pop()); 14 | //s1.pop(); 15 | } 16 | s1.push(x); 17 | while (!s2.isEmpty()){ 18 | s1.push(s2.pop()); 19 | //s2.pop(); 20 | } 21 | } 22 | private int dequeue(){ 23 | if (s1.isEmpty()){ 24 | System.out.println("Queue is Empty"); 25 | System.exit(0); 26 | } 27 | int x = s1.peek(); 28 | s1.pop(); 29 | return x; 30 | } 31 | } 32 | //Main Function 33 | public static void main(String[] args){ 34 | int n = 5; 35 | int[] arr = {1,2,1,3,2,1,4,2}; 36 | Queue queue = new Queue(); 37 | for (int i=0;i 2 | using namespace std; 3 | 4 | // Class for stack implementation 5 | 6 | class Stack { 7 | queue q1, q2; 8 | int N; // Size of the stack 9 | 10 | public: 11 | 12 | Stack(){ 13 | 14 | this->N = 0; 15 | } 16 | 17 | int pop(){ 18 | 19 | // Dequeue all elements of q1 except the last and 20 | // Enqueue them to q2. 21 | 22 | while (q1.size() != 1) { 23 | this->q2.push(this->q1.front()); 24 | this->q1.pop(); 25 | } 26 | 27 | // Front of q1 is the top of stack; 28 | int top = this->q1.front(); 29 | this->q1.pop(); 30 | this->N--; 31 | 32 | // swap the names of two queues 33 | queue q = this->q1; 34 | this->q1 = this->q2; 35 | this->q2 = q; 36 | 37 | return top; 38 | } 39 | 40 | void push(int X){ 41 | 42 | this->q1.push(X); 43 | this->N++; 44 | } 45 | 46 | 47 | }; 48 | 49 | int main(){ 50 | 51 | Stack s; 52 | s.push(2); 53 | s.push(3); 54 | cout< q1 = new LinkedList(); 10 | static Queue q2 = new LinkedList(); 11 | static int curr_size; 12 | 13 | Stack(){ 14 | curr_size = 0; 15 | } 16 | 17 | static void push(int x){ 18 | curr_size++; 19 | q2.add(x); 20 | while (!q1.isEmpty()) { 21 | q2.add(q1.peek()); 22 | q1.remove(); 23 | } 24 | Queue q = q1; 25 | q1 = q2; 26 | q2 = q; 27 | } 28 | static int pop(){ 29 | if (q1.isEmpty()) 30 | return -1; 31 | int ans =q1.peek(); 32 | q1.remove(); 33 | curr_size--; 34 | return ans; 35 | } 36 | static int top(){ 37 | if (q1.isEmpty()) return -1; 38 | return q1.peek(); 39 | } 40 | 41 | static int size(){ 42 | return curr_size; 43 | } 44 | } 45 | 46 | //Main Function 47 | public static void main(String[] args){ 48 | Stack stack = new Stack(); 49 | stack.push(2); 50 | stack.push(3); 51 | System.out.println(stack.pop()); 52 | stack.push(4); 53 | System.out.println(stack.pop()); 54 | System.out.println(stack.top()); 55 | System.out.println(stack.size()); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /15_Stacksusing two Queues/Problem Statement/stackUsingTwoQueues.md: -------------------------------------------------------------------------------- 1 | ## **Stack Using Two Queues** 2 | 3 | Implement a Stack using two queues q1 and q2 such that the stack supports two operations push() and pop() 4 | 5 | 6 | #### **Sample Input** 7 | push(2) 8 | push(3) 9 | pop() 10 | push(4) 11 | pop() 12 | 13 | 14 | 15 | #### **Sample Output** 16 | 3 4 17 | 18 | #### **Sample Explanation** 19 | push(2) the stack will be {2} 20 | push(3) the stack will be {2 3} 21 | pop() poped element will be 3 the stack will be {2} 22 | push(4) the stack will be {2 4} 23 | pop() poped element will be 4 24 | 25 | #### **Expected Time Complexity** 26 | __O__(1) for push() and __O__(N) for pop() (or vice-versa). 27 | #### **Expected Space Complexity** 28 | __O__(N), auxilliary Space required for storing data in queues. 29 | 30 | #### **Constraints** 31 | 1 <= Number of operations on the stack <= 100 32 | 1 <= Values in the stack <= 100 33 | 34 | 35 | -------------------------------------------------------------------------------- /16_Nearest smaller neighbour/Ideal Solutions/nearestSmallerNeighbour.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to calculate nearest smaller neighbour for all array elements 5 | 6 | void nearestSmallerNeighbour(int arr[], int N){ 7 | 8 | stack S; 9 | 10 | for (int i=0; i= arr[i]) 15 | S.pop(); 16 | 17 | // condition for empty stack 18 | if (S.empty()) 19 | cout <<-1<<" "; 20 | 21 | else //Else print the nearest smaller neighbour 22 | cout << S.top() << " "; 23 | 24 | S.push(arr[i]); 25 | 26 | } 27 | } 28 | 29 | int main(){ 30 | 31 | int N = 5; // size of array 32 | 33 | int arr[] = { 1, 2, 5, 3, 5 }; 34 | 35 | nearestSmallerNeighbour(arr, N); 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /16_Nearest smaller neighbour/Ideal Solutions/nearestSmallerNeighbour.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.lang.*; 4 | 5 | 6 | class Main{ 7 | //This function returns an array having the nearest smaller element for each number or -1 if it does not exists. 8 | public static int[] nearestSmallerNeighbour(int[] arr,int n){ 9 | Stack stack = new Stack<>(); 10 | int[] ans = new int[n]; 11 | for (int i=0;i= arr[i]) stack.pop(); 13 | if (stack.isEmpty()) ans[i] = -1; 14 | else{ 15 | ans[i] = stack.peek(); 16 | } 17 | stack.push(arr[i]); 18 | } 19 | return ans; 20 | } 21 | //This function prints all the elements of an array on a single line. 22 | public static void printArray(int[] ans){ 23 | for (int i=0;i 0 and nearestArray[-1] >= array[i]: 14 | nearestArray.pop() 15 | 16 | # If At any point , the stack is empty that means no smallest neighbour element exist for the current element 17 | if len(nearestArray) == 0: 18 | result.append(-1) 19 | 20 | # Otherwise the top element of the stack is the nearest smallest element. 21 | else: 22 | result.append(nearestArray[-1]) 23 | 24 | # Insert Every element 25 | nearestArray.append(array[i]) 26 | 27 | return result 28 | 29 | 30 | if __name__ == "__main__": 31 | 32 | # Static input 33 | array = [1, 2, 5, 3, 5] 34 | print(nearestSmallestNeighbour(array)) 35 | -------------------------------------------------------------------------------- /16_Nearest smaller neighbour/Problem Statement/nearestSmallerNeighbour.md: -------------------------------------------------------------------------------- 1 | ## **Smaller neighbour element** 2 | Given an array A having N positive integers. Find the nearest smaller number for every element such that the smaller element is on left side. 3 | 4 | Note - If any element doesn't have any smaller element that it to it's left, print -1 for it. 5 | 6 | #### **Sample Input** 7 | input: N = 5 8 | A : 1 2 5 3 5 9 | 10 | #### **Sample Output** 11 | A: -1 1 2 2 3 12 | 13 | #### **Sample Explanation** 14 | 15 | There is no element to the left of 1 hence for it there is no smaller neighbour. Hence the answer is -1. 16 | For 2 nearest smaller neighbout to it's left is 1. 17 | For 5 nearest smaller neighbout to it's left is 2. 18 | For 3 nearest smaller neighbout to it's left is 2. 19 | For 5 nearest smaller neighbout to it's left is 3. 20 | 21 | #### **Expected Time Complexity** 22 | __O__(N), where N is the size of the array. 23 | 24 | #### **Expected Space Complexity** 25 | __O__(N), where N is the size of the array. 26 | 27 | #### **Constraints** 28 | 1 <= N <= 100000 29 | -------------------------------------------------------------------------------- /17_Sort An Array of 0's. 1's and 2's/Ideal Solutions/sortAnArrayOf012.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to sort the input array of 0's, 1's and 2'. 5 | 6 | void sort012(int arr[], int N){ 7 | 8 | int cnt0 = 0, cnt1 = 0, cnt2 = 0; 9 | 10 | // Count the number of 0, 1 and 2 present in th array 11 | 12 | for( int i = 0; i 0) { 32 | arr[i++] = 0; 33 | cnt0--; 34 | } 35 | 36 | while (cnt1 > 0) { 37 | arr[i++] = 1; 38 | cnt1--; 39 | } 40 | while (cnt2 > 0) { 41 | arr[i++] = 2; 42 | cnt2--; 43 | } 44 | printArr(arr, n); 45 | } 46 | 47 | // Main Function 48 | public static void main(String[] args){ 49 | int arr[] = {0, 1, 2, 0, 1, 2}; 50 | int n = arr.length; 51 | sortArr(arr, n); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /17_Sort An Array of 0's. 1's and 2's/Ideal Solutions/sortArray.py: -------------------------------------------------------------------------------- 1 | # Sort array 0's , 1's and 2's in order 2 | 3 | def sortArray(array): 4 | # Variable Declaration 5 | current = 0 # Current pointer which will point to current position 6 | leftPointer = 0 # Left Pointer which will point to the left most position 7 | rightPointer = len(array) - 1 # Right Pointer which will point to the right most position 8 | 9 | while current <= rightPointer: # current pointer will move towards the right pointer 10 | 11 | # If current pointer contains the value 0, Then Move the 0 to begin, by swapping it with left pointer 12 | if array[current] == 0: 13 | array[current], array[leftPointer] = array[leftPointer], array[current] 14 | current = current + 1 15 | leftPointer = leftPointer + 1 16 | 17 | # If current pointer contains the value 1, Then keep it as the same position 18 | elif array[current] == 1: 19 | current += 1 20 | 21 | # If current pointer contains the value 2, Then Move the 2 to last by swapping with right pointer 22 | else: 23 | array[current], array[rightPointer] = array[rightPointer], array[current] 24 | rightPointer = rightPointer - 1 25 | 26 | return array 27 | 28 | 29 | if __name__ == "__main__": 30 | # Static Input 31 | array = [0, 1, 2, 0, 1, 2] 32 | 33 | print(sortArray(array)) 34 | -------------------------------------------------------------------------------- /17_Sort An Array of 0's. 1's and 2's/Problem Statement/sortAnArray.md: -------------------------------------------------------------------------------- 1 | ## **Sort an Array of 0s, 1s, or 2s** 2 | 3 | Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last. 4 | 5 | 6 | 7 | #### **Sample Input** 8 | array = {0, 1, 2, 0, 1, 2} 9 | 10 | 11 | 12 | #### **Sample Output** 13 | array = {0, 0, 1, 1, 2, 2} 14 | 15 | #### **Sample Explanation** 16 | The array on sorting gives the resultant array as shown in the output 17 | 18 | #### **Expected Time Complexity** 19 | __O__(N), where N is the size of the array. 20 | #### **Expected Space Complexity** 21 | __O__(1),Auxilliary Space 22 | 23 | #### **Constraints** 24 | n == nums.length 25 | 1 <= n <= 300 26 | array[i] is 0, 1, or 2. 27 | 28 | 29 | -------------------------------------------------------------------------------- /18_Matrix rotation/Ideal Solutions/matrixRotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | const int R = 3, C = 3; // Size of rows and colums of the matrix 4 | 5 | void matrixRotation(int arr[][C]) { 6 | // Function to rotate the matrix by 90 degrees anti-clockwise 7 | 8 | // Taking Transpose 9 | for (int i = 0; i < R; i++) 10 | for (int j = i; j < C; j++) 11 | swap(arr[i][j], arr[j][i]); 12 | // Reversing the columns 13 | for (int i = 0; i < C; i++) 14 | for (int j = 0, k = C - 1; j < k; j++, k--) 15 | swap(arr[j][i], arr[k][i]); 16 | } 17 | 18 | // Driven code 19 | int main() 20 | { 21 | int arr[R][C] = { { 1, 2, 3 }, 22 | { 4, 5, 6 }, 23 | { 7, 8, 9 } }; 24 | 25 | // Calling the function to rotate the matrix 26 | matrixRotation(arr); 27 | 28 | // Printing the rotated matrix 29 | for (int i = 0; i < R; i++) { 30 | for (int j = 0; j < C; j++) 31 | cout << arr[i][j] << " "; 32 | cout << '\n'; 33 | } 34 | return 0; 35 | } -------------------------------------------------------------------------------- /18_Matrix rotation/Ideal Solutions/matrixRotation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function rotates the elements in the array in cl 8 | public static void matrixRotation(int[][] matrix){ 9 | int n = matrix.length; 10 | for (int i=0;i4->3], list2 = [5->6->4] 10 | 11 | #### **Sample Output** 12 | list = [7->0->8] 13 | 14 | #### **Sample Explanation** 15 | The number represented by the first linked list is 342, while the number represented by the second linked list is 465. Adding them, the new list represents their sum 807. 16 | 17 | 18 | #### **Expected Time Complexity** 19 | __O__(m + n), where m and n are number of nodes in first and second lists respectively. 20 | The lists needs to be traversed only once. 21 | 22 | 23 | #### **Expected Space Complexity** 24 | __O__(k), where k is the number of digits. 25 | 26 | #### **Constraints** 27 | The number of nodes in each linked list is in the range [1, 100]. 28 | 0 <= Node.val <= 9 29 | It is guaranteed that the list represents a number that does not have leading zeros. 30 | -------------------------------------------------------------------------------- /20_Reverse a Linked List/Ideal Solutions/reverseALinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Node structure of LinkedList */ 5 | 6 | struct Node { 7 | 8 | int data; 9 | struct Node* next; 10 | 11 | Node(int data){ 12 | 13 | this->data = data; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | struct LinkedList { 19 | 20 | Node* head; 21 | LinkedList() { head = NULL; } 22 | 23 | 24 | void push(int data){ 25 | 26 | Node* temp = new Node(data); 27 | 28 | if(head == NULL ){ 29 | head = temp; 30 | } 31 | 32 | else{ 33 | 34 | Node* curr = head; 35 | 36 | while( curr->next != NULL ){ 37 | curr = curr->next; 38 | } 39 | 40 | curr->next = temp; 41 | 42 | } 43 | } 44 | 45 | // Function to reverse the linked list 46 | 47 | void reverse(){ 48 | 49 | Node* curr = head; 50 | Node *prev = NULL, *next = NULL; 51 | 52 | while (curr != NULL) { 53 | 54 | next = curr->next; 55 | 56 | curr->next = prev; 57 | 58 | prev = curr; 59 | 60 | curr = next; 61 | } 62 | 63 | head = prev; 64 | } 65 | 66 | 67 | void print(){ 68 | 69 | struct Node* temp = head; 70 | while (temp != NULL) { 71 | cout << temp->data << " "; 72 | temp = temp->next; 73 | } 74 | } 75 | 76 | }; 77 | 78 | int main(){ 79 | 80 | LinkedList L; 81 | 82 | L.push(1); 83 | L.push(2); 84 | L.push(3); 85 | L.push(4); 86 | 87 | L.reverse(); 88 | 89 | L.print(); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /20_Reverse a Linked List/Ideal Solutions/reverseLinkedList.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | //This class implements the structure of the Singly linked list 6 | class Node{ 7 | int data; 8 | Node next; 9 | 10 | 11 | Node(int data){ 12 | this.data = data; 13 | this.next = null; 14 | } 15 | } 16 | 17 | 18 | class Main{ 19 | //This function adds two Singly linked list. 20 | public static Node reverseLinkedList(Node head){ 21 | Node current = head; 22 | Node after = null; 23 | Node before = null; 24 | while(current != null){ 25 | after = current.next; 26 | current.next = before; 27 | before = current; 28 | current = after; 29 | } 30 | head = before; 31 | return head; 32 | } 33 | 34 | //This function prints the Singly linked list on a single line. 35 | public static void printList(Node head){ 36 | if(head == null) return ; 37 | while(head != null){ 38 | System.out.print(head.data + "->"); 39 | head = head.next; 40 | } 41 | System.out.println("NULL"); 42 | 43 | } 44 | 45 | //This function creates a singly linked list from an array. 46 | public static Node generateSinglyLinkedList(int[] arr){ 47 | if (arr.length == 0 || arr == null) return null; 48 | Node SinglyLinkedList = new Node(arr[0]); 49 | Node temp = SinglyLinkedList; 50 | for (int i=1;i2->3->4->NULL 8 | 9 | #### **Sample Output** 10 | list = 4->3->2->1->NULL 11 | 12 | #### **Sample Explanation** 13 | On reversing the linked list by changing the link between the nodes, the linked list is transformed as shown in the sample output 14 | 15 | 16 | #### **Expected Time Complexity** 17 | __O__(N), where N is the number elements in the linked list. 18 | 19 | 20 | #### **Expected Space Complexity** 21 | __O__(1), i.e. , constant space complexity. 22 | 23 | #### **Constraints** 24 | A linked list can be reversed either iteratively or recursively. The task is to implement both the implementations. 25 | -------------------------------------------------------------------------------- /21_Detect Loop in a Linked List/Ideal Solutions/detectLoop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Link list node */ 5 | class Node { 6 | public: 7 | int data; 8 | Node* next; 9 | }; 10 | 11 | void push(Node** head_ref, int new_data) 12 | { 13 | Node* new_node = new Node(); 14 | 15 | new_node->data = new_data; 16 | 17 | new_node->next = (*head_ref); 18 | 19 | (*head_ref) = new_node; 20 | } 21 | 22 | int detectLoop(Node* list) 23 | { 24 | Node *slow_p = list, *fast_p = list; 25 | 26 | while (slow_p && fast_p && fast_p->next) { 27 | slow_p = slow_p->next; 28 | fast_p = fast_p->next->next; 29 | if (slow_p == fast_p) { 30 | return 1; 31 | } 32 | } 33 | return 0; 34 | } 35 | int main() { 36 | /* Start with the empty list */ 37 | Node* head = NULL; 38 | 39 | push(&head, 3); 40 | push(&head, 2); 41 | push(&head, 0); 42 | push(&head, -4); 43 | 44 | /* Create a loop for testing */ 45 | head->next->next->next->next = head; 46 | if (detectLoop(head)) 47 | cout << "Loop found" << endl; 48 | else 49 | cout << "No Loop" << endl; 50 | return 0; 51 | } -------------------------------------------------------------------------------- /21_Detect Loop in a Linked List/Ideal Solutions/detectLoop.py: -------------------------------------------------------------------------------- 1 | # Node Class containing the value and next pointer 2 | class Node: 3 | def __init__(self, value): 4 | self.value = value 5 | self.next = None 6 | 7 | 8 | # List class containing set of functions to insert, print and detect loop 9 | class List: 10 | # Intialize the head object 11 | def __init__(self): 12 | self.head = None 13 | 14 | # This will insert the node at he beginning 15 | def insert(self, value): 16 | node = Node(value) 17 | node.next = self.head 18 | self.head = node 19 | 20 | # This function will print the complete list 21 | def print(self): 22 | temporaryNode = self.head 23 | 24 | while temporaryNode: 25 | print(temporaryNode.value) 26 | temporaryNode = temporaryNode.next 27 | 28 | # This function will detect the loop in the list 29 | def detectLoop(self): 30 | slowPointer, fastPointer = self.head, self.head 31 | while slowPointer and fastPointer and fastPointer.next: 32 | slowPointer = slowPointer.next 33 | fastPointer = fastPointer.next.next 34 | if slowPointer == fastPointer: return True 35 | 36 | return False 37 | 38 | 39 | if __name__ == "__main__": 40 | list = List() 41 | 42 | list.insert(3) 43 | list.insert(2) 44 | list.insert(0) 45 | list.insert(-4) 46 | 47 | # Inserting Cycle in the linked list 48 | list.head.next.next.next.next = list.head 49 | 50 | # list.print() # Runs Infinite Times, Because List contains Loop 51 | 52 | if list.detectLoop(): 53 | print("List Contains Cycle") 54 | else: 55 | print("Not Contains Cycle") 56 | -------------------------------------------------------------------------------- /21_Detect Loop in a Linked List/Problem Statement/loopInALinkedList.md: -------------------------------------------------------------------------------- 1 | ## **Detect Loop in a Linked List** 2 | 3 | Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. 4 | Refer [this](https://i0.wp.com/www.dineshonjava.com/wp-content/uploads/2018/09/Linked-List-Loop.png?resize=530%2C207&ssl=1) this for better understanding. 5 | 6 | #### **Sample Input** 7 | list = [3,2,0,-4], position = 1 8 | 9 | #### **Sample Output** 10 | Linked List contains a cycle. 11 | 12 | #### **Sample Explanation** 13 | There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, position is used here to denote the index of the node that tail's next pointer is connected to. Note that position is not passed as a parameter. 14 | 15 | 16 | #### **Expected Time Complexity** 17 | __O__(N), where N is the number of elements in the linked list. Only one traversal of the loop should be needed. 18 | 19 | 20 | #### **Expected Space Complexity** 21 | __O__(1), Auxiliary space 22 | 23 | #### **Constraints** 24 | The number of the nodes in the list is in the range [0, 10^4]. 25 | -10^5 <= Node.val <= 10^5 26 | -------------------------------------------------------------------------------- /22_Palindrome Linked List/Ideal Solutions/palindromeLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // structure of node of linked list 5 | struct Node { 6 | 7 | int data; 8 | 9 | Node *next = NULL; 10 | 11 | }; 12 | 13 | // Function to check if the linked list 14 | // is palindrome or not 15 | bool isPalindrome(Node* head){ 16 | 17 | // Temp pointer 18 | Node* temp= head; 19 | 20 | stack s; 21 | 22 | // Push all elements of the list 23 | // into the stack 24 | while(temp != NULL){ 25 | s.push(temp->data); 26 | 27 | // Move ahead 28 | temp = temp->next; 29 | } 30 | 31 | // Pop all the elements of stack and 32 | // Check with elements of linkedlist one by one 33 | 34 | while(head != NULL ){ 35 | 36 | // Get the top most element 37 | int top =s.top(); 38 | 39 | // Pop the element 40 | s.pop(); 41 | 42 | // Check if data is not 43 | // same as the top element 44 | if(head -> data != top){ 45 | return false; 46 | } 47 | 48 | head=head->next; 49 | } 50 | 51 | return true; 52 | 53 | 54 | } 55 | 56 | 57 | int main(){ 58 | 59 | // Linked list 60 | Node* head = new Node; 61 | head->data = 1; 62 | Node* temp = head; 63 | temp->next = new Node; 64 | temp->next->data = 2; 65 | temp = temp->next; 66 | temp->next = new Node; 67 | temp->next->data = 3; 68 | temp = temp->next; 69 | temp->next = new Node; 70 | temp->next->data = 2; 71 | temp = temp->next; 72 | temp->next = new Node; 73 | temp->next->data = 1; 74 | temp = temp->next; 75 | 76 | if(isPalindrome(head)) 77 | cout<<"Given linked list is a palindrome \n"; 78 | else 79 | cout<<"Given linked list is not a palindrome\n"; 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /22_Palindrome Linked List/Problem Statement/plaindromeLinkedList.md: -------------------------------------------------------------------------------- 1 | ## **Palindrome Linked List** 2 | 3 | Given a singly linked list, determine if it is a palindrome. 4 | 5 | __NOTE__ : A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. 6 | 7 | #### **Sample Input** 8 | list = 1->2->2->1 9 | 10 | #### **Sample Output** 11 | Given linked list is a palindrome 12 | 13 | #### **Sample Explanation** 14 | The linked list given in the sample test case, is the same read whether forwards or backwards. Therefore, it can be deemed as a palindrome. 15 | 16 | 17 | #### **Expected Time Complexity** 18 | __O__(N), where N is the number of elements in the linked list. 19 | 20 | 21 | #### **Expected Space Complexity** 22 | 23 | __O__(N), Auxiliary space 24 | 25 | 26 | #### **Constraints** 27 | This can be checked both iteratively and recursively. The task is to implement both the implementations. 28 | -------------------------------------------------------------------------------- /23_Container With Most Water/Ideal Solutions/containerWithMostWater.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.lang.*; 4 | 5 | 6 | class Main{ 7 | //This function out the value of the container with most water. 8 | public static int containerWithMostWater(int[] container){ 9 | int left = 0; 10 | int right = container.length-1; 11 | int max_area = 0; 12 | while(left < right){ 13 | max_area = Math.max(max_area, Math.min(container[left],container[right])*(right - left)); 14 | if (container[left] < container[right]) left++; 15 | else{ 16 | right--; 17 | } 18 | } 19 | return max_area; 20 | } 21 | //Main function 22 | public static void main(String[] args){ 23 | int[] container = {1,8,6,2,5,4,8,3,7}; 24 | int max_area = containerWithMostWater(container); 25 | System.out.println(max_area); 26 | } 27 | } -------------------------------------------------------------------------------- /23_Container With Most Water/Ideal Solutions/mostWaterContainer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int mostWaterContainer(int arr[], int n) 5 | { 6 | // Function to calculate maximum area of water that can be contained 7 | int left = 0; 8 | int right = n - 1; 9 | int area = 0; 10 | 11 | while (left < right) 12 | { 13 | area = max(area, min(arr[left], arr[right]) * (right - left)); 14 | 15 | if (arr[left] < arr[right]) 16 | left += 1; 17 | 18 | else 19 | right -= 1; 20 | } 21 | return area; 22 | } 23 | int main() { 24 | int n = 9; // Size of the array 25 | int arr[] = {1, 8, 6, 2, 5, 4, 8, 3, 7}; 26 | 27 | cout << mostWaterContainer(arr, n) << endl; 28 | return 0; 29 | } -------------------------------------------------------------------------------- /23_Container With Most Water/Ideal Solutions/mostWaterContainer.py: -------------------------------------------------------------------------------- 1 | 2 | # Calculating the conatainer area with most water 3 | def mostWaterContainer(container): 4 | 5 | # Setting left pointer, right pointer and area 6 | leftMostSide = 0 7 | rightMostSide = len(container) - 1 8 | maxArea = 0 9 | 10 | while leftMostSide < rightMostSide: 11 | 12 | # Keep Track of max area 13 | maxArea = max(maxArea, min(container[leftMostSide], container[rightMostSide]) * (rightMostSide - leftMostSide)) 14 | 15 | # Either side which will be smaller , index will be updated 16 | if container[leftMostSide] < container[rightMostSide]: 17 | leftMostSide += 1 18 | else: 19 | rightMostSide = rightMostSide - 1 20 | 21 | return maxArea 22 | 23 | 24 | if __name__ == "__main__": 25 | array = [] 26 | 27 | # Inputs 28 | container = [1, 8, 6, 2, 5, 4, 8, 3, 7] 29 | 30 | print(mostWaterContainer(container)) 31 | -------------------------------------------------------------------------------- /23_Container With Most Water/Problem Statement/containerWithMostWater.md: -------------------------------------------------------------------------------- 1 | ## **Container With Most Water** 2 | 3 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. 4 | 5 | Notice that you may not slant the container. 6 | 7 | 8 | 9 | 10 | 11 | #### **Sample Input** 12 | array = [1,8,6,2,5,4,8,3,7] 13 | 14 | 15 | 16 | #### **Sample Output** 17 | 49 18 | 19 | #### **Sample Explanation** 20 | Refer [this](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg) image for understanding. 21 | The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 22 | 23 | #### **Expected Time Complexity** 24 | __O__(N), where N is the size of the array. 25 | #### **Expected Space Complexity** 26 | __O__(1),Auxilliary Space 27 | 28 | #### **Constraints** 29 | n == height.length 30 | 2 <= n <= 3 * 10^4 31 | 0 <= height[i] <= 3 * 10^4 32 | 33 | 34 | -------------------------------------------------------------------------------- /24_Sliding Window Maximum/Ideal Solutions/slidingWindowMaximum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to calculate Maximum element for all subarrays of size k 5 | 6 | void kMax(int arr[], int N, int K){ 7 | 8 | // Double Ended Queue, 9 | // maintaining nonincreasing order of 10 | // values from front to rear in Qi. 11 | 12 | deque dq(K); 13 | 14 | // Push the first window 15 | 16 | for (int i = 0; i < K; ++i){ 17 | 18 | // Remove all the elements of dequeue 19 | // which are less than or equal to arr[i] 20 | 21 | while ((!dq.empty()) && arr[i] >= arr[dq.back()]) 22 | // Remove from rear 23 | dq.pop_back(); 24 | 25 | // Add new element at rear of dequeue 26 | dq.push_back(i); 27 | } 28 | 29 | for (int i = K; i < N; ++i){ 30 | 31 | // The element at the front of 32 | // the dequeue is the largest element of 33 | // previous window 34 | cout << arr[dq.front()] << " "; 35 | 36 | // Remove the elements which 37 | // are out of this window 38 | while ((!dq.empty()) && dq.front() <= i-K) 39 | 40 | // Remove from front of queue 41 | dq.pop_front(); 42 | 43 | while ((!dq.empty()) && arr[i] >= arr[dq.back()]) 44 | dq.pop_back(); 45 | 46 | dq.push_back(i); 47 | } 48 | 49 | // Print for the last window 50 | cout << arr[dq.front()]; 51 | } 52 | 53 | 54 | int main(){ 55 | 56 | int arr[] = { 1, 2, 3, 1, 4, 5 }; 57 | 58 | int N = 6; 59 | int K = 3; 60 | 61 | kMax(arr, N, K); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /24_Sliding Window Maximum/Ideal Solutions/slidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main{ 6 | //This function finds out the maximum element in all subarrays of size K 7 | public static List slidingWindowMaximum(int arr[], int k){ 8 | if (k > arr.length) return new ArrayList<>(); 9 | List ans = new ArrayList<>(); 10 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); 11 | for (int i=0;i ans = slidingWindowMaximum(arr,k); 25 | for (Integer i : ans) System.out.print(i + " "); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /24_Sliding Window Maximum/Ideal Solutions/slidingWindowMaximum.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # Sliding Window Problem 4 | def slidingWindowMaximum(arr, K): 5 | slidingDeque = deque() 6 | maxWindow = [] 7 | 8 | for index, currentValue in enumerate(arr): 9 | while slidingDeque and arr[slidingDeque[-1]] < currentValue: 10 | slidingDeque.pop() 11 | 12 | # Add element in the queue from the right 13 | slidingDeque.append(index) 14 | 15 | if slidingDeque[0] == index - K: 16 | slidingDeque.popleft() 17 | 18 | if index >= (K-1): 19 | maxWindow.append(arr[slidingDeque[0]]) 20 | 21 | return maxWindow 22 | 23 | 24 | 25 | 26 | 27 | if __name__ == "__main__": 28 | 29 | # Input 30 | arr = [1, 2, 3, 1, 4, 5] 31 | K = 3 32 | 33 | print(slidingWindowMaximum(arr, K)) 34 | -------------------------------------------------------------------------------- /24_Sliding Window Maximum/Problem Statement/Sliding Window Maximum.md: -------------------------------------------------------------------------------- 1 | ## **Sliding Window Maximum** 2 | Given an array and an integer K, find the maximum for each and every contiguous subarray of size K. 3 | 4 | #### **Sample Input** 5 | arr[] = {1, 2, 3, 1, 4, 5} 6 | K = 3 7 | #### **Sample Output** 8 | Output: 3 3 4 5 9 | #### **Sample Explanation** 10 | Maximum of 1, 2, 3 is 3 11 | Maximum of 2, 3, 1 is 3 12 | Maximum of 3, 1, 4 is 4 13 | Maximum of 1, 4, 5 is 5 14 | #### **Expected Time Complexity** 15 | __O__(N* log K), where N : Size of array, K: Size of sub-array 16 | #### **Expected Space Complexity** 17 | __O__(K) : Auxillary space, where K is the size of sub-array 18 | 19 | #### **Constraints** 20 | 1 <= N <= 100000 21 | 1 <= K <= 100000 22 | -------------------------------------------------------------------------------- /25_Two Numbers in Sorted Array whose sum is K/Ideal Solutions/twoNumbersInSortedArraySumK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | // Function to check if any two numbers of array add to k 6 | 7 | void kSum(int arr[], int N, int k){ 8 | 9 | //Initializing two pointers 10 | 11 | int i = 0, j = N-1; 12 | 13 | while(i k ) 19 | j--; 20 | 21 | // If sum of two numbers is less than k then, 22 | // move the first pointer one step ahead. 23 | 24 | else if( arr[i] + arr[j] < k ) 25 | i++; 26 | 27 | // Else given numbers add to k 28 | 29 | else 30 | break; 31 | } 32 | 33 | // No answer exists if pointer i becomes greater than or equal to j 34 | 35 | if(i>=j) 36 | cout<<-1<<"\n"; 37 | 38 | else 39 | cout< K) right--; 19 | else{ 20 | left++; 21 | } 22 | } 23 | return ans; 24 | } 25 | //Main Function 26 | public static void main(String args[]){ 27 | int[] array = {2,7,11,15}; 28 | int K = 9; 29 | int[] ans = twoSum(array,K); 30 | System.out.println(ans[0] +" "+ans[1]); 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /25_Two Numbers in Sorted Array whose sum is K/Ideal Solutions/twoSum.py: -------------------------------------------------------------------------------- 1 | 2 | # 2 sum problem to find target number , from the sum of 2 numbers of given array 3 | def twoSum(array, targetNumber): 4 | 5 | seen = set() 6 | 7 | for index, val in enumerate(array): 8 | 9 | # Value of other number 10 | difference = targetNumber - val 11 | if difference in seen: 12 | secondNumberIndex = array.index(difference) 13 | result = list((index, secondNumberIndex)) 14 | seen.add(val) 15 | 16 | return result 17 | 18 | 19 | 20 | if __name__ == "__main__": 21 | 22 | # Static Input 23 | array = [2,7,11,15] 24 | K = 9 25 | 26 | print(twoSum(array, K)) 27 | -------------------------------------------------------------------------------- /25_Two Numbers in Sorted Array whose sum is K/Problem Statement/twoNumbersInSortedArray.md: -------------------------------------------------------------------------------- 1 | ## **Two Numbers in sorted array whose sum is K** 2 | 3 | Given a sorted array of integers nums and an integer K, return indices of the two numbers such that they add up to K. 4 | 5 | Note: You can assume that the answer always exists 6 | 7 | #### **Sample Input** 8 | array = [2,7,11,15], K = 9 9 | 10 | 11 | #### **Sample Output** 12 | [0,1] 13 | 14 | #### **Sample Explanation** 15 | As seen from the sample input, the values at index 0 and 1 add up to the required value of 9. Therefore, the output is [0,1]. 16 | 17 | #### **Expected Time Complexity** 18 | __O__(N),where N is the size of the array. 19 | 20 | #### **Expected Space Complexity** 21 | __O__(1), Auxillary space complexity. 22 | 23 | #### **Constraints** 24 | 2 <= nums.length <= 103 25 | -10^9 <= nums[i] <= 10^9 26 | -10^9 <= target <= 10^9 27 | 28 | 29 | -------------------------------------------------------------------------------- /26_GCD/Editorial/gcd Editorial.md: -------------------------------------------------------------------------------- 1 | ### GCD- Editorial 2 | 3 | ### Difficulty: Medium 4 | 5 | ### Prerequisite: Recursion, Modulo Operation 6 | --- 7 | ### Hint 8 | 9 | * To get GCD of two numbers think about subtracting smaller one from the larger number to get the a number which divides both of them. 10 | 11 | ### Short Explanation 12 | 13 | * Greatest Common Divisor (GCD) of two or more numbers (A and B) is the largest positive number that divides all the numbers which are being taken into consideration. So we can think of finding an integer which divides both A and B. 14 | 15 | 16 | ### Detailed Explanation 17 | 18 | * We can traverse from min(A,B) to 1 and check which number divides both A and B, and if it does it is the GCD but it will take O(max(A,B)) time. 19 | 20 | * We are going to use Euclidean method to find out the GCD efficiently, The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number now to make it more efficient instead of subtraction, if we divide the smaller number, the algorithm stops when we find remainder 0. 21 | 22 | ### Time Complexity: 23 | 24 | ` O(log(max(A, B))) `, where `A` and `B` are two Numbers 25 | 26 | ### Space Complexity: 27 | 28 | `O(1)`, Constant space is required. 29 | 30 | ### Alternate Solution: 31 | 32 | Read about Extended Euclidean to apply 33 | -------------------------------------------------------------------------------- /26_GCD/Ideal Solutions/greatestCommonDivisor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int greatestCommonDivisor(int a, int b) { 4 | // Recursive function to find GCD of a and b 5 | if (b == 0) 6 | return a; 7 | return greatestCommonDivisor(b, a % b); 8 | } 9 | int main() { 10 | int a = 10, b = 6; 11 | cout << greatestCommonDivisor(a, b) << endl; 12 | return 0; 13 | } -------------------------------------------------------------------------------- /26_GCD/Ideal Solutions/greatestCommonDivisor.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This recrsive function calculates the greatest common divisor of two numbers. 8 | public static int greatestCommonDivisor(int n,int m){ 9 | if (n == 0) return m; 10 | return greatestCommonDivisor(m % n,n); 11 | } 12 | //Main Function 13 | public static void main(String[] args){ 14 | int n = 10; 15 | int m = 6; 16 | System.out.println(greatestCommonDivisor(n,m)); 17 | } 18 | } -------------------------------------------------------------------------------- /26_GCD/Ideal Solutions/greatestCommonDivisor.py: -------------------------------------------------------------------------------- 1 | # Compute GCD of A and B 2 | def greatestCommonDivisor(N, M): 3 | if M == 0 : 4 | return N 5 | return greatestCommonDivisor(M, N%M) 6 | pass 7 | 8 | 9 | if __name__ == "__main__": 10 | 11 | # Input 12 | array = [1, 2, 1, 3, 5, 6, 4] 13 | N = 10 14 | M = 6 15 | 16 | print(greatestCommonDivisor(N, M)) 17 | -------------------------------------------------------------------------------- /26_GCD/Problem Statement/gcd.md: -------------------------------------------------------------------------------- 1 | ## **GCD** 2 | Given two integer N and M. Calculate the gcd of N and M. 3 | 4 | #### **Sample Input** 5 | input: N = 10, M = 6 6 | 7 | #### **Sample Output** 8 | Output: 2 9 | 10 | #### **Sample Explanation** 11 | 2 is the biggest factor that divides both 10 and 6. 12 | 13 | #### **Expected Time Complexity** 14 | __O__(log(MAX(N,M))) 15 | 16 | #### **Expected Space Complexity** 17 | __O__(1), i.e., constant space complexity. 18 | 19 | #### **Constraints** 20 | 1 <= N,M <= 1000000000 21 | -------------------------------------------------------------------------------- /27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fib_code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fib_code.png -------------------------------------------------------------------------------- /27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fib_complexity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fib_complexity.png -------------------------------------------------------------------------------- /27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fibonacci.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fibonacci.png -------------------------------------------------------------------------------- /27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fibonacci2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fibonacci2.png -------------------------------------------------------------------------------- /27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fibonacci_eqn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/27_Nth Fibonacci/Editorial/Nth Fibonacci - Editorial 6b42f65168a44ba3a8f845ded117ae09/fibonacci_eqn.png -------------------------------------------------------------------------------- /27_Nth Fibonacci/Ideal Solutions/nthFibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to calculate Nth fibonacci 5 | 6 | int fibonacci(int N){ 7 | 8 | int F1 = 1, F2 = 1, Fn; 9 | 10 | for(int i = 3; i <= N; i++){ 11 | 12 | Fn = F1 + F2; 13 | F1 = F2; 14 | F2 = Fn; 15 | } 16 | 17 | if( N == 1 ) 18 | return F1; 19 | if( N == 2) 20 | return F2; 21 | 22 | return Fn; 23 | } 24 | 25 | 26 | int main(){ 27 | 28 | int N = 5; 29 | 30 | cout << fibonacci(N); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /27_Nth Fibonacci/Ideal Solutions/nthFibonacci.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | class Main{ 6 | //This function returns the Nth fibonacci number. 7 | public static int nthFibonacci(int n){ 8 | if (n == 0) return 0; 9 | if (n == 1) return 1; 10 | return nthFibonacci(n-1) + nthFibonacci(n-2); 11 | } 12 | //Main Function 13 | public static void main(String[] args){ 14 | int n = 4; 15 | System.out.println(nthFibonacci(n)); 16 | } 17 | } -------------------------------------------------------------------------------- /27_Nth Fibonacci/Ideal Solutions/nthFibonacci.py: -------------------------------------------------------------------------------- 1 | # Finds Nth Fibonacci Number 2 | def nthFibonacci(Number): 3 | first, second = 0, 1 4 | 5 | # Base Case 6 | if Number < 0: 7 | print("Wrong Input") 8 | elif Number == 0: 9 | return first 10 | elif Number == 1: 11 | return second 12 | 13 | 14 | # Finding Nth Fibonacci using recurring addition 15 | else: 16 | for i in range(2, Number + 1): 17 | third = first + second 18 | first = second 19 | second = third 20 | 21 | return second 22 | 23 | 24 | if __name__ == "__main__": 25 | array = [] 26 | 27 | # Static Input 28 | N = 9 29 | 30 | print(nthFibonacci(N)) 31 | -------------------------------------------------------------------------------- /27_Nth Fibonacci/Problem Statement/fibonacci.md: -------------------------------------------------------------------------------- 1 | ## **Nth Fibonacci** 2 | Given a positive integer N. Find the Nth fibonacci number. 3 | 4 | __NOTE__ : In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. The beginning of the sequence is thus 5 | `[0,1,2,3,5,8,13,21,34,...]` 6 | 7 | #### **Sample Input** 8 | input: N = 5 9 | 10 | #### **Sample Output** 11 | A: 3 12 | 13 | #### **Sample Explanation** 14 | Fibonacci series: 0 1 1 2 3 5 8 13 .... 15 | Hence 5th fibonacci is: 3 16 | 17 | #### **Expected Time Complexity** 18 | __O__(N) 19 | 20 | #### **Expected Space Complexity** 21 | __O__(N), Auxillary space complexity. 22 | 23 | #### **Constraints** 24 | 1 <= N <= 100000 25 | -------------------------------------------------------------------------------- /28_Permutations with Largest Sum/Ideal Solutions/permutationWithLargestSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to calculate maximum sum for a permutation of array 5 | 6 | void permutationWithLargestSum(int arr[], int N){ 7 | 8 | sort(arr, arr + N); // sort the array 9 | 10 | for (int i = 0; i < N; i++) 11 | cout< 2 | using namespace std; 3 | 4 | // Function to print all permutations of an array 5 | 6 | void permutations(int arr[], int l, int r, int N){ 7 | 8 | //Only permutations for an array having single element 9 | 10 | if (l == r){ 11 | 12 | for(int i=0; i < N; i++) 13 | cout< 2 | using namespace std; 3 | 4 | 5 | void printAllSubsequences(string input, string output){ 6 | 7 | // Function of print all subsequences of a string 8 | 9 | // if the input string is empty then print the output string 10 | 11 | if (input.size() == 0 ) { 12 | cout << output << endl; 13 | return; 14 | } 15 | 16 | //Print all subsequences that contains the first character of the input 17 | printAllSubsequences(input.substr(1), output + input[0]); 18 | 19 | //Print all subsequences that doesn't contain the first character of the input 20 | printAllSubsequences(input.substr(1), output); 21 | } 22 | 23 | int main(){ 24 | 25 | string input = "abc"; 26 | 27 | string output = ""; // output string initially empty 28 | 29 | printAllSubsequences(input, output); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /30_Print all Subsequences of a String/Ideal Solutions/allSubsequencesOfAString.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | class Main{ 6 | static List list = new ArrayList<>(); //global list stores all non empty subsequences of the string 7 | 8 | //Main Function 9 | public static void main(String[] args){ 10 | String s = "abc"; 11 | findsubsequences(s, ""); 12 | System.out.println(list); 13 | } 14 | //This function finds out all the subsequences of the given string. 15 | public static void findsubsequences(String s,String ans){ 16 | if (s.length() == 0) { 17 | if (!ans.isEmpty()) list.add(ans); 18 | return; 19 | } 20 | findsubsequences(s.substring(1), ans + s.charAt(0)); 21 | findsubsequences(s.substring(1), ans); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /30_Print all Subsequences of a String/Problem Statement/Print all subsequences of a string.md: -------------------------------------------------------------------------------- 1 | ## **Print all subsequences of a string** 2 | Given a string, we have to find out all subsequences of it. 3 | 4 | __Note__: A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order. 5 | 6 | #### **Sample Input** 7 | abc 8 | 9 | #### **Sample Output** 10 | a, b, c, ab, bc, ac, abc 11 | #### **Sample Explanation** 12 | Generate all subsequence of string "abc" 13 | 14 | #### **Expected Time Complexity** 15 | __O__(2^N*l), where N is length of string to find subsequences and l is length of binary string. 16 | #### **Expected Space Complexity** 17 | __O__(N), Auxiliary space 18 | 19 | #### **Constraints** 20 | 1 <= N <= 10 21 | -------------------------------------------------------------------------------- /31_N-Queens/Ideal Solutions/nQueens.py: -------------------------------------------------------------------------------- 1 | 2 | # N-Queens Problem 3 | 4 | def isSafe(row, column, board, size): 5 | # CHECKING ROW/COLUMN 6 | for k in range(0, size): 7 | if board[row][k] == 1 or board[k][column] == 1: 8 | return False 9 | 10 | # CHECKING DIAGONALS 11 | for r in range(0, size): 12 | for c in range(0, size): 13 | if (r + c == row + column) or (r - c == row - column): 14 | if board[r][c] == 1: 15 | return False 16 | return True 17 | 18 | 19 | 20 | def nQueens(board, size, row ): 21 | # Base Case 22 | if row == size: return True 23 | 24 | # CHECKING FOR EACH ROW/COLUMN of Board 25 | for column in range(0, 4): 26 | if isSafe(row, column, board, size) and board[row][column] != 1: 27 | 28 | # Putting Queen at row, column 29 | board[row][column] = 1 30 | if nQueens(board, size, row+1): return True 31 | # Removing Queen from row, column 32 | board[row][column] = 0 33 | 34 | return False 35 | 36 | 37 | if __name__ == "__main__": 38 | 39 | # Static Input 40 | N = 4 41 | board = [[0] * N for _ in range(N)] 42 | 43 | nQueens(board, N, 0) 44 | 45 | # Print the cell values of the board 46 | for i in board: 47 | print(i) 48 | 49 | 50 | -------------------------------------------------------------------------------- /31_N-Queens/Problem Statement/N-Queens.md: -------------------------------------------------------------------------------- 1 | ## **N-Queens** 2 | The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. 3 | 4 | __Note__: Given an integer n, output an arrangement if it's possible to place n queens under the given condition, else output "Not Possible" 5 | 6 | #### **Sample Input** 7 | N = 4 8 | 9 | #### **Sample Output** 10 | { 0, 1, 0, 0} 11 | { 0, 0, 0, 1} 12 | { 1, 0, 0, 0} 13 | { 0, 0, 1, 0} 14 | 15 | #### **Sample Explanation** 16 | 1 -> Represents Queen at that place 17 | 0 -> Empty Cell 18 | No two Queens attack each other in this arrangement 19 | 20 | #### **Expected Time Complexity** 21 | __O__(N!), where N*N is the size of the board 22 | #### **Expected Space Complexity** 23 | __O__(N), where N*N is the size of the board 24 | 25 | #### **Constraints** 26 | 1 <= N <= 9 -------------------------------------------------------------------------------- /32_Binary Search/Ideal Solutions/binarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool binarySearch(int arr[], int n, int key) 4 | { 5 | // Function to find key in the array using Binary Search approach 6 | // Iterative Binary Search 7 | int low = 0, high = n - 1; 8 | while (low < high) { 9 | int mid = low + (high - low) / 2; 10 | if (arr[mid] == key) 11 | return 1; 12 | else if (arr[mid] > key) 13 | high = mid - 1; 14 | else if (arr[mid] < key) 15 | low = mid; 16 | } 17 | return 0; 18 | } 19 | int main() { 20 | int n = 4; 21 | int arr[] = {1, 3, 4, 7}; 22 | int key = 3; 23 | 24 | //Sorting the array in increasing order first as Binary Search works on sorted array 25 | sort(arr, arr + n); 26 | 27 | if (binarySearch(arr, n, key)) 28 | cout << "true" << endl; 29 | else 30 | cout << "false" << endl; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /32_Binary Search/Ideal Solutions/binarySearch.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class Main{ 6 | 7 | //This function implements the binary search for k. 8 | public static boolean binarySearch(int[] arr,int n,int k){ 9 | int low = 0; 10 | int high = n - 1; 11 | while(low <= high){ 12 | int mid = low + (high - low)/2; //This ensures that integer overflow does not take place. 13 | if (arr[mid] == k) return true; 14 | else if (arr[mid] > k) high = mid - 1; //searching in the left half 15 | else{ 16 | low = mid + 1; //searching in the right half 17 | } 18 | } 19 | return false; 20 | } 21 | 22 | //Main Function 23 | public static void main(String[] args){ 24 | int n = 4; 25 | int arr[] = {1,3,4,7}; 26 | int k = 3; //The element to be searched. 27 | System.out.println(binarySearch(arr,n,k)); 28 | 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /32_Binary Search/Ideal Solutions/binarySearch.py: -------------------------------------------------------------------------------- 1 | # Binary Search 2 | def binarySearch(arr, N, target): 3 | low = 0 4 | high = N - 1 5 | middle = 0 6 | 7 | while low <= high: 8 | middle = (high + low) // 2 9 | 10 | # If Target is greater, Then consider right half 11 | if arr[middle] < target: 12 | low = middle + 1 13 | 14 | # If Target is smaller, Then consider left half 15 | elif arr[middle] > target: 16 | high = middle - 1 17 | 18 | # If found then return position 19 | else: 20 | return middle 21 | 22 | return -1 23 | 24 | 25 | if __name__ == "__main__": 26 | array = [] 27 | 28 | # Static Input 29 | N = 4 30 | K = 3 31 | arr = [1, 3, 4, 7] 32 | 33 | print(binarySearch(arr, N, K)) -------------------------------------------------------------------------------- /32_Binary Search/Problem Statement/Binary Search.md: -------------------------------------------------------------------------------- 1 | ## **Binary Search** 2 | Given a sorted array of N integers and you need to find if Key (K) exists in the array or not, write an efficient code to do this. 3 | 4 | 5 | __Note__: Try to do it by implementing Binary Search both iteratively and recursively 6 | 7 | #### **Sample Input** 8 | N = 4, arr[] = { 1, 3, 4, 7 }, K = 3 9 | 10 | #### **Sample Output** 11 | true 12 | 13 | #### **Sample Explanation** 14 | Using Binary Search we find that key 3 exists in the array. 15 | 16 | #### **Expected Time Complexity** 17 | __O__(logN), where N is the length of the array 18 | #### **Expected Space Complexity** 19 | __O__(1), constant space solution 20 | 21 | 22 | #### **Constraints** 23 | 1<= N <= 10^6 24 | 1<= arr[i] <= 10^6 25 | 26 | -------------------------------------------------------------------------------- /33_Frequency in Sorted Array/Ideal Solutions/frequencyInSortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int frequencyInSortedArray(int n, int arr[], int k) { 4 | //Function to find the frequency of given element 5 | int cnt = upper_bound(arr, arr + n, k) - lower_bound(arr, arr + n, k); 6 | return cnt; 7 | } 8 | int main() { 9 | int n = 10, q = 3; // Size of array and Number of Queries respectively 10 | int arr[] = { 1, 3, 3, 4, 5, 6, 7, 7, 8, 9 }; 11 | int query[] = {3, 7, 11}; // Storing query elements in an array for simplicity 12 | for (int i = 0; i < q; i++) { 13 | cout << frequencyInSortedArray(n, arr, query[i]) << endl; 14 | } 15 | return 0; 16 | } -------------------------------------------------------------------------------- /33_Frequency in Sorted Array/Ideal Solutions/frequencyInSortedArray.py: -------------------------------------------------------------------------------- 1 | # Frequency in sorted array 2 | def binarySearch(array, low, high, element): 3 | if high < low: return -1 4 | 5 | middle = int(low + (high - low) / 2) 6 | 7 | if array[middle] == element: return middle 8 | 9 | if array[middle] > element: 10 | return binarySearch(array, low, middle - 1, element) 11 | 12 | return binarySearch(array, middle + 1, high, element) 13 | 14 | 15 | def frequencyInSortedArray(array, N, Q): 16 | index = binarySearch(array, 0, N - 1, Q) 17 | 18 | if index == -1: return 0 19 | 20 | frequencyCount = 1 21 | left = index - 1 22 | 23 | # Counting on left side 24 | while left >= 0 and array[left] == Q: 25 | frequencyCount += 1 26 | left -= 1 27 | 28 | # Counting on right side 29 | right = index + 1 30 | while right < N and array[right] == Q: 31 | frequencyCount += 1 32 | right += 1 33 | 34 | return frequencyCount 35 | 36 | 37 | if __name__ == "__main__": 38 | array = [] 39 | 40 | # Static Input : 41 | array = [1, 3, 3, 4, 5, 6, 7, 7, 8, 9] 42 | N = 10 43 | 44 | Q = 3 45 | print(frequencyInSortedArray(array, N, Q)) 46 | Q = 7 47 | print(frequencyInSortedArray(array, N, Q)) 48 | Q = 1 49 | print(frequencyInSortedArray(array, N, Q)) 50 | -------------------------------------------------------------------------------- /33_Frequency in Sorted Array/Problem Statement/Frequency in Sorted Array .md: -------------------------------------------------------------------------------- 1 | ## **Frequency in Sorted Array** 2 | Given a sorted array of N integers, you will be given Q queries and in each query you will be given an integer and you need to output the frequency of that integer in the given array. 3 | 4 | __Note__: Avoid using extra space like using Hashing or Map, It is expected to implement all functions which you use like Binary Search etc. 5 | 6 | #### **Sample Input** 7 | N = 10 , Q = 3 8 | arr[] = { 1,3,3,4,5,6,7,7,8,9 } 9 | Query 1 : 3 10 | Query 2 : 7 11 | Query 3 : 11 12 | 13 | #### **Sample Output** 14 | Output Query 1 : 2 15 | Output Query 2 : 2 16 | Output Query 3 : 0 17 | 18 | #### **Sample Explanation** 19 | In Query 1 : Count of 3 is 2 20 | In Query 2 : Count of 7 is 2 21 | In Query 3 : Count of 11 is 0 22 | 23 | #### **Expected Time Complexity** 24 | __O__(log(N)) for each Query, N: Size of the input array 25 | #### **Expected Space Complexity** 26 | __O__(1), for each Query 27 | 28 | #### **Constraints** 29 | 1<= N <= 10^6 30 | 1<= Q <= 10^5 31 | 1<= arr[i] <= 10^9 32 | 33 | -------------------------------------------------------------------------------- /34_Find Peak Element/Ideal Solutions/findPeakElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int findPeakElement(int arr[], int low, int high, int n) { 4 | // Function to find the index of any peak element present in the array 5 | 6 | int mid = low + (high - low) / 2; 7 | 8 | if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) 9 | return mid; 10 | 11 | // If middle element is not peak and it's left neighbour is greater than it, then the left half must have a peak element 12 | else if (mid > 0 && arr[mid - 1] > arr[mid]) 13 | return findPeakElement(arr, low, (mid - 1), n); 14 | 15 | // If middle element is not the peak and it's right neighbour is greater than it, then the right half must have a peak element 16 | else 17 | return findPeakElement(arr, (mid + 1), high, n); 18 | } 19 | int main() { 20 | int n = 4; 21 | int arr[] = { 1, 2, 3, 1}; 22 | cout << findPeakElement(arr, 0, n - 1, n) << endl; // Calling the function to print the index of peak element 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /34_Find Peak Element/Ideal Solutions/findPeakElement.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | 8 | //This function finds the peak element. 9 | public static int findPeakElement(int n,int[] arr){ 10 | int low = 0; 11 | int high = arr.length-1; 12 | while(low < high){ 13 | int mid = low + (high - low)/2; 14 | if (arr[mid] > arr[mid + 1]) high = mid; 15 | else{ 16 | low = mid + 1; 17 | } 18 | } 19 | return low; 20 | } 21 | 22 | //Main Function 23 | public static void main(String[] args){ 24 | int n = 4; 25 | int[] array = {1,2,3,1}; 26 | int ans = findPeakElement(n,array); 27 | System.out.println(ans); 28 | } 29 | } -------------------------------------------------------------------------------- /34_Find Peak Element/Ideal Solutions/findPeakElement.py: -------------------------------------------------------------------------------- 1 | def findPeakElement(array, N): 2 | 3 | # 1. Set left and right values 4 | left = 0 5 | right = N-1 6 | 7 | # 2. For Binary Search, we have to ensure the condition of left < right 8 | while left < right: 9 | 10 | # 2.1 Calculate mid 11 | mid = int((left + right)/2) 12 | 13 | # 2.2 check mid element is greater than forward neighbour. If True, Then Recur the left side of the array. 14 | if array[mid] > array[mid + 1]: 15 | right = mid 16 | 17 | # 2.3 check mid element is less than forward neighbour. If False, Then Recur the right side of the array. 18 | else: 19 | left = mid + 1 20 | 21 | return left 22 | 23 | 24 | if __name__ == "__main__": 25 | 26 | # Input 27 | array = [1, 2, 1, 3, 5, 6, 4] 28 | N = 7 29 | 30 | print(findPeakElement(array, N)) 31 | -------------------------------------------------------------------------------- /34_Find Peak Element/Problem Statement/findPeakElement.md: -------------------------------------------------------------------------------- 1 | # **Find Peak Element** 2 | A peak element is an element that is strictly greater than its neighbors. 3 | Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks. 4 | 5 | __Note__ : You may imagine that nums[-1] = nums[n] = -∞. 6 | 7 | 8 | #### **Sample Input** 9 | array = [1,2,3,1] 10 | #### **__Sample Output__** 11 | Output: 2 12 | 13 | ### **__Sample Explanation__** 14 | 3 is a peak element and your function should return the index number 2. 15 | 16 | ### **__Expected Time Complexity__** 17 | __O__(log(N)), where N is the size of the array 18 | 19 | #### **Expected Space Complexity** 20 | __O__(1), i.e., constant space complexity. 21 | 22 | #### **Constraints** 23 | 1 <= nums.length <= 1000 24 | -2^31 <= nums[i] <= 2^31 - 1 25 | nums[i] != nums[i + 1] for all valid i. 26 | -------------------------------------------------------------------------------- /35_Search in Rotated & Sorted Array/Ideal Solutions/rotatedSortedArraySearch.py: -------------------------------------------------------------------------------- 1 | def rotatedSortedArraySearch(nums, target): 2 | if not nums: return -1 3 | 4 | left = 0 5 | right = len(nums) - 1 6 | 7 | while left <= right: 8 | mid = left + (right - left) // 2 9 | 10 | if nums[mid] == target: 11 | return mid 12 | 13 | elif nums[mid] < nums[right]: 14 | if nums[mid] < target <= nums[right]: 15 | left = mid + 1 16 | else: 17 | right = mid - 1 18 | 19 | else: 20 | if nums[mid] > target >= nums[left]: 21 | right = mid - 1 22 | else: 23 | left = mid + 1 24 | 25 | return -1 26 | 27 | 28 | if __name__ == "__main__": 29 | 30 | # Input 31 | nums = [4, 5, 6, 7, 0, 1, 2] 32 | target = 0 33 | 34 | print(rotatedSortedArraySearch(nums, target)) 35 | -------------------------------------------------------------------------------- /35_Search in Rotated & Sorted Array/Ideal Solutions/searchInRotatedAndSortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function that returns the position of key in a sorted and rotated array 5 | 6 | int search(int arr[], int lo, int hi, int key){ 7 | 8 | if (lo > hi) 9 | return -1; 10 | 11 | int mid = (lo + hi) / 2; 12 | 13 | if (arr[mid] == key) 14 | return mid; 15 | 16 | if (arr[lo] <= arr[mid]) { 17 | 18 | if (key >= arr[lo] && key <= arr[mid]) 19 | return search(arr, lo, mid - 1, key); 20 | 21 | return search(arr, mid + 1, hi, key); 22 | } 23 | 24 | if (key >= arr[mid] && key <= arr[hi]) 25 | return search(arr, mid + 1, hi, key); 26 | 27 | return search(arr, lo, mid - 1, key); 28 | } 29 | 30 | 31 | int main(){ 32 | 33 | int N = 7; // Size of the array 34 | 35 | int arr[] = { 4, 5, 6, 7, 0, 1, 2 }; 36 | 37 | int key = 0; 38 | 39 | int idx = search(arr, 0, N - 1, key); 40 | 41 | cout << idx << endl; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /35_Search in Rotated & Sorted Array/Ideal Solutions/searchInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | class Main{ 6 | //This function finds out the index of a particular element if it exists, using binary search 7 | public static int searchInRotatedSortedArray(int[] arr,int low,int high,int k){ 8 | while(low <= high){ 9 | int mid = low + (high - low)/2; 10 | if (arr[mid] == k) return mid; 11 | else if (arr[mid] > k) high = mid - 1; 12 | else{ 13 | low = mid + 1; 14 | } 15 | } 16 | return -1; 17 | } 18 | //This function finds out the index at which the array is rotated. 19 | public static int findPivotIndex(int[] arr){ 20 | if (arr == null || arr.length == 0) return -1; 21 | if (arr.length == 0) return 0; 22 | if (arr[0] < arr[arr.length-1]) return 0; 23 | int low = 0; 24 | int high = arr.length-1; 25 | while(low <= high){ 26 | int mid = low + (high - low); 27 | if (arr[mid] < arr[high]) high = mid; 28 | else if (arr[mid] > arr[high]) low = mid + 1; 29 | else{ 30 | if (high != 0 && arr[high] >= arr[high - 1]) high--; 31 | else{ 32 | return high; 33 | } 34 | } 35 | } 36 | return low; 37 | } 38 | public static void main(String[] args){ 39 | int[] arr = {4,5,6,7,0,1,2}; 40 | int target = 0; 41 | int pivot = findPivotIndex(arr); 42 | int ans1 = searchInRotatedSortedArray(arr,0,pivot-1,target); 43 | int ans2 = searchInRotatedSortedArray(arr,pivot,arr.length-1,target); 44 | if (ans1 != -1) System.out.println(ans1); 45 | else if (ans2 != -1) System.out.println(ans2); 46 | else{ 47 | System.out.println(-1); 48 | } 49 | 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /35_Search in Rotated & Sorted Array/Problem Statement/searchInRotatedSortedArray.md: -------------------------------------------------------------------------------- 1 | ## **Search in Rotated Sorted Array** 2 | 3 | You are given an integer array nums sorted in ascending order (with distinct values), and an integer target. 4 | Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 5 | If target is found in the array return its index, otherwise, return -1. 6 | 7 | 8 | 9 | 10 | 11 | #### **Sample Input** 12 | nums = [4,5,6,7,0,1,2], target = 0 13 | 14 | 15 | 16 | #### **Sample Output** 17 | 4 18 | 19 | #### **Sample Explanation** 20 | In the array given in the sample test case, the target element 0 is stored at index 4. 21 | 22 | #### **Expected Time Complexity** 23 | __O__(log(N)), where N is the size of the array. 24 | #### **Expected Space Complexity** 25 | __O__(1),Auxilliary Space 26 | 27 | #### **Constraints** 28 | 1 <= nums.length <= 5000 29 | -10^4 <= nums[i] <= 10^4 30 | All values of nums are unique. nums is guaranteed to be rotated at some pivot. 31 | -10^4 <= target <= 10^4 32 | 33 | -------------------------------------------------------------------------------- /36_Minimum in Rotated & Sorted Array/Ideal Solutions/minRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minRotatedSortedArray(int arr[], int low, int high) 5 | { 6 | // Function to find minimum in rotated sorted array 7 | while (low < high) 8 | { 9 | int mid = low + (high - low) / 2; 10 | if (arr[mid] == arr[high]) 11 | high--; 12 | else if (arr[mid] > arr[high]) 13 | low = mid + 1; 14 | else 15 | high = mid; 16 | } 17 | return arr[high]; // Minimum Element in the array 18 | } 19 | int main() 20 | { 21 | int n = 7; // Size of the array 22 | int arr[] = {4,5,6,7,0,1,2}; // Elements of the array 23 | cout << minRotatedSortedArray(arr, 0, n - 1) << endl; 24 | return 0; 25 | } -------------------------------------------------------------------------------- /36_Minimum in Rotated & Sorted Array/Ideal Solutions/minRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | 2 | # Finding minimum element in a rotated array 3 | def findMin(array): 4 | left, right = 0, len(array) - 1 5 | 6 | while left < right - 1: 7 | middle = (left + right) // 2 8 | 9 | # Middle located within the left rotated part 10 | if array[middle] < array[left]: 11 | right = middle 12 | 13 | # Middle located within the right rotated part 14 | elif array[middle] > array[right]: 15 | left = middle 16 | 17 | # Middle is located between the left and right, its a correct increasing order. 18 | else: 19 | right = middle 20 | 21 | return array[left] if array[left] < array[right] else array[right] 22 | 23 | 24 | 25 | if __name__ == "__main__": 26 | array = [4, 5, 6, 7, 1, 2] 27 | print(findMin(array)) -------------------------------------------------------------------------------- /36_Minimum in Rotated & Sorted Array/Ideal Solutions/minimumInSorted&RotatedArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | 6 | class Main{ 7 | //This function finds the minimum element in a rotated & sorted array. 8 | public static int minimumInSortedRotatedArray(int[] arr){ 9 | if (arr == null || arr.length == 0) return -1; 10 | if (arr.length == 1) return arr[0]; 11 | int low = 0; 12 | int high = arr.length-1; 13 | if (arr[low] < arr[high]) return arr[low]; 14 | while(low <= high){ 15 | int mid = low + (high - low)/2; 16 | if (arr[mid] > arr[mid + 1]) return arr[mid + 1]; 17 | if (arr[mid] < arr[mid - 1]) return arr[mid]; 18 | if (arr[mid] > arr[low]) low = mid + 1; 19 | else{ 20 | high = mid - 1; 21 | } 22 | } 23 | return -1; 24 | } 25 | //Main Function 26 | public static void main(String[] args){ 27 | int[] arr = {1,2,3}; 28 | int ans = minimumInSortedRotatedArray(arr); 29 | System.out.println(ans); 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /36_Minimum in Rotated & Sorted Array/Problem Statement/minimumInSorted&RotatedArray.md: -------------------------------------------------------------------------------- 1 | ## **Minimum in Rotated Sorted Array** 2 | 3 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 4 | Find the minimum element. 5 | The array may contain duplicates. 6 | 7 | 8 | 9 | 10 | 11 | #### **Sample Input** 12 | array = [1,3,5] 13 | 14 | 15 | 16 | #### **Sample Output** 17 | 1 18 | 19 | #### **Sample Explanation** 20 | As evident from the array, 1 is the minimum element in the array 21 | 22 | #### **Expected Time Complexity** 23 | __O__(log(N)), where N is the size of the array. 24 | 25 | #### **Expected Space Complexity** 26 | __O__(1),Auxilliary Space 27 | 28 | #### **Constraints** 29 | 1 <= nums.length <= 5000 30 | -10^4 <= nums[i] <= 10^4 31 | All values of nums are unique. nums is guaranteed to be rotated at some pivot. 32 | -10^4 <= target <= 10^4 33 | 34 | -------------------------------------------------------------------------------- /37_Square Root of an Integer/Ideal Solution/squareRootOfAnInteger.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Returns floor square root of x using binary search 5 | 6 | int Sqrt(long long X){ 7 | 8 | if (X == 0 || X == 1) 9 | return X; 10 | 11 | int lo = 1, hi = X, ans; 12 | 13 | while (lo <= hi){ 14 | 15 | int mid = (lo + hi) / 2; 16 | 17 | // If x is a perfect square 18 | if (mid*mid == X) 19 | return mid; 20 | 21 | // if mid*mid is lesser than x then, 22 | // search for a better answer from mid+1 to hi 23 | 24 | if (mid*mid < X){ 25 | 26 | lo = mid + 1; 27 | ans = mid; 28 | } 29 | 30 | // Else the answer lies in a range lo to mid-1 31 | else 32 | hi = mid-1; 33 | } 34 | 35 | return ans; 36 | } 37 | 38 | 39 | int main(){ 40 | 41 | int X = 11; 42 | cout << Sqrt(X) << endl; 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /37_Square Root of an Integer/Ideal Solution/squareRootOfAnInteger.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.lang.*; 4 | 5 | class Main{ 6 | //This function find out the square root of an integer. 7 | public static int squareRoot(int n){ 8 | if (n == 0 || n == 1) return n; 9 | int low = 1; 10 | int high = n; 11 | int ans = 0; 12 | while(low <= high){ 13 | int mid = low + (high - low)/2; 14 | if (mid * mid == n) return mid; 15 | else if (mid * mid < n) { 16 | ans = mid; 17 | low = mid + 1; 18 | } 19 | else{ 20 | high = mid - 1; 21 | } 22 | } 23 | return ans; 24 | } 25 | //Main function 26 | public static void main(String[] args){ 27 | int n = 11; 28 | int ans = squareRoot(n); 29 | System.out.println(ans); 30 | 31 | } 32 | } -------------------------------------------------------------------------------- /37_Square Root of an Integer/Ideal Solution/squareRootOfInteger'.py: -------------------------------------------------------------------------------- 1 | # Finding the square root of integer using Binary search 2 | def squareRootOfInteger(X): 3 | low = 1 # Setting lower limit as 1 4 | high = X # Setting higher limit as X 5 | 6 | while low <= high: 7 | 8 | # Calculating mid 9 | mid = (low + high) // 2 10 | 11 | # If Square of mid lie Before the Number X, Then Our required square should be present in the forward direction 12 | if mid * mid <= X: 13 | low = mid + 1 14 | # If Square of mid lie after the Number X, Then Our required square should be present in the backward direction 15 | else: 16 | high = mid - 1 17 | 18 | return low - 1 19 | 20 | 21 | if __name__ == "__main__": 22 | # Static Input 23 | X = 11 24 | 25 | print(squareRootOfInteger(X)) 26 | -------------------------------------------------------------------------------- /37_Square Root of an Integer/Problem Statement/Square Root of an Integer.md: -------------------------------------------------------------------------------- 1 | ## **Square Root of an Integer** 2 | Given an integer x, find it’s square root. If x is not a perfect square, then return floor(√x). 3 | 4 | __Note__: In case X is not a perfect square, then we need to return the floor value of square root of x 5 | 6 | #### **Sample Input** 7 | X = 11 8 | 9 | #### **Sample Output** 10 | 3 11 | 12 | #### **Sample Explanation** 13 | The square root of 11 lies in between 3 and 4 so floor of the square root is 3 14 | 15 | #### **Expected Time Complexity** 16 | __O__(log(X)) 17 | #### **Expected Space Complexity** 18 | __O__(1), constant space solution 19 | 20 | #### **Constraints** 21 | 1<= X <= 10^18 22 | 23 | -------------------------------------------------------------------------------- /38_Painter's Partition Problem/Ideal Solutions/painterPartition.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | # Calculate Sum between two index 4 | def calculateSum(arr, intial, final): 5 | totalSum = 0 6 | 7 | for value in range(intial, final + 1): 8 | totalSum += arr[value] 9 | 10 | return totalSum 11 | 12 | 13 | # Painter Problem DP approach 14 | def painterPartition(arr, noOfPainters): 15 | noOfBoards = len(A) 16 | 17 | dpArray = [[0 for i in range(noOfBoards + 1)] 18 | for j in range(noOfPainters + 1)] 19 | 20 | # Base Case 21 | for i in range(1, noOfBoards + 1): 22 | dpArray[1][i] = calculateSum(arr, 0, i - 1) 23 | 24 | # Base Case 25 | for i in range(1, noOfPainters + 1): 26 | dpArray[i][1] = arr[0] 27 | 28 | # For Other Cells 29 | for row in range(2, noOfPainters + 1): 30 | for column in range(2, noOfBoards + 1): 31 | 32 | optimum = sys.maxsize 33 | 34 | for g in range(row, column + 1): 35 | optimum = min(optimum, max(dpArray[row - 1][g], 36 | calculateSum(arr, noOfPainters, column - 1))) 37 | 38 | dpArray[row][column] = optimum 39 | 40 | return dpArray[noOfPainters][noOfBoards] 41 | 42 | 43 | if __name__ == "__main__": 44 | # Static Input 45 | k = 2 46 | A = [10, 10, 10, 10] 47 | 48 | print(painterPartition(A, k)) 49 | -------------------------------------------------------------------------------- /38_Painter's Partition Problem/Ideal Solutions/painterPartitionProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to find maximum number of painters to paint the board in most_time 5 | 6 | int findPainters(int board[], int most_time, int n) { 7 | 8 | int s = 0, painters = 1; 9 | 10 | for (int i = 0; i < n; i++) { 11 | 12 | s += board[i]; 13 | 14 | if (s > most_time) { 15 | 16 | s = board[i]; 17 | painters++; 18 | } 19 | } 20 | 21 | return painters; 22 | } 23 | 24 | // Function to partition the board among painters 25 | 26 | int partition(int board[], int k, int n) { 27 | 28 | int s = 0, m = 0; 29 | 30 | for(int i = 0; i < n; i++){ 31 | 32 | m = max(m, board[i]); 33 | s += board[i]; 34 | } 35 | 36 | int low = m, high = s; 37 | 38 | while (low < high){ 39 | 40 | int mid = low + (high - low) / 2; 41 | 42 | int painters = findPainters(board, mid, n); 43 | 44 | if (painters <= k) high = mid; 45 | 46 | else low = mid + 1; 47 | } 48 | 49 | return low; 50 | } 51 | 52 | int main(){ 53 | 54 | int k = 2; // Number of painters 55 | 56 | int n = 4; // size of board 57 | 58 | int A[] = { 10, 10, 10, 10 }; 59 | 60 | cout<val){ 13 | sum = a[i]; 14 | count++; 15 | } 16 | } 17 | return count <= k ? true : false; 18 | } 19 | //This function finds the minimum time to paint all the boards. 20 | public static long paintersPartitionProblem(long[] arr,long low,long high,int k){ 21 | long ans = 0; 22 | while(low <= high){ 23 | long mid = low + (high - low)/2; 24 | if (checkIfPossible(arr,k,mid)){ 25 | ans = mid; 26 | high = mid - 1; 27 | }else{ 28 | low = mid + 1; 29 | } 30 | } 31 | return ans; 32 | } 33 | //Main Function 34 | public static void main(String[] args){ 35 | long arr[] = {10,10,10,10}; 36 | long low = 0; 37 | long high = 0; 38 | for (int i=0;i 2 | using namespace std; 3 | int maxProfit(int prices[], int N) { 4 | // Function to calculate maximum profit buy doing one buy and sell operation 5 | int cost = 0; 6 | int maxProfit = 0; 7 | if (N == 0) 8 | return 0; 9 | int minPrice = prices[0]; 10 | for (int i = 0; i < N; i++) 11 | { 12 | minPrice = min(minPrice, prices[i]); 13 | cost = prices[i] - minPrice; 14 | maxProfit = max(maxProfit, cost); 15 | } 16 | return maxProfit; 17 | } 18 | int main() { 19 | 20 | int N = 6; // Total number of days 21 | 22 | //Stock prices on consecutive days 23 | int prices[] = { 7, 1, 5, 3, 6, 4 }; 24 | cout << maxProfit(prices, N) << endl; 25 | return 0; 26 | } -------------------------------------------------------------------------------- /39_Best Time to Buy and Sell Stock/Ideal Solutions/bestTimeToBuySellStock.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.*; 3 | import java.lang.*; 4 | import java.util.*; 5 | 6 | 7 | class Main{ 8 | //This function implements the required function. 9 | public static int bestTimeToBuySellStock(int[] prices){ 10 | if (prices.length <= 1){ 11 | return 0; 12 | } 13 | int min = prices[0]; 14 | int max_diff = 0; 15 | for (int i=1;i max_diff){ 21 | max_diff = temp; 22 | } 23 | } 24 | return max_diff; 25 | } 26 | //Main Function 27 | public static void main(String[] args){ 28 | int[] prices = {7,1,5,3,6,4}; 29 | int ans = bestTimeToBuySellStock(prices); 30 | System.out.println(ans); 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /39_Best Time to Buy and Sell Stock/Ideal Solutions/bestTimeToBuySellStock.py: -------------------------------------------------------------------------------- 1 | def bestTimeToBuySellStock(prices): 2 | maximumProfit = 0 3 | minPurchase = prices[0] 4 | 5 | for index in range(1, len(prices)): 6 | if prices[index] - minPurchase > maximumProfit: 7 | maximumProfit = prices[index] - minPurchase 8 | 9 | if prices[index] < minPurchase: 10 | minPurchase = prices[index] 11 | 12 | return maximumProfit 13 | 14 | 15 | if __name__ == "__main__": 16 | 17 | # Static Input 18 | prices = [7, 1, 5, 3, 6, 4] 19 | 20 | print(bestTimeToBuySellStock(prices)) 21 | -------------------------------------------------------------------------------- /39_Best Time to Buy and Sell Stock/Problem Statement/bestTimeToBuyAndSellStock.md: -------------------------------------------------------------------------------- 1 | ## **Best Time to Buy and Sell Stock** 2 | 3 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 4 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 5 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 6 | 7 | 8 | 9 | #### **Sample Input** 10 | prices = [7,1,5,3,6,4] 11 | 12 | 13 | #### **Sample Output** 14 | 5 15 | 16 | #### **Sample Explanation** 17 | Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. 18 | 19 | #### **Expected Time Complexity** 20 | __O__(N),where N is the number of days. 21 | 22 | #### **Expected Space Complexity** 23 | __O__(1), constant space complexity. 24 | 25 | #### **Constraints** 26 | 1 <= prices.length <= 10^5 27 | 0 <= prices[i] <= 10^4 28 | 29 | -------------------------------------------------------------------------------- /40_Gas Stations/Ideal Solutions/gasStations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int gasStations(int gas[], int cost[], int n) { 4 | // Function to find the index of the starting gas station around the circuit once 5 | int totalDiff = 0, diff = 0; 6 | int index = 0; 7 | for (int i = 0; i < n; i++) { 8 | diff += gas[i] - cost[i]; 9 | totalDiff += gas[i] - cost[i]; 10 | if (diff < 0) { 11 | diff = 0; 12 | index = i + 1; 13 | } 14 | } 15 | if ((totalDiff >= 0)) 16 | return index; 17 | else 18 | return -1; 19 | } 20 | int main() { 21 | int n = 5; // Size of the array 22 | int gas[] = {1, 2, 3, 4, 5}; // Amount of gas on ith station 23 | int cost[] = {3, 4, 5, 1, 2}; // Cost to travel from ith to (i+1)th station 24 | cout << gasStations(gas, cost, n) << endl; 25 | return 0; 26 | } -------------------------------------------------------------------------------- /40_Gas Stations/Ideal Solutions/gasStations.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function calculates the possible starting point, or else returns -1. 8 | public static int gasStations(int[] gas,int[] cost){ 9 | int current_gas = 0; 10 | int total_gas = 0; 11 | int start = 0; 12 | for (int i=0;i= 0 ? start : -1; //If the total gas required is less than the total gas available at all the stations, then it will not be possible to complete a full circle. 21 | } 22 | 23 | //Main Function 24 | public static void main(String[] args){ 25 | int[] gas = {1,2,3,4,5}; 26 | int[] cost = {3,4,5,1,2}; 27 | int ans = gasStations(gas,cost); 28 | System.out.println(ans); 29 | 30 | } 31 | } -------------------------------------------------------------------------------- /40_Gas Stations/Ideal Solutions/gasStations.py: -------------------------------------------------------------------------------- 1 | def gasStations(gas, cost): 2 | 3 | gasSum = sum(gas) 4 | costSum = sum(cost) 5 | 6 | # Total Gas must be greater than Total cost .Only Then it is possible to travel 7 | if gasSum < costSum: 8 | return -1 9 | 10 | startStationIndex = 0 11 | fuel = 0 12 | gasStationLength = len(gas) 13 | 14 | for i in range(gasStationLength): 15 | if gas[i] + fuel < cost[i]: 16 | startStationIndex = i+1 17 | fuel = 0 18 | 19 | else: 20 | fuel += (gas[i]-cost[i]) 21 | 22 | return startStationIndex 23 | 24 | 25 | if __name__ == "__main__": 26 | 27 | # Input 28 | gas = [1, 2, 3, 4, 5] 29 | cost = [3, 4, 5, 1, 2] 30 | 31 | 32 | print(gasStations(gas, cost)) -------------------------------------------------------------------------------- /40_Gas Stations/Problem Statement/Gas Stations.md: -------------------------------------------------------------------------------- 1 | ## **Gas Stations** 2 | There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. 3 | 4 | __Note__: Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique 5 | 6 | #### **Sample Input** 7 | gas = [1,2,3,4,5] 8 | cost = [3,4,5,1,2] 9 | 10 | #### **Sample Output** 11 | 3 12 | 13 | #### **Sample Explanation** 14 | Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 15 | Travel to station 4. Your tank = 4 - 1 + 5 = 8 16 | Travel to station 0. Your tank = 8 - 2 + 1 = 7 17 | Travel to station 1. Your tank = 7 - 3 + 2 = 6 18 | Travel to station 2. Your tank = 6 - 4 + 3 = 5 19 | Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. 20 | Therefore, return 3 as the starting index. 21 | 22 | #### **Expected Time Complexity** 23 | __O__(N), where N is the length of the gas stations array 24 | #### **Expected Space Complexity** 25 | __O__(1), constant space solution 26 | 27 | #### **Constraints** 28 | gas.length == n 29 | cost.length == n 30 | 1 <= n <= 10^4 31 | 0 <= gas[i], cost[i] <= 10^4 32 | -------------------------------------------------------------------------------- /41_Meeting Rooms/Ideal Solutions/meetingRooms.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool meetingRooms(vector > intervals) 4 | { 5 | // Function to find out if it's possible to attend all meetings or not 6 | int n = intervals.size(); 7 | if(n==0) 8 | return true; 9 | sort(intervals.begin(),intervals.end()); 10 | for(int i = 1;i < n;i++) { 11 | int a = intervals[i-1][1]; 12 | int b = intervals[i][0]; 13 | if(a>b) 14 | return false; 15 | } 16 | return true; 17 | } 18 | int main(){ 19 | 20 | // Input of intervals in the form [start,end] 21 | vector > intervals { 22 | {0,30}, 23 | {5,10}, 24 | {15,20} }; 25 | bool result = meetingRooms(intervals); 26 | if(result) 27 | cout<<"true"<{ 7 | public int compare(int[] arr1,int[] arr2){ 8 | for (int i=0;i= ends[j]: 15 | overlap += 1 16 | j += 1 17 | 18 | # If Starts time is greater than ends time, That means time slot is not valid and can not hold a meeting 19 | else: 20 | overlap += 1 21 | current_max = max(current_max, overlap) 22 | i += 1 23 | 24 | # Current_max ensuring that one person can attend all meetings. If it is 2 , then it means 2 person needed to complete the attendance in all meetings. 25 | if current_max == 1: 26 | return True 27 | else: 28 | return False 29 | 30 | 31 | if __name__ == "__main__": 32 | 33 | # Static Input 34 | intervals = [[0, 4], [5, 20], [15, 20], [25, 30]] 35 | 36 | print(meetingRooms(intervals)) 37 | -------------------------------------------------------------------------------- /41_Meeting Rooms/Problem Statement/Meeting Rooms.md: -------------------------------------------------------------------------------- 1 | ## **Meeting Rooms** 2 | Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings. 3 | 4 | 5 | #### **Sample Input** 6 | intervals = [ [0,30], [5,10], [15,20] ] 7 | 8 | #### **Sample Output** 9 | false 10 | 11 | #### **Sample Explanation** 12 | Two or more meetings are overlapping, so the person cannot attend all the meetings. 13 | 14 | #### **Expected Time Complexity** 15 | __O__(N*logN), where N is the length of the intervals array 16 | #### **Expected Space Complexity** 17 | __O__(1), constant space solution 18 | 19 | #### **Constraints** 20 | 0 <= intervals.length <= 10^4 21 | intervals[i].length == 2 22 | 0 <= starti < endi <= 10^6 23 | 24 | -------------------------------------------------------------------------------- /42_Longest Common Subsequence/Ideal Solutions/longestCommonSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int M = 1010; 5 | 6 | int longestCommonSubsequence(string X, string Y, int m, int n, int dp[][M]) { 7 | // Function to calculate the longest common subsequence of two strings 8 | // Base case 9 | if (m == 0 || n == 0) 10 | return 0; 11 | 12 | // Already Computed state 13 | if (dp[m - 1][n - 1] != -1) 14 | return dp[m - 1][n - 1]; 15 | 16 | if (X[m - 1] == Y[n - 1]) { 17 | return dp[m - 1][n - 1] = 1 + longestCommonSubsequence(X, Y, m - 1, n - 1, dp); 18 | } 19 | else { 20 | return dp[m - 1][n - 1] = max(longestCommonSubsequence(X, Y, m, n - 1, dp), longestCommonSubsequence(X, Y, m - 1, n, dp)); 21 | } 22 | } 23 | 24 | // Driver Code 25 | int main() { 26 | 27 | string X = "abcde"; 28 | string Y = "ace"; 29 | int m = X.length(), n = Y.length(); 30 | 31 | int dp[max(m, n)][M]; 32 | 33 | // assign -1 to all positions 34 | memset(dp, -1, sizeof(dp)); 35 | 36 | cout << longestCommonSubsequence(X, Y, m, n, dp) << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /42_Longest Common Subsequence/Ideal Solutions/longestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function calculates the longest common subsequence between the two strings. 8 | public static int longestCommonSubsequence( char[] arr1, char[] arr2){ 9 | int m = arr1.length; 10 | int n = arr2.length; 11 | int dp[][] = new int[m+1][n+1]; 12 | for (int i=0; i<=m; i++){ 13 | for (int j=0; j<=n; j++){ 14 | if (i == 0 || j == 0) 15 | dp[i][j] = 0; 16 | else if (arr1[i-1] == arr2[j-1]) 17 | dp[i][j] = dp[i-1][j-1] + 1; 18 | else 19 | dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); 20 | } 21 | } 22 | return dp[m][n]; 23 | } 24 | //Main function 25 | public static void main(String[] args){ 26 | String s1 = "abcde"; 27 | String s2 = "ace"; 28 | char[] arr1=s1.toCharArray(); 29 | char[] arr2=s2.toCharArray(); 30 | int ans = longestCommonSubsequence(arr1,arr2); 31 | System.out.println(ans); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /42_Longest Common Subsequence/Ideal Solutions/longestCommonSubsequence.py: -------------------------------------------------------------------------------- 1 | 2 | # Finding Longest Subsequence between two sequences 3 | def longestCommonSubsequence(sequenceFirst, sequenceSecond): 4 | 5 | # Declare 2D DP array of size first string and second string 6 | longestSubsequence = [[0 for i in range(len(sequenceSecond) + 1)] for j in range(len(sequenceFirst) + 1)] 7 | 8 | # Appending Space at beginning , So that loop will begin from 1st index 9 | sequenceFirst = " " + sequenceFirst 10 | sequenceSecond = " " + sequenceSecond 11 | 12 | # loop through both sequence 13 | for row in range(1, len(sequenceFirst)): 14 | for column in range(1, len(sequenceSecond)): 15 | 16 | # If Char matches then, add 1 to total combinations 17 | if sequenceFirst[row] == sequenceSecond[column]: 18 | longestSubsequence[row][column] = 1 + longestSubsequence[row-1][column-1] 19 | 20 | # If not matches then, take max of both remaining subsequence 21 | else: 22 | longestSubsequence[row][column] = max(longestSubsequence[row-1][column], longestSubsequence[row][column-1]) 23 | 24 | return longestSubsequence[-1][-1] 25 | 26 | 27 | if __name__ == "__main__": 28 | 29 | # Static Input 30 | text1 = "abcde" 31 | text2 = "ace" 32 | 33 | print(longestCommonSubsequence(text1, text2)) 34 | -------------------------------------------------------------------------------- /42_Longest Common Subsequence/Problem Statement/longestCommonSubsequence.md: -------------------------------------------------------------------------------- 1 | ## **Longest Common Subsequence** 2 | 3 | Given two strings text1 and text2, return the length of their longest common subsequence. 4 | 5 | A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings. 6 | 7 | 8 | 9 | If there is no common subsequence, return 0. 10 | 11 | 12 | #### **Sample Input** 13 | text1 = "abcde", text2 = "ace" 14 | 15 | #### **Sample Output** 16 | 3 17 | 18 | #### **Sample Explanation** 19 | The longest common subsequence is "ace" and its length is 3. 20 | 21 | 22 | #### **Expected Time Complexity** 23 | __O__(M * N), where M and N are the length of the two Strings 24 | 25 | 26 | #### **Expected Space Complexity** 27 | __O__(M * N). Auxillary Space. 28 | 29 | #### **Constraints** 30 | 1 <= length(N) <= 1000 31 | 1 <= length(M) <= 1000 32 | -------------------------------------------------------------------------------- /43_Longest Increasing Subsequence/Editorial/Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2/LISEqn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/43_Longest Increasing Subsequence/Editorial/Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2/LISEqn.png -------------------------------------------------------------------------------- /43_Longest Increasing Subsequence/Editorial/Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2/LongestSubTree.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/43_Longest Increasing Subsequence/Editorial/Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2/LongestSubTree.jpg -------------------------------------------------------------------------------- /43_Longest Increasing Subsequence/Editorial/Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2/includeExclude.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/43_Longest Increasing Subsequence/Editorial/Longest Increasing Subsequence - Editorial 355e0d4002fa4fd1883260e0cbd30dc2/includeExclude.jpg -------------------------------------------------------------------------------- /43_Longest Increasing Subsequence/Ideal Solutions/longestIncreasingSubsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int longestIncreasingSubsequence(int n, int arr[]) { 4 | // Function to find the Longest Increasing Subsequence of the given sequence 5 | int dp[n + 1]; 6 | 7 | // Every Element is LIS on it's own so setting value of dp to be 1 8 | for (int i = 0; i <= n; i++) 9 | dp[i] = 1; 10 | 11 | for (int i = 0; i < n; i++) { 12 | for (int j = i; j < n; j++) { 13 | if (arr[j] > arr[i]) 14 | dp[j] = max(dp[i] + 1, dp[j]); 15 | } 16 | } 17 | int result = 0; 18 | for (int i = 0; i < n; i++) { 19 | result = max(result, dp[i]); 20 | } 21 | return result; 22 | } 23 | int main() { 24 | int n = 9; 25 | int arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80}; 26 | cout << longestIncreasingSubsequence(n, arr) << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /43_Longest Increasing Subsequence/Ideal Solutions/longestIncreasingSubsequence.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | 6 | class Main{ 7 | //This function finds out the longest Increasing subsequence in an array. 8 | public static int longestIncreasingSubsequence(int[] arr,int n){ 9 | int[] dp = new int[n + 1]; 10 | Arrays.fill(dp,1); 11 | for (int i=0;i arr[i]) dp[j] = Math.max(dp[i] + 1, dp[j]); 14 | } 15 | } 16 | int max = 0; 17 | for (int i=0;i= 0 and right < lengthOfString and str[left] == str[right]: 3 | left -= 1 4 | right += 1 5 | return str[left + 1 : right] 6 | 7 | 8 | def longestPalindromeSubstring(str): 9 | result = "" 10 | lengthOfString = len(str) 11 | 12 | for index in range(lengthOfString): 13 | result = max(expandAroundCenter(index, index, lengthOfString, str), expandAroundCenter(index, index+1, lengthOfString, str), result, key=len) 14 | 15 | return result 16 | 17 | 18 | if __name__ == "__main__": 19 | 20 | # Input 21 | str = "xyzasisayzx" 22 | 23 | print(longestPalindromeSubstring(str)) 24 | -------------------------------------------------------------------------------- /44_Longest Palindromic Substring/Ideal Solutions/longestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void longestPalindromicSubstring(string str) { 5 | // Function to calculate longest palindromic substring 6 | int maxLength = 1; 7 | int start = 0; 8 | int len = str.length(); 9 | int low, high; 10 | for (int i = 1; i < len; ++i) { 11 | low = i - 1; 12 | high = i; 13 | while (low >= 0 && high < len && str[low] == str[high]) { 14 | if (high - low + 1 > maxLength) { 15 | start = low; 16 | maxLength = high - low + 1; 17 | } 18 | low--; 19 | high++; 20 | } 21 | low = i - 1; 22 | high = i + 1; 23 | while (low >= 0 && high < len && str[low] == str[high]) { 24 | if (high - low + 1 > maxLength) { 25 | start = low; 26 | maxLength = high - low + 1; 27 | } 28 | low--; 29 | high++; 30 | } 31 | } 32 | // maxLength is the length of the longest palindromic substring 33 | 34 | // Printing the longest palindromic substring 35 | for (int i = start; i <= start + maxLength - 1; i++) 36 | cout << str[i]; 37 | cout << endl; 38 | } 39 | int main() { 40 | int N = 11; // Size of the String 41 | string str = "xyzasisayzx"; 42 | longestPalindromicSubstring(str); 43 | return 0; 44 | } -------------------------------------------------------------------------------- /44_Longest Palindromic Substring/Problem Statement/longestPalindromicSubstring.md: -------------------------------------------------------------------------------- 1 | ## **Longest Palindromic Substring** 2 | Given a string of length N. Find the longest substring which is palindrome. 3 | 4 | #### **Sample Input** 5 | input: N = 11, string: xyzasisayzx 6 | 7 | #### **Sample Output** 8 | Output: asisa 9 | 10 | #### **Sample Explanation** 11 | Self explanatory. 12 | 13 | #### **Expected Time Complexity** 14 | __O__(N*N), where N is the size of the string 15 | 16 | #### **Expected Space Complexity** 17 | __O__(N*N) 18 | 19 | #### **Constraints** 20 | 1 <= N <= 1000 21 | -------------------------------------------------------------------------------- /45_Minimum Jumps To Reach The End/Editorials/Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a/OptimizeArray.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/45_Minimum Jumps To Reach The End/Editorials/Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a/OptimizeArray.jpg -------------------------------------------------------------------------------- /45_Minimum Jumps To Reach The End/Editorials/Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a/Org_Chart_(1).jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/45_Minimum Jumps To Reach The End/Editorials/Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a/Org_Chart_(1).jpg -------------------------------------------------------------------------------- /45_Minimum Jumps To Reach The End/Editorials/Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a/timeComplexity.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/45_Minimum Jumps To Reach The End/Editorials/Minimum Jumps - Editorial 28b57b66a1664ee0864f2fa34bd67b1a/timeComplexity.jpg -------------------------------------------------------------------------------- /45_Minimum Jumps To Reach The End/Ideal Solutions/minJumpsToEnd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int minJumpsToEnd(int arr[], int n) { 4 | // Function to calculate Min jumps to reach end 5 | int jumps[n + 1]; 6 | 7 | if (n == 0 || arr[0] == 0) // Corner Case 8 | return INT_MAX; 9 | 10 | jumps[0] = 0; 11 | for (int i = 1; i < n; i++) { 12 | jumps[i] = INT_MAX; 13 | for (int j = 0; j < i; j++) { 14 | if (i <= j + arr[j] && jumps[j] != INT_MAX) { 15 | jumps[i] = min(jumps[i], jumps[j] + 1); 16 | break; 17 | } 18 | } 19 | } 20 | return jumps[n - 1]; 21 | } 22 | int main() { 23 | int n = 5; // Size of Array 24 | int arr[] = {2, 3, 1, 1, 4}; 25 | cout << minJumpsToEnd(arr, n)< currentDistance: 16 | 17 | # Max Distance should be keep track 18 | currentDistance = maxDistance 19 | 20 | # Keeping track of Steps Count 21 | countSteps += 1 22 | 23 | # Keeping track what is the max distance we can reach from all the past current position 24 | maxDistance = max(maxDistance, index+jumps[index]) 25 | 26 | return countSteps 27 | 28 | 29 | if __name__ == "__main__": 30 | 31 | # input 32 | jumps = [2, 3, 1, 1, 4] 33 | 34 | print(minJumpsToEnd(jumps)) -------------------------------------------------------------------------------- /45_Minimum Jumps To Reach The End/Ideal Solutions/minJumpsToTheEnd.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | import java.lang.*; 4 | 5 | 6 | class Main{ 7 | //This function returns the minimum number of jumps to reach the end of the array. 8 | public static int minJumpsToEnd(int[] array){ 9 | int[] dp = new int[array.length]; 10 | Arrays.fill(dp,Integer.MAX_VALUE); 11 | dp[0] = 0; 12 | for (int i=0;i 2 | using namespace std; 3 | int maximumSumSubarray(int n, int arr[]) { 4 | // Function to calculate the maximum sum of a subarray 5 | int currentMax = 0, globalMax = INT_MIN; 6 | for (int i = 0; i < n; i++) { 7 | currentMax += arr[i]; 8 | if (currentMax > globalMax) 9 | globalMax = currentMax; 10 | if (currentMax < 0) 11 | currentMax = 0; 12 | } 13 | return globalMax; 14 | } 15 | int main() { 16 | int n = 8; // Size of the array 17 | int arr[] = {2, -3, 4, -1, -2, 1, 5, -3}; 18 | cout << maximumSumSubarray(n, arr) << endl; 19 | return 0; 20 | }; 21 | -------------------------------------------------------------------------------- /46_Maximum_Sum_Subarray/Ideal Solutions/maximumSumSubarray.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function calculates the maximum sum of a subarray, for a given array. 8 | public static int maximumSumSubarray(int[] arr){ 9 | int max_so_far = Integer.MIN_VALUE; 10 | int max_ending_here = 0; 11 | for (int i = 0;i 2 | using namespace std; 3 | 4 | int moneyAndShopping(int arr[][3], int N) 5 | { 6 | // Function to find minimum shopping money spent using the mentioned method 7 | int dp[N][3]; 8 | dp[0][0] = arr[0][0]; 9 | dp[0][1] = arr[0][1]; 10 | dp[0][2] = arr[0][2]; 11 | for (int i = 1; i < N; i++) { 12 | 13 | dp[i][0] = arr[i][0] + min(dp[i - 1][1], dp[i - 1][2]); 14 | dp[i][1] = arr[i][1] + min(dp[i - 1][0], dp[i - 1][2]); 15 | dp[i][2] = arr[i][2] + min(dp[i - 1][0], dp[i - 1][1]); 16 | } 17 | return min({dp[N - 1][0], dp[N - 1][1], dp[N - 1][2]}); 18 | } 19 | int main() 20 | { 21 | int N = 3; // Number of shops 22 | int arr[N][3] = { {1, 50, 50}, 23 | {50, 50, 50}, 24 | {1, 50, 50} 25 | }; // Elements of the array representing prices of items in shop 26 | cout << moneyAndShopping(arr, N) << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /47_Money and Shopping/Ideal Solutions/moneyAndShopping.py: -------------------------------------------------------------------------------- 1 | 2 | # Money and Shopping Problem 3 | def moneyAndShopping(arr, N): 4 | dp = [[0] * N for _ in range(3)] 5 | dp[0][0] = arr[0][0] 6 | dp[0][1] = arr[0][1] 7 | dp[0][2] = arr[0][2] 8 | 9 | 10 | for i in range(0 ,N): 11 | dp[i][0] = arr[i][0] + min(dp[i - 1][1], dp[i - 1][2]) 12 | dp[i][1] = arr[i][1] + min(dp[i - 1][0], dp[i - 1][2]) 13 | dp[i][2] = arr[i][2] + min(dp[i - 1][0], dp[i - 1][1]) 14 | 15 | return min(dp[N - 1][0], dp[N - 1][1], dp[N - 1][2]) 16 | 17 | 18 | 19 | if __name__ == "__main__": 20 | # input 21 | N = 3 22 | arr = [[1, 50, 50], 23 | [50, 50, 50], 24 | [1, 50, 50]] 25 | 26 | print(moneyAndShopping(arr, N)) 27 | -------------------------------------------------------------------------------- /47_Money and Shopping/Problem Statement/money&Shopping.md: -------------------------------------------------------------------------------- 1 | ## **Money and Shopping** 2 | 3 | Alice is in a shopping mall to buy books, shirts and shoes. The mall has exactly N different shops and each shop contains all these three items at different prices. Alice has a plan which she will be following. As per her plan, she won't buy the same item from the current shop if she had already bought that item from the shop adjacent to the current shop. 4 | 5 | Alice wants to follow her strategy strictly but at the same time she wants to minimize the total money she spends on shopping. You are provided description about all N shops i.e costs of all three items in each shop. You need to help Alice find minimum money that she needs to spend such that she buys exactly one item from every shop. 6 | 7 | 8 | 9 | #### **Sample Input** 10 | 3 11 | 1 50 50 12 | 50 50 50 13 | 1 50 50 14 | 15 | 16 | #### **Sample Output** 17 | 52 18 | 19 | #### **Sample Explanation** 20 | Since Alice has to buy atleast one artifact from every shop, and the overall cost has to be minimum, so she buys artifact with cost 1 form the first shop, artifact of cost 50 from the second shop, and artifact of cost 1 from the last shop, making the overall cost to be 52. 21 | 22 | #### **Expected Time Complexity** 23 | __O__(N),where N is the number of shops. 24 | 25 | #### **Expected Space Complexity** 26 | __O__(N^3), where N is the number of shops. 27 | 28 | #### **Constraints** 29 | 1 ≤ T ≤ 10 30 | 1 ≤ N ≤ 100000 31 | Cost of each item (book/shirt/shoe) does not exceed 10000 32 | 33 | 34 | -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Ideal Solutions/Ideal Solutions/zeroOneKnapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int dp[2005][2005]; // using dp array to store values of overlapping sub-problems, also we are using top-down recursive approach 4 | 5 | int zeroOneKnapsack(int N, int W, int value [], int weight []) { 6 | // helper function to calculate the maximum value of knapsack 7 | if(N <= 0|| W <= 0) 8 | return 0; 9 | if(dp[N][W]!=-1) 10 | return dp[N][W]; 11 | if(W - weight[N-1] < 0) 12 | return dp[N][W] = zeroOneKnapsack(N-1, W, value, weight); 13 | return dp[N][W] = max( zeroOneKnapsack(N-1, W, value, weight), value[N-1] + zeroOneKnapsack(N-1, W - weight[N-1], value, weight) ); 14 | } 15 | int main() { 16 | // Taking the Sample Input Values 17 | int N = 3; 18 | int value[] = { 60, 100, 120 }; 19 | int weight[] = { 10, 20, 30 }; 20 | int W = 50; 21 | 22 | memset(dp, -1, sizeof(dp)); // setting the values of dp array to -1 23 | int result = zeroOneKnapsack(N, W, value, weight); 24 | 25 | cout << result << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Ideal Solutions/Ideal Solutions/zeroOneKnapsack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | 6 | class Main { 7 | //This function returns the maximum value that we can, without exceeding the capacity of the KnapSack 8 | public static int zeroOneKnapSack(int W, int weight[], int value[], int n){ 9 | if (n == 0 || W == 0) return 0; 10 | if (weight[n - 1] > W) return zeroOneKnapSack(W, weight, value, n - 1); 11 | else{ 12 | return Math.max(value[n - 1]+ zeroOneKnapSack(W - weight[n - 1], weight,value, n - 1),zeroOneKnapSack(W, weight, value, n - 1)); 13 | } 14 | } 15 | //Main Function 16 | public static void main(String args[]){ 17 | int value[] = new int[] { 60, 100, 120 }; 18 | int weight[] = new int[] { 10, 20, 30 }; 19 | int W = 50; 20 | int n = value.length; 21 | System.out.println(zeroOneKnapSack(W, weight, value, n)); 22 | } 23 | } -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Ideal Solutions/Ideal Solutions/zeroOneKnapsack.py: -------------------------------------------------------------------------------- 1 | def zeroOneKnapsack(weight, value, W, noOfItems, knapsackDP): 2 | if noOfItems == 0 or W == 0: 3 | return 0 4 | 5 | # If this Value is already computed , then don't compute it anr return the already calculated value 6 | if knapsackDP[noOfItems][W] != -1: 7 | return knapsackDP[noOfItems][W] 8 | 9 | # If current Item wait is less than W, Then we have two choices 10 | # 1. Include it 11 | # 2. Exclude it 12 | # Take max of both of it 13 | if weight[noOfItems - 1] <= W: 14 | knapsackDP[noOfItems][W] = max( 15 | value[noOfItems - 1] + zeroOneKnapsack(weight, value, W - weight[noOfItems - 1], noOfItems - 1, knapsackDP), 16 | zeroOneKnapsack(weight, value, W, noOfItems - 1, knapsackDP)) 17 | 18 | # If current Item wait is greater than W, Then we have only one choice 19 | # Skip it and move forward 20 | else: 21 | knapsackDP[noOfItems][W] = zeroOneKnapsack(weight, value, W, noOfItems - 1, knapsackDP) 22 | 23 | return knapsackDP[noOfItems][W] 24 | 25 | 26 | if __name__ == "__main__": 27 | 28 | # Input 29 | value = [60, 100, 120] 30 | weight = [10, 20, 30] 31 | W = 50 32 | noOfItems = len(value) 33 | 34 | # Initialize 2D DP array 35 | knapsackDP = [[-1 for i in range(W + 1)] for j in range(noOfItems + 1)] 36 | 37 | print(zeroOneKnapsack(weight, value, W, noOfItems, knapsackDP)) 38 | -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Ideal Solutions/Problem Statement/0-1KnapsackProblem.md: -------------------------------------------------------------------------------- 1 | ## **0-1 Knapsack Problem** 2 | 3 | Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property). 4 | 5 | 6 | 7 | #### **Sample Input** 8 | value = {60,100,120} 9 | weight = {10,20,30} 10 | W = 50 11 | 12 | #### **Sample Output** 13 | 220 14 | 15 | #### **Sample Explanation** 16 | In the sample test case, without exceeding the capacity of the knapsack, we can add weights with 20 and 30. Therefore, the value will be 50. 17 | 18 | #### **Expected Time Complexity** 19 | __O__(N * W). where ‘N’ is the number of weight element and ‘W’ is capacity. 20 | 21 | 22 | #### **Expected Space Complexity** 23 | __O__(N * W), where ‘N’ is the number of weight element and ‘W’ is capacity. 24 | 25 | 26 | #### **Constraints** 27 | 1 <= N <= 2000 28 | 1 <= W <= 2000 29 | 1 <= value[i],weight[i] <= 1000 30 | -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Ideal Solutions/zeroOneKnapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int dp[2005][2005]; // using dp array to store values of overlapping sub-problems, also we are using top-down recursive approach 4 | 5 | int zeroOneKnapsack(int N, int W, int value [], int weight []) { 6 | // helper function to calculate the maximum value of knapsack 7 | if(N <= 0|| W <= 0) 8 | return 0; 9 | if(dp[N][W]!=-1) 10 | return dp[N][W]; 11 | if(W - weight[N-1] < 0) 12 | return dp[N][W] = zeroOneKnapsack(N-1, W, value, weight); 13 | return dp[N][W] = max( zeroOneKnapsack(N-1, W, value, weight), value[N-1] + zeroOneKnapsack(N-1, W - weight[N-1], value, weight) ); 14 | } 15 | int main() { 16 | // Taking the Sample Input Values 17 | int N = 3; 18 | int value[] = { 60, 100, 120 }; 19 | int weight[] = { 10, 20, 30 }; 20 | int W = 50; 21 | 22 | memset(dp, -1, sizeof(dp)); // setting the values of dp array to -1 23 | int result = zeroOneKnapsack(N, W, value, weight); 24 | 25 | cout << result << endl; 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Ideal Solutions/zeroOneKnapsack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | 6 | class Main { 7 | //This function returns the maximum value that we can, without exceeding the capacity of the KnapSack 8 | public static int zeroOneKnapSack(int W, int weight[], int value[], int n){ 9 | if (n == 0 || W == 0) return 0; 10 | if (weight[n - 1] > W) return zeroOneKnapSack(W, weight, value, n - 1); 11 | else{ 12 | return Math.max(value[n - 1]+ zeroOneKnapSack(W - weight[n - 1], weight,value, n - 1),zeroOneKnapSack(W, weight, value, n - 1)); 13 | } 14 | } 15 | //Main Function 16 | public static void main(String args[]){ 17 | int value[] = new int[] { 60, 100, 120 }; 18 | int weight[] = new int[] { 10, 20, 30 }; 19 | int W = 50; 20 | int n = value.length; 21 | System.out.println(zeroOneKnapSack(W, weight, value, n)); 22 | } 23 | } -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Ideal Solutions/zeroOneKnapsack.py: -------------------------------------------------------------------------------- 1 | def zeroOneKnapsack(weight, value, W, noOfItems, knapsackDP): 2 | if noOfItems == 0 or W == 0: 3 | return 0 4 | 5 | # If this Value is already computed , then don't compute it anr return the already calculated value 6 | if knapsackDP[noOfItems][W] != -1: 7 | return knapsackDP[noOfItems][W] 8 | 9 | # If current Item wait is less than W, Then we have two choices 10 | # 1. Include it 11 | # 2. Exclude it 12 | # Take max of both of it 13 | if weight[noOfItems - 1] <= W: 14 | knapsackDP[noOfItems][W] = max( 15 | value[noOfItems - 1] + zeroOneKnapsack(weight, value, W - weight[noOfItems - 1], noOfItems - 1, knapsackDP), 16 | zeroOneKnapsack(weight, value, W, noOfItems - 1, knapsackDP)) 17 | 18 | # If current Item wait is greater than W, Then we have only one choice 19 | # Skip it and move forward 20 | else: 21 | knapsackDP[noOfItems][W] = zeroOneKnapsack(weight, value, W, noOfItems - 1, knapsackDP) 22 | 23 | return knapsackDP[noOfItems][W] 24 | 25 | 26 | if __name__ == "__main__": 27 | 28 | # Input 29 | value = [60, 100, 120] 30 | weight = [10, 20, 30] 31 | W = 50 32 | noOfItems = len(value) 33 | 34 | # Initialize 2D DP array 35 | knapsackDP = [[-1 for i in range(W + 1)] for j in range(noOfItems + 1)] 36 | 37 | print(zeroOneKnapsack(weight, value, W, noOfItems, knapsackDP)) 38 | -------------------------------------------------------------------------------- /48_0-1 Knapsack Problem/Problem Statement/01knapsackProblem.md: -------------------------------------------------------------------------------- 1 | ## **0-1 Knapsack Problem** 2 | 3 | Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or don’t pick it (0-1 property). 4 | 5 | 6 | 7 | #### **Sample Input** 8 | value = {60,100,120} 9 | weight = {10,20,30} 10 | W = 50 11 | 12 | #### **Sample Output** 13 | 220 14 | 15 | #### **Sample Explanation** 16 | In the sample test case, without exceeding the capacity of the knapsack, we can add weights with 20 and 30. Therefore, the value will be 50. 17 | 18 | #### **Expected Time Complexity** 19 | __O__(N * W). where ‘N’ is the number of weight element and ‘W’ is capacity. 20 | 21 | 22 | #### **Expected Space Complexity** 23 | __O__(N * W), where ‘N’ is the number of weight element and ‘W’ is capacity. 24 | 25 | 26 | #### **Constraints** 27 | 1 <= N <= 2000 28 | 1 <= W <= 2000 29 | 1 <= value[i],weight[i] <= 1000 30 | -------------------------------------------------------------------------------- /49_Coin Change Problem/Editorial/Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8/Psuedo_Code_Coin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/49_Coin Change Problem/Editorial/Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8/Psuedo_Code_Coin.png -------------------------------------------------------------------------------- /49_Coin Change Problem/Editorial/Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8/breaking_CoinChange.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/49_Coin Change Problem/Editorial/Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8/breaking_CoinChange.png -------------------------------------------------------------------------------- /49_Coin Change Problem/Editorial/Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8/coinChange_recrrence.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/49_Coin Change Problem/Editorial/Coin Change Problem - Editorial d9a49c0a05574afb85e805610d9f68e8/coinChange_recrrence.png -------------------------------------------------------------------------------- /49_Coin Change Problem/Ideal Solutions/coinChange.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int coinChange(int n, int amount, int coins[]) { 4 | // Function to calculate minimum number of coins required to form the amount 5 | 6 | vector dp(amount + 1, INT_MAX); // dp vector to store minimum coins needed to make each smaller or sub amount less than the target amount 7 | 8 | dp[0] = 0; // If amount is 0 , no coin is needed 9 | 10 | for (int i = 1; i <= amount; i++) { 11 | for (int j = 0; j < n; j++) { 12 | if (coins[j] <= i) { 13 | 14 | int subAnswer = dp[i - coins[j]]; 15 | 16 | if (subAnswer != INT_MAX && subAnswer + 1 < dp[i]) 17 | dp[i] = subAnswer + 1; 18 | } 19 | } 20 | } 21 | if (dp[amount] != INT_MAX) 22 | return dp[amount]; 23 | return -1; 24 | } 25 | int main() { 26 | int N = 3; // Number of coins 27 | int amount = 11; // Total amount of money 28 | int coins[] = {1, 2, 5}; 29 | int ans = coinChange(N, amount, coins); 30 | cout << ans << endl; 31 | } -------------------------------------------------------------------------------- /49_Coin Change Problem/Ideal Solutions/coinChange.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function finds the minimum number of coins required to make an amount else returns -1. 8 | public static int coinChange(int[] coins,int amount){ 9 | Arrays.sort(coins); 10 | int[] dp = new int[amount+1]; 11 | Arrays.fill(dp,amount+1); 12 | dp[0] = 0; 13 | for (int i=1;i<=amount;i++){ 14 | for (int j=0;j targetSum: 13 | subsetSum[n][targetSum] = subsetProblem(array, n-1, targetSum, subsetSum) 14 | return subsetSum[n][targetSum] 15 | 16 | # We have two choices. Wither we can include or exclude it. 17 | exclude = subsetProblem(array, n-1, targetSum, subsetSum) 18 | include = subsetProblem(array, n-1, targetSum-array[n-1], subsetSum) 19 | 20 | # Store the values in DP array 21 | subsetSum[n][targetSum] = exclude or include 22 | 23 | return subsetSum[n][targetSum] 24 | 25 | 26 | if __name__ == "__main__": 27 | 28 | # Static Input 29 | X = 11 30 | array = [3, 34, 4, 12, 5, 2] 31 | n = len(array) 32 | targetSum = 16 33 | 34 | # Creating 2D DP array 35 | subsetSum = [[-1 for i in range(targetSum+1)] for j in range(n+1)] 36 | 37 | print(subsetProblem(array, n, targetSum, subsetSum)) 38 | -------------------------------------------------------------------------------- /50_Subset Sum Problem/Ideal Solutions/subsetSumProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int dp[2000][2000]; 5 | 6 | // Function to check if any subset with given sum exists or not 7 | 8 | int subsetSum(int arr[], int N, int sum){ 9 | 10 | // If sum is 0, there always exists an empty subset 11 | if (sum == 0) 12 | return 1; 13 | 14 | // If array is empty only a single subset with sum zero is possible 15 | if (N <= 0) 16 | return 0; 17 | 18 | // If a subset with given sum already exists 19 | 20 | if (dp[N - 1][sum] != -1) 21 | return dp[N - 1][sum]; 22 | 23 | // If arr[N-1] > sum, it can never be a part of the subset 24 | 25 | if (arr[N - 1] > sum) 26 | return dp[N - 1][sum] = subsetSum(arr, N - 1, sum); 27 | 28 | //Else arr[N - 1] may be or may not be the part of subset with given sum 29 | else{ 30 | 31 | return dp[N - 1][sum] = subsetSum(arr, N - 1, sum) || 32 | subsetSum(arr, N - 1, sum - arr[N - 1]); 33 | } 34 | } 35 | 36 | int main(){ 37 | 38 | // initialising the dp table with value -1. 39 | memset(dp, -1, sizeof(dp)); 40 | 41 | int N = 6; 42 | 43 | int arr[] = {3, 34, 4, 12, 5, 2}; 44 | 45 | int sum = 8; 46 | 47 | if (subsetSum(arr, N, sum)){ 48 | 49 | cout << "True" << endl; 50 | } 51 | else 52 | cout << "False" << endl; 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /50_Subset Sum Problem/Ideal Solutions/subsetSumProblem.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | 5 | 6 | class Main{ 7 | //This function finds out if the subset with the required sum exists or not. 8 | public static boolean subsetSumProblem(int array[],int sum){ 9 | int n = array.length; 10 | boolean subset[][] = new boolean[sum + 1][n + 1]; 11 | for (int i = 0; i <= n; i++) subset[0][i] = true; 12 | for (int i = 1; i <= sum; i++) subset[i][0] = false; 13 | for (int i = 1; i <= sum; i++) { 14 | for (int j = 1; j <= n; j++) { 15 | subset[i][j] = subset[i][j - 1]; 16 | if (i >= array[j - 1]) 17 | subset[i][j] = subset[i][j] || subset[i - array[j - 1]][j - 1]; 18 | } 19 | } 20 | return subset[sum][n]; 21 | } 22 | //Main Function 23 | public static void main(String args[]){ 24 | int array[] = { 3, 34, 4, 12, 5, 2 }; 25 | int sum = 9; 26 | if (subsetSumProblem(array, sum)) System.out.println("True"); 27 | else{ 28 | System.out.println("False"); 29 | } 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /50_Subset Sum Problem/Problem Statement/subsetSumProblem.md: -------------------------------------------------------------------------------- 1 | ## **Subset Sum Problem** 2 | 3 | Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. 4 | 5 | 6 | 7 | #### **Sample Input** 8 | set = {3, 34, 4, 12, 5, 2}, sum = 8 9 | 10 | #### **Sample Output** 11 | True 12 | 13 | #### **Sample Explanation** 14 | The subset (3,5) gives the required sum 8. 15 | 16 | #### **Expected Time Complexity** 17 | __O__(sum * n), where sum is the ‘target sum’ and ‘n’ is the size of array. 18 | 19 | 20 | #### **Expected Space Complexity** 21 | __O__(sum * n) 22 | 23 | #### **Constraints** 24 | 1 <= N <= 100 25 | 1 <= A[i] <= 100 26 | 1 <= sum <= 10^5 27 | -------------------------------------------------------------------------------- /51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/RecursionTree_rod.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/RecursionTree_rod.png -------------------------------------------------------------------------------- /51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/Rod_Recursion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/Rod_Recursion.jpg -------------------------------------------------------------------------------- /51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/Rods_cut.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/Rods_cut.jpg -------------------------------------------------------------------------------- /51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/loopEqn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/loopEqn.png -------------------------------------------------------------------------------- /51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/rod_eqn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/rod_eqn.png -------------------------------------------------------------------------------- /51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/time_rod.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/masai-course/DSA-Must-Do-Questions/ea957a29a489539455023ccee8517d0e76a470ea/51_Rod Cutting Problem/Editorial/Cutting Rod fb54c14dfdff4b3ab82f028f3ee77504/time_rod.png -------------------------------------------------------------------------------- /51_Rod Cutting Problem/Ideal Solution/rodCuttingProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function that returns the best price for a rod of length n 5 | 6 | int cutRod(int price[], int N){ 7 | 8 | int dp[N+1]; 9 | dp[0] = 0; 10 | int i, j; 11 | 12 | // Build the dp table val[] in bottom up manner 13 | 14 | for (i = 1; i<= N; i++){ 15 | 16 | dp[i] = INT_MIN; 17 | 18 | for (j = 0; j < i; j++) 19 | dp[i] = max(dp[i], price[j] + dp[i-j-1]); 20 | 21 | } 22 | 23 | // Return the maximum price 24 | return dp[N]; 25 | } 26 | 27 | 28 | int main(){ 29 | 30 | int N = 8; // Size of Rod 31 | 32 | int price [] = {1, 5, 8, 9, 10, 17, 17, 20}; // Price for different pieces 33 | 34 | cout<