├── insertion.txt ├── SDE-SHEET.pdf ├── test.java ├── test.cpp ├── Inorder.java ├── postorder.java ├── Preorder.java ├── pyramid_pattern.c ├── inverted_pyramid.c ├── BinaryTreefromInorder.cpp ├── prime_no.c ├── SieveofEratosthenes.py ├── peakIndexInMountainArray.java ├── full_pyramid.c ├── Minimum Elements to Add to Form a Given Sum.py ├── README.md ├── StockBuy&Sell.java ├── missingNrepeating.py ├── MiddleNodeLL.java ├── coinchange.py ├── pascal.c ├── string_palindrome.c ├── dijkstra.java ├── MoveZerostoend.java ├── FirstMissingPositive.java ├── ReverseNumber.cs ├── Reverse_String ├── sort012python.py ├── AnagramPalindrome.java ├── quick_sort.c ├── trapping.java ├── Min. Diff in an Array.java ├── kadaneAlgorithm.cpp ├── BSTIterator.cpp ├── contributing.md ├── Shortest Path in Binary Trees.java ├── sieveOfEratosthenes.java ├── maximum.java ├── RemoveDuplicatedfromSortedArray.java ├── kadane.java ├── Prime.java ├── FlipImage.java ├── dsa.py ├── longestValidParentheses.py ├── maxWealth.java ├── sieveOfEratosthenes.cpp ├── selectionSort.txt ├── BoyerMoore.java ├── linear-search.cpp ├── LargestSubarrayWithZeroSum.java ├── DSA-Recursion.java ├── Pascal’s Triangle ├── pascals triangle ├── Selection sort ├── ValidAnagram.java ├── LongestPalindromicSubstring.py ├── dnfSort.cpp ├── BinarySearch.cpp ├── SlidingWindowMaximum.cpp ├── Insertion_Sort.c ├── selectionSort.cpp ├── bubbleSort.txt ├── PreorderB-tree.cpp ├── Find_maximum_height_pyramid_from_the_given_array_of_objects.java ├── Parenthesis_Balance.cpp ├── primsAlgoMST.cpp ├── sort012java.java ├── kthelement.cpp ├── lexicographically order ├── lexicographically order in java ├── add.java ├── divideandconquer.java ├── bubblesort.java ├── Merge_Sort.java ├── Reverse Linked List ├── ReverseStackRecursion.cpp ├── maxwidthBinaryTree.cpp ├── BurnaBinaryTree.cpp ├── bitonic.java ├── DFS ├── stack.java ├── serach_in_circular-linklist.py ├── width_of_bst.cpp ├── calculator in java.java ├── ReverseLL.cpp ├── jobseq.py ├── Mergesort.cpp ├── RotatedBinarySearch.java ├── Quick-Sort.java ├── SplitArrayLargestSum.java ├── queue.java ├── DFS in java ├── DFS using Java ├── DiameterofBT.java ├── HeapSort.java ├── CyclicSort.java ├── BFS.java ├── queue.c ├── Find Count of Single Valued Subtrees.java ├── InsertionSort.java ├── LinkedListByRazen.java ├── JavaCalculatorUI.java └── stack_SDE.py /insertion.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /SDE-SHEET.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/souvikg544/DSA/HEAD/SDE-SHEET.pdf -------------------------------------------------------------------------------- /test.java: -------------------------------------------------------------------------------- 1 | class test{ 2 | public static void main(String args[]){ 3 | System.out.println("Hello Java"); 4 | } 5 | } -------------------------------------------------------------------------------- /test.cpp: -------------------------------------------------------------------------------- 1 | // Your First C++ Program 2 | 3 | #include 4 | 5 | int main() { 6 | std::cout << "Hello World!"; 7 | return 0; 8 | } -------------------------------------------------------------------------------- /Inorder.java: -------------------------------------------------------------------------------- 1 | static String inorder(Node tree) 2 | { 3 | inorder(tree.left); 4 | System.out.println(tree.root); 5 | inorder(tree.right); 6 | } 7 | -------------------------------------------------------------------------------- /postorder.java: -------------------------------------------------------------------------------- 1 | static String postorder(Node tree) 2 | { 3 | postorder(tree.left); 4 | postorder(tree.right); 5 | System.out.println(tree.root); 6 | } 7 | -------------------------------------------------------------------------------- /Preorder.java: -------------------------------------------------------------------------------- 1 | static string preorder(Node tree) 2 | { 3 | 4 | 5 | 6 | System.out.println(tree.root); 7 | preorder(tree.left); 8 | preorder(tree.right); 9 | } 10 | -------------------------------------------------------------------------------- /pyramid_pattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, rows; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = 1; i <= rows; ++i) { 7 | for (j = 1; j <= i; ++j) { 8 | printf("* "); 9 | } 10 | printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /inverted_pyramid.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, j, rows; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = rows; i >= 1; --i) { 7 | for (j = 1; j <= i; ++j) { 8 | printf("%d ", j); 9 | } 10 | printf("\n"); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /BinaryTreefromInorder.cpp: -------------------------------------------------------------------------------- 1 | TreeNode* solve(vector& v, int l, int r){ 2 | if(l>r){ 3 | return NULL; 4 | } 5 | int m = (l+r)/2; 6 | TreeNode* root = new TreeNode(v[m]); 7 | root->left = solve(v, l, m-1); 8 | root-> right = solve(v, m+1,r); 9 | return root; 10 | } 11 | 12 | TreeNode *BSTFromInorder(vector &inorder) 13 | { 14 | return solve(inorder, 0, inorder.size()-1); 15 | } 16 | -------------------------------------------------------------------------------- /prime_no.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | int n,i,m=0,flag=0; 4 | printf("Enter the number to check prime:"); 5 | scanf("%d",&n); 6 | m=n/2; 7 | for(i=2;i<=m;i++) 8 | { 9 | if(n%i==0) 10 | { 11 | printf("Number is not prime"); 12 | flag=1; 13 | break; 14 | } 15 | } 16 | if(flag==0) 17 | printf("Number is prime"); 18 | return 0; 19 | } -------------------------------------------------------------------------------- /SieveofEratosthenes.py: -------------------------------------------------------------------------------- 1 | def SieveOfEratosthenes(num): 2 | prime=[True for i in range(num+1)] 3 | 4 | p=2 5 | while(p*p<=num): 6 | if(prime[p]==True): 7 | 8 | for i in range(p*p,num+1,p): 9 | prime[i]=False 10 | p+=1 11 | 12 | for p in range(2,num+1): 13 | if prime[p]: 14 | print(p) 15 | 16 | if __name__=='__main__': 17 | num=50 18 | SieveOfEratosthenes(num) 19 | -------------------------------------------------------------------------------- /peakIndexInMountainArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int peakIndexInMountainArray(int[] arr) { 3 | // binary search 4 | int l=0,u=arr.length-1; 5 | while(larr[mid+1]){ 8 | u = mid; 9 | }else{ 10 | l=mid+1; 11 | } 12 | 13 | } 14 | return l; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /full_pyramid.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int i, space, rows, k = 0; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = 1; i <= rows; ++i, k = 0) { 7 | for (space = 1; space <= rows - i; ++space) { 8 | printf(" "); 9 | } 10 | while (k != 2 * i - 1) { 11 | printf("* "); 12 | ++k; 13 | } 14 | printf("\n"); 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Minimum Elements to Add to Form a Given Sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minElements(self, nums, limit, goal): 3 | d=abs(goal-sum(nums)) 4 | c=d%limit 5 | if c==0: 6 | return d//limit 7 | else: 8 | return d//limit+1 9 | 10 | """ 11 | :type nums: List[int] 12 | :type limit: int 13 | :type goal: int 14 | :rtype: int 15 | """ 16 | 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DSA 2 | Hello everyoone ! Welcome to my dsa code sheets.( Come'on not mine 😉 Fork it , it will be yours soon) 3 | It is here that I understand and solve strivers dsa sheet and implement it with java and python. 4 | 5 | ## Hacktober Guidelines 6 | 7 | - Fork this repository, 8 | - Respond to the issues 9 | - Make meaningful pull requests. 10 | If you are a begineer to github let me help you with it.Catch me up on LinkedIn or find a suitable video on Youtube.. 11 | 12 | 13 | -------------------------------------------------------------------------------- /StockBuy&Sell.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int maxProfit(int[] prices) { 3 | int maxcurr = 0 , max = 0; 4 | for(int i = 1; i1): 13 | repeat.append(i) 14 | elif(l[i]==0): 15 | missing.append(i) 16 | print(repeat) 17 | print(missing) 18 | find([1,2,3,5,5]) 19 | 20 | -------------------------------------------------------------------------------- /MiddleNodeLL.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode middleNode(ListNode head) { 3 | 4 | // fast and slow pointer method 5 | ListNode slow = head; 6 | ListNode fast = head; 7 | 8 | if(head == null || head.next == null){ 9 | return head; 10 | } 11 | 12 | while(fast != null && fast.next != null){ 13 | slow = slow.next; 14 | fast = fast.next.next; 15 | } 16 | 17 | return slow; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /coinchange.py: -------------------------------------------------------------------------------- 1 | def count(coins,n,sum1): 2 | ans=[[0 for x in range(n)] for x in range(sum1+1)] 3 | for i in range(n): 4 | table[0][i] = 1 5 | for i in range(1, sum1+1): 6 | for j in range(n): 7 | x = table[i - coins[j]][j] if i-coins[j] >= 0 else 0 8 | y = table[i][j-1] if j >= 1 else 0 9 | table[i][j] = x + y 10 | 11 | return table[sum1][n-1] 12 | if __name__ == '__main__': 13 | coins = [1, 2, 3] 14 | n = len(coins) 15 | sum1 = 4 16 | print(count(coins, n, sum1)) 17 | 18 | 19 | -------------------------------------------------------------------------------- /pascal.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int rows, coef = 1, space, i, j; 4 | printf("Enter the number of rows: "); 5 | scanf("%d", &rows); 6 | for (i = 0; i < rows; i++) { 7 | for (space = 1; space <= rows - i; space++) 8 | printf(" "); 9 | for (j = 0; j <= i; j++) { 10 | if (j == 0 || i == 0) 11 | coef = 1; 12 | else 13 | coef = coef * (i - j + 1) / j; 14 | printf("%4d", coef); 15 | } 16 | printf("\n"); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /string_palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int main(){ 5 | char str[20]; 6 | int i, len, temp=0; 7 | int flag = 0; 8 | printf("Enter a string:"); 9 | scanf("%s", str); 10 | len = strlen(str); 11 | for(i=0;i < len ;i++){ 12 | if(str[i] != str[len-i-1]){ 13 | temp = 1; 14 | break; 15 | } 16 | } 17 | 18 | if (temp==0) { 19 | printf("String is a palindrome"); 20 | } 21 | else { 22 | printf("String is not a palindrome"); 23 | } 24 | return 0; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /dijkstra.java: -------------------------------------------------------------------------------- 1 | public class Node { 2 | 3 | private String name; 4 | 5 | private List shortestPath = new LinkedList<>(); 6 | 7 | private Integer distance = Integer.MAX_VALUE; 8 | 9 | Map adjacentNodes = new HashMap<>(); 10 | 11 | public void addDestination(Node destination, int distance) { 12 | adjacentNodes.put(destination, distance); 13 | } 14 | 15 | public Node(String name) { 16 | this.name = name; 17 | } 18 | 19 | // getters and setters 20 | } 21 | -------------------------------------------------------------------------------- /MoveZerostoend.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | void moveZeros(int arr[],int n) 4 | { 5 | int count=0; 6 | 7 | for(int i=0;i numbers = new HashSet<>(); 5 | 6 | // iterating over all the numbers present in nums 7 | for(int num:nums){ 8 | numbers.add(num); 9 | } 10 | 11 | 12 | for (int i = 1 ; i <=nums.length ; i++) { 13 | // if it is not contained then return the answer 14 | if (!numbers.contains(i)) { 15 | return i; 16 | } 17 | } 18 | 19 | return nums.length+1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ReverseNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class ReverseNumber 4 | { 5 | public static void Main(string[] args) 6 | { 7 | int number; 8 | int reverse=0; 9 | int rem; 10 | 11 | Console.Write("Enter a number: "); 12 | number= int.Parse(Console.ReadLine()); 13 | 14 | while(number != 0) 15 | { 16 | rem = number % 10; 17 | reverse = reverse * 10 + rem; 18 | number /= 10; 19 | } 20 | 21 | Console.Write("Reversed Number: "+reverse); 22 | } 23 | } -------------------------------------------------------------------------------- /Reverse_String: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class Main 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc=new Scanner(System.in); 7 | System.out.println("Enter the string"); 8 | String str=sc.nextLine(); 9 | String str1=""; 10 | char a,b,c,d; 11 | int i,k,j; 12 | for(i=0;i=2)?0:1; 19 | } 20 | 21 | public static void main(String[] args) { 22 | System.out.println(isPossible("geeksogeeks")); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /quick_sort.c: -------------------------------------------------------------------------------- 1 | 2 | quickSort(array, leftmostIndex, rightmostIndex) 3 | if (leftmostIndex < rightmostIndex) 4 | pivotIndex <- partition(array,leftmostIndex, rightmostIndex) 5 | quickSort(array, leftmostIndex, pivotIndex - 1) 6 | quickSort(array, pivotIndex, rightmostIndex) 7 | 8 | partition(array, leftmostIndex, rightmostIndex) 9 | set rightmostIndex as pivotIndex 10 | storeIndex <- leftmostIndex - 1 11 | for i <- leftmostIndex + 1 to rightmostIndex 12 | if element[i] < pivotElement 13 | swap element[i] and element[storeIndex] 14 | storeIndex++ 15 | swap pivotElement and element[storeIndex+1] 16 | return storeIndex + 1 17 | -------------------------------------------------------------------------------- /trapping.java: -------------------------------------------------------------------------------- 1 | class trapping { 2 | public int trap(int[] height) { 3 | int n = height.length; 4 | int left[] = new int[n]; 5 | int right[] = new int[n]; 6 | left[0] = height[0]; 7 | for(int i =1;i< n;i++){ 8 | left[i] = Math.max(left[i-1], height[i]); 9 | } 10 | 11 | right[n-1] = height[n-1]; 12 | for(int j =n-2;j>=0;j--){ 13 | right[j] = Math.max(right[j+1],height[j]); 14 | } 15 | int res = 0; 16 | for(int k=0;k 2 | 3 | using namespace std; 4 | 5 | void kadaneAlgo(int a[], int n) 6 | { 7 | int maxSum = INT_MIN; 8 | int currSum = 0; 9 | 10 | for (int i = 0; i < n; i++) 11 | { 12 | currSum += a[i]; 13 | if (currSum <= 0) 14 | { 15 | currSum = 0; 16 | } 17 | } 18 | 19 | maxSum = max(currSum, maxSum); 20 | 21 | cout << maxSum; 22 | 23 | // Time complexity: O(n) 24 | } 25 | 26 | int main() 27 | { 28 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 29 | int n = sizeof(a) / sizeof(a[0]); 30 | 31 | kadaneAlgo(a, n); 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /BSTIterator.cpp: -------------------------------------------------------------------------------- 1 | class BSTIterator { 2 | public: 3 | stackmyStack; 4 | void pushAll(TreeNode* root){ 5 | while(root){ 6 | myStack.push(root); 7 | root=root->left; 8 | } 9 | } 10 | 11 | BSTIterator(TreeNode* root) { 12 | pushAll(root); 13 | } 14 | 15 | int next() { 16 | TreeNode* temp=myStack.top(); 17 | myStack.pop(); 18 | pushAll(temp->right); 19 | return temp->val; 20 | } 21 | 22 | bool hasNext() { 23 | if(myStack.empty()) 24 | return false; 25 | else 26 | return true; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | While on one hand our repository is a good place for beginners to contribute something useful to open source, on the other hand it is also a good place for experienced people to contribute something useful to open source. We welcome contributions from everyone.
3 | However some people tend to spam the repository with irrelevant pull requests and get one PR for hacktoberfest and other such open source events. We do not want that to happen. So we have a few guidelines that we would like you to follow.
4 | __In case we find your PR not relevant or spam, we will mark it as invalid and it will not be counted towards hacktoberfest.__ 5 | -------------------------------------------------------------------------------- /Shortest Path in Binary Trees.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | 8 | class Codechef 9 | { 10 | public static void main (String[] args) throws java.lang.Exception 11 | { 12 | Scanner scn = new Scanner(System.in); 13 | int t = scn.nextInt(); 14 | while(t-->0){ 15 | int a = scn.nextInt(); 16 | int b = scn.nextInt(); 17 | int ans = 0; 18 | while (a != b) { 19 | if (a > b) { 20 | a = a / 2; 21 | } 22 | else if (b > a) { 23 | b = b / 2; 24 | } 25 | ans++; 26 | } 27 | System.out.println(ans); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /sieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | public class sieveOfEratosthenes { 2 | public static void main(String[] args) { 3 | int n=40; 4 | boolean[] primes = new boolean[n+1]; 5 | sieve(n,primes); 6 | 7 | } 8 | 9 | static void sieve(int n, boolean[] primes){ 10 | for(int i=2;i*i<=n;i++){ 11 | if(!primes[i]){ 12 | for(int j=i*2;j<=n;j+=i){ 13 | primes[j]=true; 14 | } 15 | } 16 | } 17 | 18 | for(int i=2;i<=n;i++){ 19 | if(!primes[i]){ 20 | System.out.print(i+" "); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /maximum.java: -------------------------------------------------------------------------------- 1 | package com.saatvik; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.PriorityQueue; 5 | 6 | public class array { 7 | public static void main(String args[]) { 8 | 9 | 10 | int arr[] = {-2,1,-3,4,-1,2,1,-5,4}; 11 | System.out.println(maxSubArray(arr)); 12 | } 13 | static int maxSubArray(int[] arr) { 14 | 15 | int n = arr.length; 16 | int currsum = arr[0]; 17 | int maxsum = currsum; 18 | for(int i =1;i int: 7 | queue = collections.deque() 8 | queue.append(0) 9 | longest = 0 10 | for p in s: 11 | if p == '(': 12 | queue.append(0) 13 | if p == ')': 14 | if len(queue) > 1: 15 | length = queue.pop() + 2 16 | queue[-1] += length 17 | longest = max(longest, queue[-1]) 18 | else: 19 | queue[-1] = 0 20 | return longest 21 | -------------------------------------------------------------------------------- /maxWealth.java: -------------------------------------------------------------------------------- 1 | // Richest Customer Wealth 2 | // URL: https://leetcode.com/problems/richest-customer-wealth/ 3 | 4 | package com.akshat; 5 | 6 | public class maxWealth { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[][] accounts = {{1,5},{7,3},{3,5}}; 11 | 12 | System.out.println(maximumWealth(accounts)); 13 | 14 | } 15 | 16 | static int maximumWealth(int[][] accounts) { 17 | int max = Integer.MIN_VALUE; 18 | for(int r=0; rmax){ 24 | max=sum; 25 | } 26 | } 27 | return max; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /sieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | // Program to find all the primes in a given range by sieve of Eratosthenes . 2 | 3 | #include 4 | #include 5 | 6 | using namespace std ; 7 | void primes(int n) 8 | { 9 | int prime[100] = {0} ; 10 | 11 | for(int i = 2 ; i <= n ; i++) 12 | { 13 | if(!prime[i]) 14 | { 15 | for(int j =pow(i,2) ; j <= n ; j += i) 16 | { 17 | prime[j] = 1 ; 18 | } 19 | } 20 | } 21 | 22 | for(int i = 2 ; i <= n ; i++) 23 | { 24 | if(!prime[i]) 25 | { 26 | cout << i ; 27 | } 28 | 29 | cout << endl ; 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | int n ; 36 | cin >> n ; 37 | 38 | primes(n) ; 39 | 40 | return 0 ; 41 | } -------------------------------------------------------------------------------- /selectionSort.txt: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class SelectionSort { 4 | void selectionSort(int array[]) { 5 | int size = array.length; 6 | 7 | for (int step = 0; step < size - 1; step++) { 8 | int min_idx = step; 9 | 10 | for (int i = step + 1; i < size; i++){ 11 | if (array[i] < array[min_idx]) { 12 | min_idx = i; 13 | } 14 | } 15 | 16 | int temp = array[step]; 17 | array[step] = array[min_idx]; 18 | array[min_idx] = temp; 19 | } 20 | } 21 | public static void main(String args[]) { 22 | int[] data = { 1,4,3,5,9,7 }; 23 | SelectionSort sc = new SelectionSort(); 24 | sc.selectionSort(data); 25 | System.out.println("Sorted Array in Ascending Order: "); 26 | System.out.println(Arrays.toString(data)); 27 | } 28 | } -------------------------------------------------------------------------------- /BoyerMoore.java: -------------------------------------------------------------------------------- 1 | class Main 2 | { 3 | 4 | public static int findMajorityElement(int[] nums) 5 | { 6 | 7 | int m = -1; 8 | 9 | int i = 0; 10 | 11 | 12 | for (int j = 0; j < nums.length; j++) 13 | { 14 | 15 | if (i == 0) 16 | { 17 | 18 | m = nums[j]; 19 | 20 | i = 1; 21 | } 22 | 23 | 24 | else if (m == nums[j]) { 25 | i++; 26 | } 27 | 28 | else { 29 | i--; 30 | } 31 | } 32 | 33 | return m; 34 | } 35 | 36 | public static void main (String[] args) 37 | { 38 | int[] nums = { 1, 8, 7, 4, 1, 2, 2, 2, 2, 2, 2 }; 39 | 40 | System.out.println("The majority element is " + findMajorityElement(nums)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /linear-search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int myarray[10] = {21,43,23,54,75,13,5,8,25,10}; 7 | int key,loc; 8 | cout<<"The input array is"<>key; 14 | for (int i = 0; i< 10; i++) 15 | { 16 | if(myarray[i] == key) 17 | { 18 | loc = i+1; 19 | break; 20 | } 21 | else 22 | loc = 0; 23 | } 24 | if(loc != 0) 25 | { 26 | cout<<"Key found at position "< mp=new HashMap<>(); 5 | int prefixSum=0,maxi=0; 6 | 7 | for (int i=0;i 2 21 | for j in range(n): 22 | for i in range(j-1): 23 | if s[i]==s[j] and dp[i+1][j-1] is True: 24 | dp[i][j] = True 25 | if maxlen < j-i+1: 26 | maxlen = max(maxlen, j-i+1) 27 | ans = s[i:j+1] 28 | 29 | 30 | return ans 31 | -------------------------------------------------------------------------------- /dnfSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // DNF SORT 6 | // ------------------------------------------------------------------------ 7 | 8 | // Sorting in ascending order 9 | void dnfsort(int a[], int n) 10 | { 11 | int low = 0; 12 | int mid = 0; 13 | int high = n - 1; 14 | 15 | while (mid <= high) 16 | { 17 | if (a[mid] == 0) 18 | { 19 | swap(a[low], a[mid]); 20 | low++; 21 | mid++; 22 | } 23 | else if (a[mid] == 1) 24 | { 25 | mid++; 26 | } 27 | else 28 | { 29 | swap(a[mid], a[high]); 30 | high--; 31 | } 32 | } 33 | } 34 | 35 | // Driver function 36 | 37 | int main() 38 | { 39 | int a[] = {1, 0, 1, 2, 0, 1, 1}; 40 | int n = sizeof(a) / sizeof(int); 41 | 42 | dnfsort(a, n); 43 | 44 | for (int i = 0; i < n; i++) 45 | { 46 | cout << a[i] << " "; 47 | } 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | // BINARY SEARCH 2 | /*Problem: Given a sorted array of size n and an integer k,find the position at which k is present in the array using binary search 3 | Time Complexity: O(logn), where n is the size of the input array 4 | Space Complexity: O(1) 5 | */ 6 | #include 7 | using namespace std; 8 | 9 | int binarysearch(int arr[], int n, int k) 10 | { 11 | int start = 0; 12 | int end = n - 1; 13 | int ans = -1; 14 | while (start <= end) 15 | { 16 | int mid = start + (end - start) / 2; 17 | if (arr[mid] == k) 18 | { 19 | ans = mid; 20 | break; 21 | } 22 | else if (arr[mid] < k) 23 | { 24 | start = mid + 1; 25 | } 26 | else 27 | { 28 | end = mid - 1; 29 | } 30 | } 31 | return ans; 32 | } 33 | 34 | int main() 35 | { 36 | int arr[5] = {10, 20, 30, 40, 50}; 37 | cout << binarysearch(arr, 5, 40) << endl; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /SlidingWindowMaximum.cpp: -------------------------------------------------------------------------------- 1 | // Problem Link : https://leetcode.com/problems/sliding-window-maximum/ 2 | // Time complexity : O(N) 3 | // Space Complexity : O(K) 4 | #include 5 | using namespace std; 6 | 7 | vector < int > maxSlidingWindow(vector < int > & nums, int k) { 8 | deque < int > dq; 9 | vector < int > ans; 10 | for (int i = 0; i < nums.size(); i++) { 11 | if (!dq.empty() && dq.front() == i - k) dq.pop_front(); 12 | 13 | while (!dq.empty() && nums[dq.back()] < nums[i]) 14 | dq.pop_back(); 15 | 16 | dq.push_back(i); 17 | if (i >= k - 1) ans.push_back(nums[dq.front()]); 18 | } 19 | return ans; 20 | } 21 | int main() { 22 | int i, j, n, k , x; 23 | cin>>k>>n; 24 | vector < int > arr (n); 25 | for(int i=0;i>arr[i]; 27 | } 28 | vector < int > ans; 29 | ans = maxSlidingWindow(arr, k); 30 | cout << "Maximum element in every " << k << " window " << endl; 31 | for (i = 0; i < ans.size(); i++) 32 | cout << ans[i] << " "; 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Insertion_Sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void printArr(int a[], int size) 5 | { 6 | for (int i = 0; i < size; i++) 7 | { 8 | printf("%d ", a[i]); 9 | } 10 | 11 | printf("\n"); 12 | } 13 | 14 | void insertionSort(int arr[] , int n) 15 | { 16 | int key , j ; 17 | 18 | for (int i = 1; i <= n - 1 ; i++) 19 | { 20 | /* code */ 21 | key = arr[i] ; 22 | j = i - 1 ; 23 | 24 | while(arr[j] > key && j >= 0) 25 | { 26 | arr[j+1] = arr[j] ; 27 | j-- ; 28 | } 29 | arr[j+1] = key ; 30 | } 31 | 32 | } 33 | 34 | int main() 35 | { 36 | int N; 37 | printf("Enter no. of elements you want to input : "); 38 | scanf("%d", &N); 39 | int *A = (int *)malloc(N * sizeof(int)); 40 | 41 | printf("Enter the elements here \n"); 42 | for (int i = 0; i < N; i++) 43 | { 44 | scanf("%d", &A[i]); 45 | } 46 | 47 | printArr(A, N); 48 | insertionSort(A, N); 49 | printf("Sorted Array :"); 50 | printArr(A, N); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /selectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int selectSort(int a[], int size){ 5 | int i, j, min, temp; 6 | 7 | //outer loop 8 | for(i = 0; i < size-1; i++){ 9 | min = i; 10 | 11 | //inner loop 12 | for(j = i+1; j < size; j++){ 13 | 14 | if(a[min] > a[j]) 15 | //update the new min if the condition is true 16 | min = j; 17 | 18 | //swap the element present in a[min] with element present in a[i] 19 | temp = a[min]; 20 | a[min] = a[i]; 21 | a[i] = temp; 22 | } 23 | } 24 | return 0; 25 | 26 | } 27 | 28 | int print(int a[], int size) 29 | { 30 | int i; 31 | for (i = 0; i < size; i++) 32 | cout<array[i+1]){ 9 | int temp=array[i]; 10 | array[i]=array[i+1]; 11 | array[i+1]=temp; 12 | } 13 | } 14 | } 15 | } 16 | static void printarray(int array[],int size){ 17 | for(int i=0;i 2 | using namespace std; 3 | struct node { 4 | int data; 5 | struct node *left; 6 | struct node *right; 7 | }; 8 | struct node *createNode(int val) { 9 | struct node *temp = (struct node *)malloc(sizeof(struct node)); 10 | temp->data = val; 11 | temp->left = temp->right = NULL; 12 | return temp; 13 | } 14 | void preorder(struct node *root) { 15 | if (root != NULL) { 16 | cout<data<<" "; 17 | preorder(root->left); 18 | preorder(root->right); 19 | } 20 | } 21 | struct node* insertNode(struct node* node, int val) { 22 | if (node == NULL) return createNode(val); 23 | if (val < node->data) 24 | node->left = insertNode(node->left, val); 25 | else if (val > node->data) 26 | node->right = insertNode(node->right, val); 27 | return node; 28 | } 29 | int main() { 30 | struct node *root = NULL; 31 | root = insertNode(root, 4); 32 | insertNode(root, 5); 33 | insertNode(root, 2); 34 | insertNode(root, 9); 35 | insertNode(root, 1); 36 | insertNode(root, 3); 37 | cout<<"Pre-Order traversal of the Binary Search Tree is: "; 38 | preorder(root); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /Find_maximum_height_pyramid_from_the_given_array_of_objects.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Find_maximum_height_pyramid_from_the_given_array_of_objects { 4 | public static int maxHeightPyramid(int arr[],int n) 5 | { 6 | int ans = 1; 7 | Arrays.sort(arr); 8 | int prev_width = arr[0]; 9 | int prev_count = 1; 10 | 11 | int curr_width = 0; 12 | int curr_count = 0; 13 | for(int i=1;i prev_width && curr_count > prev_count) 18 | { 19 | prev_width = curr_width; 20 | prev_count = curr_count; 21 | 22 | curr_count = 0; 23 | curr_width = 0; 24 | 25 | ans++; 26 | } 27 | } 28 | return ans; 29 | } 30 | public static void main(String[] args) { 31 | int arr[] = {10, 20, 30, 50, 60, 70}; 32 | int n = arr.length; 33 | System.out.println("maximum height of pyramid is " + maxHeightPyramid(arr, n)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Parenthesis_Balance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std ; 6 | 7 | bool parenBal(string s) 8 | { 9 | stack st ; 10 | bool ans = true ; 11 | 12 | for(int i = 0 ; i < s.length() ; i++) 13 | { 14 | if(s[i] == '(' || s[i] == '{' || s[i] =='[') 15 | st.push(s[i]) ; 16 | 17 | else if (!st.empty() && st.top() == '(' && s[i] == ')') 18 | { 19 | st.pop() ; 20 | ans = true ; 21 | } 22 | else if (!st.empty() && st.top() == '[' && s[i] == ']') 23 | { 24 | st.pop() ; 25 | ans = true ; 26 | } 27 | else if (!st.empty() && st.top() == '{' && s[i] == '}') 28 | { 29 | st.pop() ; 30 | ans = true ; 31 | } 32 | 33 | else 34 | ans = false ; 35 | 36 | } 37 | 38 | if(!st.empty()) 39 | ans = false ; 40 | 41 | return ans ; 42 | 43 | } 44 | int main() 45 | { 46 | string inp ; 47 | cin >> inp ; 48 | if(parenBal(inp)) 49 | cout << "Valid String" < 2 | 3 | using namespace std ; 4 | 5 | signed main(){ 6 | 7 | int n , m ; 8 | cin >> n >> m ; 9 | 10 | vector> graph(n) ; 11 | 12 | int a , b , wt ; 13 | 14 | for(int i = 0 ; i < m ; i++){ 15 | cin >> a >> b >> wt ; 16 | 17 | graph[a].push_back(make_pair(b,wt)) ; 18 | graph[b].push_back(make_pair(a,wt)) ; 19 | } 20 | 21 | vector key(n , INT_MAX) ; 22 | vector parent(n) ; 23 | 24 | vector mstSet(n , false) ; 25 | 26 | key[0] = 0 ; 27 | parent[0] = -1 ; 28 | 29 | priority_queue , vector> , greater>> pq ; 30 | 31 | pq.push({0,0}) ; 32 | 33 | while (!pq.empty()) 34 | { 35 | /* code */ 36 | int u = pq.top().second ; 37 | pq.pop() ; 38 | 39 | mstSet[u] = true ; 40 | 41 | for(auto it : graph[u]){ 42 | int v = it.first ; 43 | int weight = it.second ; 44 | 45 | if(mstSet[v] == false and weight < key[v]){ 46 | key[v] = weight ; 47 | parent[v] = u ; 48 | 49 | pq.push({key[v] , v}) ; 50 | } 51 | } 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /sort012java.java: -------------------------------------------------------------------------------- 1 | public class sort012java { 2 | 3 | public static void main(String args[]) 4 | { 5 | 6 | sortColors(new int[]{ 1,0,0,2,2,1,0,2,0,1}); 7 | } 8 | 9 | public static void sortColors(int[] nums) { 10 | int lo = 0; 11 | int hi = nums.length - 1; 12 | int mid = 0; 13 | int temp; 14 | while (mid <= hi) 15 | { 16 | switch (nums[mid]) { 17 | case 0: { 18 | temp = nums[lo]; 19 | nums[lo] = nums[mid]; 20 | nums[mid] = temp; 21 | lo++; 22 | mid++; 23 | break; 24 | } 25 | case 1: 26 | mid++; 27 | break; 28 | case 2: { 29 | temp = nums[mid]; 30 | nums[mid] = nums[hi]; 31 | nums[hi] = temp; 32 | hi--; 33 | break; 34 | } 35 | } 36 | } 37 | for (int i = 0; i < nums.length; i++) 38 | { 39 | System.out.println(nums[i]); 40 | } 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /kthelement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int kthelement(int arr1[], int arr2[], int m, int n, int k) { 4 | if(m > n) { 5 | return kthelement(arr2, arr1, n, m, k); 6 | } 7 | 8 | int low = max(0,k-m), high = min(k,n); 9 | 10 | while(low <= high) { 11 | int cut1 = (low + high) >> 1; 12 | int cut2 = k - cut1; 13 | int l1 = cut1 == 0 ? INT_MIN : arr1[cut1 - 1]; 14 | int l2 = cut2 == 0 ? INT_MIN : arr2[cut2 - 1]; 15 | int r1 = cut1 == n ? INT_MAX : arr1[cut1]; 16 | int r2 = cut2 == m ? INT_MAX : arr2[cut2]; 17 | 18 | if(l1 <= r2 && l2 <= r1) { 19 | return max(l1, l2); 20 | } 21 | else if (l1 > r2) { 22 | high = cut1 - 1; 23 | } 24 | else { 25 | low = cut1 + 1; 26 | } 27 | } 28 | return 1; 29 | } 30 | int main() { 31 | int array1[] = {2,3,6,7,9}; 32 | int array2[] = {1,4,8,10}; 33 | int m = sizeof(array1)/sizeof(array1[0]); 34 | int n = sizeof(array2)/sizeof(array2[0]); 35 | int k = 5; 36 | cout<<"The element at the kth position in the final sorted array is " 37 | < 0) { 13 | String temp = strArr[i]; 14 | strArr[i] = strArr[j]; 15 | strArr[j] = temp; 16 | } 17 | } 18 | } 19 | } 20 | 21 | // this function prints the array passed as argument 22 | public static void printArray(String strArr[]) 23 | { 24 | for (String string : strArr) 25 | System.out.print(string + " "); 26 | System.out.println(); 27 | } 28 | 29 | public static void main(String[] args) 30 | { 31 | // Initializing String array. 32 | String stringArray[] 33 | = { "Harit", "Girish", "Gritav", 34 | "Lovenish", "Nikhil", "Harman" }; 35 | 36 | // sorting String array lexicographically. 37 | sortLexicographically(stringArray); 38 | 39 | printArray(stringArray); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /lexicographically order in java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class GFG { 4 | 5 | // this method sort the string array lexicographically. 6 | public static void 7 | sortLexicographically(String strArr[]) 8 | { 9 | for (int i = 0; i < strArr.length; i++) { 10 | for (int j = i + 1; j < strArr.length; j++) { 11 | if (strArr[i].compareToIgnoreCase(strArr[j]) 12 | > 0) { 13 | String temp = strArr[i]; 14 | strArr[i] = strArr[j]; 15 | strArr[j] = temp; 16 | } 17 | } 18 | } 19 | } 20 | 21 | // this function prints the array passed as argument 22 | public static void printArray(String strArr[]) 23 | { 24 | for (String string : strArr) 25 | System.out.print(string + " "); 26 | System.out.println(); 27 | } 28 | 29 | public static void main(String[] args) 30 | { 31 | // Initializing String array. 32 | String stringArray[] 33 | = { "Harit", "Girish", "Gritav", 34 | "Lovenish", "Nikhil", "Harman" }; 35 | 36 | // sorting String array lexicographically. 37 | sortLexicographically(stringArray); 38 | 39 | printArray(stringArray); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /add.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | public class array { 4 | public static void main(String args[]) { 5 | 6 | int arr1[] = {9,9,9}; 7 | int arr2[] = {2,8}; 8 | int n1 = arr1.length; 9 | int n2 = arr2.length; 10 | sum_of_two_array(arr1,arr2,n1,n2); 11 | } 12 | static void sum_of_two_array(int arr[],int arr1[],int n1,int n2){ 13 | int[] sum = new int[n1 > n2 ?n1:n2]; 14 | int c=0; 15 | int i = arr.length-1; 16 | int j = arr1.length-1; 17 | int k = sum.length-1; 18 | 19 | while(k>0){ 20 | int d = c; 21 | if(i>=0){ 22 | d = d + arr[i]; 23 | } 24 | if(j>=0){ 25 | d = d+ arr1[j]; 26 | 27 | } 28 | c = d/10; 29 | d = d%10; 30 | sum[k] = d; 31 | i--; 32 | j--; 33 | k--; 34 | 35 | } 36 | if(c!=0){ 37 | System.out.print(c+" "); 38 | } 39 | for(int val : sum){ 40 | System.out.print(val+" "); 41 | } 42 | } 43 | 44 | 45 | // Question 2 rotate array k times 46 | 47 | 48 | } 49 | 50 | // static void rotate(int arr[] ,int start, int end){ 51 | // 52 | // 53 | // } 54 | //} 55 | -------------------------------------------------------------------------------- /divideandconquer.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class MergeSortTopDown { 4 | public int[] sort(int[] arr) { 5 | int n = arr.length; 6 | if (n < 2) { 7 | return arr; 8 | } 9 | 10 | // divide the array in half 11 | int[] left = Arrays.copyOfRange(arr, 0, n/2); 12 | int[] right = Arrays.copyOfRange(arr, n/2, n); 13 | 14 | // sort/conquer each half 15 | int[] sortedLeft = sort(left); 16 | int[] sortedRight = sort(right); 17 | 18 | // merge/combine the sorted halves 19 | return merge(sortedLeft, sortedRight, n); 20 | } 21 | 22 | private int[] merge(int[] left, int[] right, int n) { 23 | int[] result = new int[n]; 24 | int l = 0; 25 | int r = 0; 26 | 27 | for (int i = 0; i < n; i++) { 28 | if (l < left.length && (r >= right.length || left[l] < right[r])) { 29 | result[i] = left[l]; 30 | l++; 31 | } else { 32 | result[i] = right[r]; 33 | r++; 34 | } 35 | } 36 | 37 | return result; 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[] a = {7, 9, 2, 3, 1}; 42 | a = new MergeSortTopDown().sort(a); 43 | 44 | Arrays.stream(a).forEach(System.out::println); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /bubblesort.java: -------------------------------------------------------------------------------- 1 | public class BubbleSortExample { 2 | static void bubbleSort(int[] arr) { 3 | int n = arr.length; 4 | int temp = 0; 5 | for(int i=0; i < n; i++){ 6 | for(int j=1; j < (n-i); j++){ 7 | if(arr[j-1] > arr[j]){ 8 | //swap elements 9 | temp = arr[j-1]; 10 | arr[j-1] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | 14 | } 15 | } 16 | 17 | } 18 | public static void main(String[] args) { 19 | int arr[] ={3,60,35,2,45,320,5}; 20 | 21 | System.out.println("Array Before Bubble Sort"); 22 | for(int i=0; i < arr.length; i++){ 23 | System.out.print(arr[i] + " "); 24 | } 25 | System.out.println(); 26 | 27 | bubbleSort(arr);//sorting array elements using bubble sort 28 | 29 | System.out.println("Array After Bubble Sort"); 30 | for(int i=0; i < arr.length; i++){ 31 | System.out.print(arr[i] + " "); 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Merge_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | public class Merge_Sort { 3 | static int[] mergeSort(int[]arr){ 4 | if (arr.length == 1){ 5 | return arr; 6 | } 7 | int mid = arr.length/2; 8 | int[] left = mergeSort(Arrays.copyOfRange(arr,0,mid)); 9 | int[] right = mergeSort(Arrays.copyOfRange(arr,mid,arr.length)); 10 | return merger(left,right); 11 | } 12 | private static int[] merger(int[]first,int[]second){ 13 | int i = 0; 14 | int j = 0; 15 | int k = 0; 16 | int[] mix = new int[first.length+ second.length]; 17 | while (i< first.length && j 6 | using namespace std; 7 | 8 | void pushAtBottom(stack &st, int x) 9 | { 10 | 11 | if (st.size() == 0) 12 | { 13 | st.push(x); 14 | } 15 | else 16 | { 17 | 18 | int a = st.top(); 19 | st.pop(); 20 | pushAtBottom(st, x); 21 | 22 | st.push(a); 23 | } 24 | } 25 | 26 | void reverse(stack &st) 27 | { 28 | if (st.size() > 0) 29 | { 30 | 31 | int x = st.top(); 32 | st.pop(); 33 | reverse(st); 34 | 35 | pushAtBottom(st, x); 36 | } 37 | return; 38 | } 39 | 40 | int main() 41 | { 42 | stack st, st2; 43 | // intializing the stack with some elements 44 | for (int i = 1; i <= 4; i++) 45 | { 46 | st.push(i); 47 | } 48 | 49 | st2 = st; 50 | // printing the original stack 51 | cout << "Original Stack" << endl; 52 | while (!st2.empty()) 53 | { 54 | cout << st2.top() << " "; 55 | st2.pop(); 56 | } 57 | cout << endl; 58 | // function call to reverse the stack 59 | reverse(st); 60 | // printing the reversed stack 61 | cout << "Reversed Stack" << endl; 62 | while (!st.empty()) 63 | { 64 | cout << st.top() << " "; 65 | st.pop(); 66 | } 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /maxwidthBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node { 4 | int data; 5 | struct Node* left; 6 | struct Node* right; 7 | Node(int d) 8 | { 9 | this->data = d; 10 | this->left = this->right = NULL; 11 | } 12 | }; 13 | int maxWidth(struct Node* root) 14 | { 15 | 16 | if (root == NULL) 17 | return 0; 18 | 19 | 20 | int result = 0; 21 | 22 | 23 | queue q; 24 | q.push(root); 25 | while (!q.empty()) { 26 | 27 | int count = q.size(); 28 | 29 | 30 | result = max(count, result); 31 | 32 | 33 | while (count--) { 34 | 35 | Node* temp = q.front(); 36 | q.pop(); 37 | 38 | 39 | if (temp->left != NULL) 40 | q.push(temp->left); 41 | if (temp->right != NULL) 42 | q.push(temp->right); 43 | } 44 | } 45 | 46 | return result; 47 | } 48 | 49 | 50 | int main() 51 | { 52 | struct Node* root = new Node(1); 53 | root->left = new Node(2); 54 | root->right = new Node(3); 55 | root->left->left = new Node(4); 56 | root->left->right = new Node(5); 57 | root->right->right = new Node(8); 58 | root->right->right->left = new Node(6); 59 | root->right->right->right = new Node(7); 60 | cout << "Maximum width is " << maxWidth(root) << endl; 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /BurnaBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | struct Node { 6 | int key; 7 | struct Node* left; 8 | struct Node* right; 9 | Node(int k) 10 | { 11 | key = k; 12 | left = right = NULL; 13 | } 14 | }; 15 | 16 | int res = 0; 17 | 18 | 19 | int burnTime(Node* root, int leaf, int& dist) 20 | { 21 | if (root == NULL) 22 | return 0; 23 | if (root->key == leaf) { 24 | dist = 0; 25 | return 1; 26 | } 27 | int ldist = -1, rdist = -1; 28 | int lh = burnTime(root->left, leaf, ldist); 29 | int rh = burnTime(root->right, leaf, rdist); 30 | 31 | if (ldist != -1) { 32 | dist = ldist + 1; 33 | res = max(res, dist + rh); 34 | } 35 | else if (rdist != -1) { 36 | dist = rdist + 1; 37 | res = max(res, dist + lh); 38 | } 39 | return max(lh, rh) + 1; 40 | } 41 | 42 | 43 | int main() 44 | { 45 | Node* root = new Node(1); 46 | root->left = new Node(2); 47 | root->right = new Node(3); 48 | root->left->left = new Node(4); 49 | root->left->right = new Node(5); 50 | root->right->left = new Node(6); 51 | root->left->left->left = new Node(8); 52 | root->left->right->left = new Node(9); 53 | root->left->right->right = new Node(10); 54 | root->left->right->left->left = new Node(11); 55 | int dist = -1; 56 | int target = 11; 57 | burnTime(root, target, dist); 58 | cout << res; 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /bitonic.java: -------------------------------------------------------------------------------- 1 | class Main 2 | { 3 | 4 | public static void findBitonicSubarray(int[] A) 5 | { 6 | if (A.length == 0) { 7 | return; 8 | } 9 | 10 | int[] I = new int[A.length]; 11 | I[0] = 1; 12 | for (int i = 1; i < A.length; i++) 13 | { 14 | I[i] = 1; 15 | if (A[i - 1] < A[i]) { 16 | I[i] = I[i - 1] + 1; 17 | } 18 | } 19 | 20 | int[] D = new int[A.length]; 21 | D[A.length - 1] = 1; 22 | for (int i = A.length - 2; i >= 0; i--) 23 | { 24 | D[i] = 1; 25 | if (A[i] > A[i + 1]) { 26 | D[i] = D[i + 1] + 1; 27 | } 28 | } 29 | 30 | int lbs_len = 1; 31 | int beg = 0, end = 0; 32 | 33 | for (int i = 0; i < A.length; i++) 34 | { 35 | int len = I[i] + D[i] - 1; 36 | if (lbs_len < len) 37 | { 38 | lbs_len = len; 39 | beg = i - I[i] + 1; 40 | end = i + D[i] - 1; 41 | } 42 | } 43 | 44 | System.out.println("The length of the longest bitonic subarray is " + lbs_len); 45 | System.out.printf("The longest bitonic subarray indices are [%d, %d]", beg, end); 46 | } 47 | 48 | public static void main(String[] args) 49 | { 50 | int[] A = { 3, 5, 8, 4, 5, 9, 10, 8, 5, 3, 4 }; 51 | 52 | findBitonicSubarray(A); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /DFS: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class Graph { 5 | private int V; 6 | 7 | 8 | private LinkedList adj[]; 9 | 10 | 11 | @SuppressWarnings("unchecked") Graph(int v) 12 | { 13 | V = v; 14 | adj = new LinkedList[v]; 15 | for (int i = 0; i < v; ++i) 16 | adj[i] = new LinkedList(); 17 | } 18 | 19 | 20 | void addEdge(int v, int w) 21 | { 22 | adj[v].add(w); // Add w to v's list. 23 | } 24 | 25 | 26 | void DFSUtil(int v, boolean visited[]) 27 | { 28 | 29 | visited[v] = true; 30 | System.out.print(v + " "); 31 | 32 | 33 | Iterator i = adj[v].listIterator(); 34 | while (i.hasNext()) { 35 | int n = i.next(); 36 | if (!visited[n]) 37 | DFSUtil(n, visited); 38 | } 39 | } 40 | 41 | 42 | void DFS(int v) 43 | { 44 | 45 | boolean visited[] = new boolean[V]; 46 | 47 | 48 | DFSUtil(v, visited); 49 | } 50 | 51 | 52 | public static void main(String args[]) 53 | { 54 | Graph g = new Graph(4); 55 | 56 | g.addEdge(0, 1); 57 | g.addEdge(0, 2); 58 | g.addEdge(1, 2); 59 | g.addEdge(2, 0); 60 | g.addEdge(2, 3); 61 | g.addEdge(3, 3); 62 | 63 | System.out.println( 64 | "Following is Depth First Traversal " 65 | + "(starting from vertex 2)"); 66 | 67 | 68 | g.DFS(2); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /stack.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Stack{ 4 | int tos; 5 | int arr[]; 6 | 7 | public Stack(){ 8 | tos = -1; 9 | arr = new int[5]; 10 | } 11 | 12 | public Stack(int n){ 13 | tos = -1; 14 | arr = new int[n]; 15 | } 16 | 17 | public int getSize(){ 18 | return arr.length; 19 | } 20 | 21 | public void push(int data){ 22 | if(tos==arr.length-1){ 23 | System.out.println("OVERFLOW"); 24 | } 25 | else{ 26 | arr[++tos] = data; 27 | } 28 | } 29 | 30 | public int pop(){ 31 | if (tos==-1){ 32 | System.out.println("UNDERFLOW"); 33 | return 0; 34 | } 35 | else{ 36 | return(arr[tos--]); 37 | } 38 | } 39 | 40 | public void display(){ 41 | System.out.println("Stack is: "); 42 | for(int i=tos;i>=0;i--){ 43 | System.out.println(arr[i]); 44 | } 45 | } 46 | } 47 | 48 | class TestStack{ 49 | public static void main(String[] args) { 50 | Scanner inpt = new Scanner(System.in); 51 | Stack str = new Stack(5); 52 | System.out.println("Size of the Stack is: " + str.getSize()); 53 | 54 | int ch; 55 | do{ 56 | System.out.println("1. PUSH"); 57 | System.out.println("1. POP"); 58 | System.out.println("1. DISPLAY"); 59 | System.out.println("1. EXIT"); 60 | System.out.println("Enter Your Choice: "); 61 | ch = inpt.nextInt(); 62 | 63 | switch(ch){ 64 | case 1: 65 | System.out.println("ENTER THE VALUE TO BE PUSHED: "); 66 | str.push(inpt.nextInt()); 67 | break; 68 | case 2: 69 | break; 70 | case 3: 71 | break; 72 | case 4: 73 | break; 74 | } 75 | }while(ch>0 && ch<5); 76 | inpt.close(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /serach_in_circular-linklist.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,data): 3 | self.data = data; 4 | self.next = None; 5 | 6 | class CircularLinkedList: 7 | def __init__(self): 8 | self.head = Node(None); 9 | self.tail = Node(None); 10 | self.head.next = self.tail; 11 | self.tail.next = self.head; 12 | 13 | def add(self,data): 14 | 15 | newNode = Node(data); 16 | if self.head.data is None: 17 | 18 | 19 | self.head = newNode; 20 | self.tail = newNode; 21 | newNode.next = self.head; 22 | 23 | else: 24 | 25 | self.tail.next = newNode; 26 | self.tail = newNode; 27 | 28 | 29 | self.tail.next = self.head; 30 | 31 | def findNode(self,element): 32 | 33 | 34 | current = self.head; 35 | i = 1; 36 | f = 0; 37 | 38 | if(self.head == None): 39 | print("Empty list"); 40 | else: 41 | while(True): 42 | 43 | if(current.data == element): 44 | 45 | f += 1; 46 | break; 47 | 48 | 49 | current = current.next; 50 | i = i + 1; 51 | 52 | if(current == self.head): 53 | break; 54 | 55 | 56 | if(f > 0): 57 | print("element is present"); 58 | else: 59 | print("element is not present"); 60 | 61 | 62 | if __name__ == '__main__': 63 | 64 | 65 | ''' 66 | Circular Linked List we will be working on: 67 | 1 -> 2 -> 3 -> 4 -> 5 -> 6 68 | ''' 69 | circularLinkedList = CircularLinkedList(); 70 | 71 | 72 | circularLinkedList.add(1); 73 | circularLinkedList.add(2); 74 | circularLinkedList.add(3); 75 | circularLinkedList.add(4); 76 | circularLinkedList.add(5); 77 | circularLinkedList.add(6); 78 | 79 | 80 | circularLinkedList.findNode(2); 81 | circularLinkedList.findNode(7); 82 | -------------------------------------------------------------------------------- /width_of_bst.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node { 4 | public: 5 | int data; 6 | node* left; 7 | node* right; 8 | }; 9 | int getWidth(node* root, int level); 10 | int height(node* node); 11 | node* newNode(int data); 12 | int getMaxWidth(node* root){ 13 | int maxWidth = 0; 14 | int width; 15 | int h = height(root); 16 | int i; 17 | for (i = 1; i <= h; ++i) { 18 | width = getWidth(root, i); 19 | if (width > maxWidth) { 20 | maxWidth = width; 21 | } 22 | } 23 | return maxWidth; 24 | } 25 | int getWidth(node* root, int level){ 26 | if (root == NULL) { 27 | return 0; 28 | } 29 | if (level == 1) { 30 | return 1; 31 | } 32 | else if (level > 1) { 33 | return getWidth(root->left, level - 1) + getWidth(root->right, level - 1); 34 | } 35 | } 36 | int height(node* node){ 37 | if (node == NULL) { 38 | return 0; 39 | } 40 | int lHeight = height(node->left); 41 | int rHeight = height(node->right); 42 | return (lHeight > rHeight)? (lHeight + 1): (rHeight + 1); 43 | } 44 | node* newNode(int data){ 45 | node* Node = new node(); 46 | Node->data = data; 47 | Node->left = NULL; 48 | Node->right = NULL; 49 | return(Node); 50 | } 51 | int main(){ 52 | node *root = newNode(10); 53 | root->left = newNode(7); 54 | root->right = newNode(4); 55 | root->left->left = newNode(9); 56 | root->left->right = newNode(2); 57 | root->right->right = newNode(1); 58 | root->right->right->left = newNode(2); 59 | root->right->right->right = newNode(5); 60 | cout<<"Maximum width = " << getMaxWidth(root) << endl; 61 | return 0; 62 | } -------------------------------------------------------------------------------- /calculator in java.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.lang.Math; 4 | import java.util.Scanner; 5 | public class BasicCalculator { 6 | 7 | public static void main(String[] args) 8 | { 9 | double num1, num2; 10 | 11 | Scanner sc = new Scanner(System.in); 12 | 13 | System.out.println("Enter the numbers"); 14 | 15 | 16 | num1 = sc.nextDouble(); 17 | 18 | num2 = sc.nextDouble(); 19 | 20 | System.out.println("Enter the operator (+,-,*,/)"); 21 | 22 | char op = sc.next().charAt(0); 23 | 24 | double o = 0; 25 | 26 | switch (op) { 27 | 28 | // case to add two numbers 29 | case '+': 30 | o = num1 + num2; 31 | 32 | break; 33 | 34 | // case to subtract two numbers 35 | case '-': 36 | 37 | o = num1 - num2; 38 | 39 | break; 40 | 41 | // case to multiply two numbers 42 | case '*': 43 | 44 | o = num1 * num2; 45 | 46 | break; 47 | 48 | // case to divide two numbers 49 | case '/': 50 | 51 | o = num1 / num2; 52 | 53 | break; 54 | 55 | 56 | default: 57 | 58 | System.out.println("You enter wrong input"); 59 | break; 60 | } 61 | 62 | 63 | System.out.println("The final result:"); 64 | 65 | System.out.println(); 66 | 67 | System.out.println(num1 + " " + op + " " + num2 68 | + " = " + o); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /ReverseLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Link list node */ 5 | struct Node { 6 | int data; 7 | struct Node* next; 8 | Node(int data) 9 | { 10 | this->data = data; 11 | next = NULL; 12 | } 13 | }; 14 | 15 | struct LinkedList { 16 | Node* head; 17 | LinkedList() { head = NULL; } 18 | 19 | /* Function to reverse the linked list */ 20 | void reverse() 21 | { 22 | // Initialize current, previous and next pointers 23 | Node* current = head; 24 | Node *prev = NULL, *next = NULL; 25 | 26 | while (current != NULL) { 27 | // Store next 28 | next = current->next; 29 | // Reverse current node's pointer 30 | current->next = prev; 31 | // Move pointers one position ahead. 32 | prev = current; 33 | current = next; 34 | } 35 | head = prev; 36 | } 37 | 38 | /* Function to print linked list */ 39 | void print() 40 | { 41 | struct Node* temp = head; 42 | while (temp != NULL) { 43 | cout << temp->data << " "; 44 | temp = temp->next; 45 | } 46 | } 47 | 48 | void push(int data) 49 | { 50 | Node* temp = new Node(data); 51 | temp->next = head; 52 | head = temp; 53 | } 54 | }; 55 | 56 | /* Driver code*/ 57 | int main() 58 | { 59 | /* Start with the empty list */ 60 | LinkedList ll; 61 | ll.push(20); 62 | ll.push(4); 63 | ll.push(15); 64 | ll.push(85); 65 | 66 | cout << "Given linked list\n"; 67 | ll.print(); 68 | 69 | ll.reverse(); 70 | 71 | cout << "\nReversed Linked list \n"; 72 | ll.print(); 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /jobseq.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | def printJobScheduling(arr): 5 | n = len(arr) 6 | 7 | # arr[i][0] = job_id, arr[i][1] = deadline, arr[i][2] = profit 8 | 9 | # sorting the array on the 10 | # basis of their deadlines 11 | arr.sort(key=lambda x: x[1]) 12 | 13 | # initialise the result array and maxHeap 14 | result = [] 15 | maxHeap = [] 16 | 17 | # starting the iteration from the end 18 | for i in range(n - 1, -1, -1): 19 | 20 | # calculate slots between two deadlines 21 | if i == 0: 22 | slots_available = arr[i][1] 23 | else: 24 | slots_available = arr[i][1] - arr[i - 1][1] 25 | 26 | # include the profit of job(as priority), deadline 27 | # and job_id in maxHeap 28 | # note we push negative value in maxHeap to convert 29 | # min heap to max heap in python 30 | heapq.heappush(maxHeap, (-arr[i][2], arr[i][1], arr[i][0])) 31 | 32 | while slots_available and maxHeap: 33 | 34 | # get the job with max_profit 35 | profit, deadline, job_id = heapq.heappop(maxHeap) 36 | 37 | # reduce the slots 38 | slots_available -= 1 39 | 40 | # include the job in the result array 41 | result.append([job_id, deadline]) 42 | 43 | 44 | result.sort(key=lambda x: x[1]) 45 | 46 | for job in result: 47 | print(job[0], end=" ") 48 | print() 49 | 50 | 51 | 52 | if __name__ == '__main__': 53 | arr = [['a', 2, 100], 54 | ['b', 1, 19], 55 | ['c', 2, 27], 56 | ['d', 1, 25], 57 | ['e', 3, 15]] 58 | 59 | print("Following is maximum profit sequence of jobs") 60 | 61 | 62 | printJobScheduling(arr) 63 | -------------------------------------------------------------------------------- /Mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { //swap the content of a and b 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i> n; 59 | int arr[n]; //create an array with given number of elements 60 | cout << "Enter elements:" << endl; 61 | for(int i = 0; i> arr[i]; 63 | } 64 | cout << "Array before Sorting: "; 65 | display(arr, n); 66 | mergeSort(arr, 0, n-1); //(n-1) for last index 67 | cout << "Array after Sorting: "; 68 | display(arr, n); 69 | } 70 | -------------------------------------------------------------------------------- /RotatedBinarySearch.java: -------------------------------------------------------------------------------- 1 | // Search in Rotated Sorted Array 2 | // URL: https://leetcode.com/problems/search-in-rotated-sorted-array/ 3 | 4 | package com.akshat; 5 | 6 | public class RotatedBinarySearch { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] nums = {4, 5, 6, 7, 0, 1, 2}; 11 | int target = 0; 12 | 13 | System.out.println(search(nums, target)); 14 | 15 | } 16 | 17 | static int search(int[] nums, int target) { 18 | int pivot = findPivot(nums); 19 | if (pivot == -1){ 20 | return bs(nums, target, 0, nums.length-1); 21 | } 22 | if (nums[pivot] == target){ 23 | return pivot; 24 | } 25 | if (target >= nums[0]){ 26 | return bs(nums, target, 0, pivot-1); 27 | } 28 | return bs(nums, target, pivot+1, nums.length-1); 29 | } 30 | 31 | static int bs(int[] nums, int target, int start, int end){ 32 | while (start <= end){ 33 | int mid = start + (end - start) / 2; 34 | if (target < nums[mid]){ 35 | end = mid - 1; 36 | } 37 | else if (target > nums[mid]){ 38 | start = mid + 1; 39 | } 40 | else{ 41 | return mid; 42 | } 43 | } 44 | return -1; 45 | } 46 | 47 | static int findPivot(int[] nums){ 48 | int start = 0; 49 | int end = nums.length - 1; 50 | while (start <= end){ 51 | int mid = start + (end - start) / 2; 52 | if (mid < end && nums[mid] > nums[mid + 1]){ 53 | return mid; 54 | } 55 | if (mid > start && nums[mid] < nums[mid - 1]){ 56 | return mid-1; 57 | } 58 | if (nums[mid] <= nums[start]){ 59 | end = mid - 1; 60 | } 61 | else{ 62 | start = mid + 1; 63 | } 64 | } 65 | return -1; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /Quick-Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Quicksort { 4 | 5 | // method to find the partition position 6 | static int partition(int array[], int low, int high) { 7 | 8 | // choose the rightmost element as pivot 9 | int pivot = array[high]; 10 | 11 | // pointer for greater element 12 | int i = (low - 1); 13 | 14 | // traverse through all elements 15 | // compare each element with pivot 16 | for (int j = low; j < high; j++) { 17 | if (array[j] <= pivot) { 18 | 19 | // if element smaller than pivot is found 20 | // swap it with the greater element pointed by i 21 | i++; 22 | 23 | // swapping element at i with element at j 24 | int temp = array[i]; 25 | array[i] = array[j]; 26 | array[j] = temp; 27 | } 28 | 29 | } 30 | 31 | // swapt the pivot element with the greater element specified by i 32 | int temp = array[i + 1]; 33 | array[i + 1] = array[high]; 34 | array[high] = temp; 35 | 36 | // return the position from where partition is done 37 | return (i + 1); 38 | } 39 | 40 | static void quickSort(int array[], int low, int high) { 41 | if (low < high) { 42 | 43 | // find pivot element such that 44 | // elements smaller than pivot are on the left 45 | // elements greater than pivot are on the right 46 | int pi = partition(array, low, high); 47 | 48 | // recursive call on the left of pivot 49 | quickSort(array, low, pi - 1); 50 | 51 | // recursive call on the right of pivot 52 | quickSort(array, pi + 1, high); 53 | } 54 | } 55 | } 56 | 57 | // Main class 58 | class Main { 59 | public static void main(String args[]) { 60 | 61 | int[] data = { 8, 7, 2, 1, 0, 9, 6 }; 62 | System.out.println("Unsorted Array"); 63 | System.out.println(Arrays.toString(data)); 64 | 65 | int size = data.length; 66 | 67 | // call quicksort() on array data 68 | Quicksort.quickSort(data, 0, size - 1); 69 | 70 | System.out.println("Sorted Array in Ascending Order "); 71 | System.out.println(Arrays.toString(data)); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /SplitArrayLargestSum.java: -------------------------------------------------------------------------------- 1 | // Split Array Largest Sum 2 | // URL: https://leetcode.com/problems/split-array-largest-sum/ 3 | 4 | package com.akshat; 5 | 6 | public class SplitArrayLargestSum { 7 | 8 | public static void main(String[] args) { 9 | 10 | int[] nums = {7, 2, 5, 10, 8}; 11 | int m = 2; 12 | 13 | System.out.println(splitArray(nums, m)); 14 | 15 | } 16 | 17 | static int splitArray(int[] nums, int m) { 18 | int start = 0; 19 | int end = 0; 20 | 21 | for (int i = 0; i < nums.length; i++) { 22 | start = Math.max(start, nums[i]); // in the end of the loop this will contain the max item of the array 23 | end += nums[i]; 24 | } 25 | 26 | // binary search 27 | while (start < end) { 28 | // try for the middle as potential ans 29 | int mid = start + (end - start) / 2; 30 | 31 | // calculate how many pieces you can divide this in with this max sum 32 | int sum = 0; 33 | int pieces = 1; 34 | for (int i = 0; i < nums.length; i++) { 35 | int num = nums[i]; 36 | if (sum + num > mid) { 37 | // you cannot add this in this subarray, make new one 38 | // say you add this num in new subarray, then sum = num 39 | sum = num; 40 | pieces++; 41 | } else { 42 | sum += num; 43 | } 44 | } 45 | 46 | if (pieces > m) { 47 | start = mid + 1; 48 | } else { 49 | end = mid; 50 | } 51 | 52 | } 53 | return end; // here start == end 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /queue.java: -------------------------------------------------------------------------------- 1 | public class queue { 2 | private int[] data; 3 | 4 | private static final int DEFAULT_SIZE = 10; 5 | 6 | int end = 0; 7 | 8 | public queue(){ 9 | this(DEFAULT_SIZE); 10 | } 11 | 12 | public queue(int size){ 13 | this.data = new int[size]; 14 | } 15 | 16 | public boolean isFull() { 17 | return end == data.length; // ptr is at last index 18 | } 19 | 20 | public boolean isEmpty(){ 21 | return end == 0; 22 | } 23 | 24 | public boolean insert(int item){ 25 | if(isFull()){ 26 | return false; 27 | } 28 | data[end++]=item; 29 | return true; 30 | } 31 | 32 | public int remove() throws Exception { 33 | if(isEmpty()){ 34 | throw new Exception("queue is empty"); 35 | } 36 | 37 | int removed=data[0]; 38 | 39 | System.arraycopy(data, 1, data, 0, data.length - 1); 40 | end--; 41 | return removed; 42 | 43 | } 44 | 45 | public int front() throws Exception{ 46 | if(isEmpty()){ 47 | throw new Exception("queue is Empty"); 48 | } 49 | return data[0]; 50 | } 51 | 52 | public void display(){ 53 | System.out.println("queue=>"); 54 | for (int i = 0; i < end; i++) { 55 | System.out.print(data[i] + " <- "); 56 | } 57 | System.out.println("END"); 58 | } 59 | 60 | public static void main(String[] args) throws Exception { 61 | queue queue = new queue(); 62 | queue.insert(1); 63 | queue.insert(2); 64 | queue.insert(3); 65 | queue.insert(4); 66 | queue.insert(5); 67 | queue.insert(6); 68 | queue.insert(7); 69 | queue.insert(8); 70 | queue.insert(9); 71 | queue.insert(10); 72 | 73 | 74 | queue.display(); 75 | 76 | System.out.println(queue.remove()); 77 | System.out.println(queue.remove()); 78 | System.out.println(queue.remove()); 79 | System.out.println(queue.remove()); 80 | System.out.println(queue.remove()); 81 | 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /DFS in java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | // This class represents a 5 | // directed graph using adjacency 6 | // list representation 7 | class Graph { 8 | private int V; // No. of vertices 9 | 10 | // Array of lists for 11 | // Adjacency List Representation 12 | private LinkedList adj[]; 13 | 14 | // Constructor 15 | @SuppressWarnings("unchecked") Graph(int v) 16 | { 17 | V = v; 18 | adj = new LinkedList[v]; 19 | for (int i = 0; i < v; ++i) 20 | adj[i] = new LinkedList(); 21 | } 22 | 23 | // Function to add an edge into the graph 24 | void addEdge(int v, int w) 25 | { 26 | adj[v].add(w); // Add w to v's list. 27 | } 28 | 29 | // A function used by DFS 30 | void DFSUtil(int v, boolean visited[]) 31 | { 32 | // Mark the current node as visited and print it 33 | visited[v] = true; 34 | System.out.print(v + " "); 35 | 36 | // Recur for all the vertices adjacent to this 37 | // vertex 38 | Iterator i = adj[v].listIterator(); 39 | while (i.hasNext()) { 40 | int n = i.next(); 41 | if (!visited[n]) 42 | DFSUtil(n, visited); 43 | } 44 | } 45 | 46 | // The function to do DFS traversal. 47 | // It uses recursive 48 | // DFSUtil() 49 | void DFS(int v) 50 | { 51 | // Mark all the vertices as 52 | // not visited(set as 53 | // false by default in java) 54 | boolean visited[] = new boolean[V]; 55 | 56 | // Call the recursive helper 57 | // function to print DFS 58 | // traversal 59 | DFSUtil(v, visited); 60 | } 61 | 62 | // Driver's Code 63 | public static void main(String args[]) 64 | { 65 | Graph g = new Graph(4); 66 | 67 | g.addEdge(0, 1); 68 | g.addEdge(0, 2); 69 | g.addEdge(1, 2); 70 | g.addEdge(2, 0); 71 | g.addEdge(2, 3); 72 | g.addEdge(3, 3); 73 | 74 | System.out.println( 75 | "Following is Depth First Traversal " 76 | + "(starting from vertex 2)"); 77 | 78 | // Function call 79 | g.DFS(2); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /DFS using Java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | // This class represents a 5 | // directed graph using adjacency 6 | // list representation 7 | class Graph { 8 | private int V; // No. of vertices 9 | 10 | // Array of lists for 11 | // Adjacency List Representation 12 | private LinkedList adj[]; 13 | 14 | // Constructor 15 | @SuppressWarnings("unchecked") Graph(int v) 16 | { 17 | V = v; 18 | adj = new LinkedList[v]; 19 | for (int i = 0; i < v; ++i) 20 | adj[i] = new LinkedList(); 21 | } 22 | 23 | // Function to add an edge into the graph 24 | void addEdge(int v, int w) 25 | { 26 | adj[v].add(w); // Add w to v's list. 27 | } 28 | 29 | // A function used by DFS 30 | void DFSUtil(int v, boolean visited[]) 31 | { 32 | // Mark the current node as visited and print it 33 | visited[v] = true; 34 | System.out.print(v + " "); 35 | 36 | // Recur for all the vertices adjacent to this 37 | // vertex 38 | Iterator i = adj[v].listIterator(); 39 | while (i.hasNext()) { 40 | int n = i.next(); 41 | if (!visited[n]) 42 | DFSUtil(n, visited); 43 | } 44 | } 45 | 46 | // The function to do DFS traversal. 47 | // It uses recursive 48 | // DFSUtil() 49 | void DFS(int v) 50 | { 51 | // Mark all the vertices as 52 | // not visited(set as 53 | // false by default in java) 54 | boolean visited[] = new boolean[V]; 55 | 56 | // Call the recursive helper 57 | // function to print DFS 58 | // traversal 59 | DFSUtil(v, visited); 60 | } 61 | 62 | // Driver's Code 63 | public static void main(String args[]) 64 | { 65 | Graph g = new Graph(4); 66 | 67 | g.addEdge(0, 1); 68 | g.addEdge(0, 2); 69 | g.addEdge(1, 2); 70 | g.addEdge(2, 0); 71 | g.addEdge(2, 3); 72 | g.addEdge(3, 3); 73 | 74 | System.out.println( 75 | "Following is Depth First Traversal " 76 | + "(starting from vertex 2)"); 77 | 78 | // Function call 79 | g.DFS(2); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /DiameterofBT.java: -------------------------------------------------------------------------------- 1 | // Recursive optimized Java program to find the diameter of 2 | // a Binary Tree 3 | 4 | // Class containing left and right child of current 5 | // node and key value 6 | class Node { 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int item) 11 | { 12 | data = item; 13 | left = right = null; 14 | } 15 | } 16 | 17 | // Class to print the Diameter 18 | class BinaryTree { 19 | Node root; 20 | 21 | // Method to calculate the diameter and return it to 22 | // main 23 | int diameter(Node root) 24 | { 25 | // base case if tree is empty 26 | if (root == null) 27 | return 0; 28 | 29 | // get the height of left and right sub-trees 30 | int lheight = height(root.left); 31 | int rheight = height(root.right); 32 | 33 | // get the diameter of left and right sub-trees 34 | int ldiameter = diameter(root.left); 35 | int rdiameter = diameter(root.right); 36 | 37 | /* Return max of following three 38 | 1) Diameter of left subtree 39 | 2) Diameter of right subtree 40 | 3) Height of left subtree + height of right 41 | subtree + 1 42 | */ 43 | return Math.max(lheight + rheight + 1, 44 | Math.max(ldiameter, rdiameter)); 45 | } 46 | 47 | // A wrapper over diameter(Node root) 48 | int diameter() { return diameter(root); } 49 | 50 | // The function Compute the "height" of a tree. Height 51 | // is the number of nodes along the longest path from 52 | // the root node down to the farthest leaf node. 53 | static int height(Node node) 54 | { 55 | // base case tree is empty 56 | if (node == null) 57 | return 0; 58 | 59 | // If tree is not empty then height = 1 + max of 60 | // left height and right heights 61 | return (1 62 | + Math.max(height(node.left), 63 | height(node.right))); 64 | } 65 | 66 | // Driver Code 67 | public static void main(String args[]) 68 | { 69 | // creating a binary tree and entering the nodes 70 | BinaryTree tree = new BinaryTree(); 71 | tree.root = new Node(1); 72 | tree.root.left = new Node(2); 73 | tree.root.right = new Node(3); 74 | tree.root.left.left = new Node(4); 75 | tree.root.left.right = new Node(5); 76 | 77 | // Function Call 78 | System.out.println( 79 | "The diameter of given binary tree is : " 80 | + tree.diameter()); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /HeapSort.java: -------------------------------------------------------------------------------- 1 | class HeapSort{ 2 | void print(int array[],int size){ 3 | int index = 0; 4 | while(index < size){ 5 | System.out.print(" " + array[index]); 6 | index++; 7 | } 8 | } 9 | void heapify(int arr[], int size, int index){ 10 | int maximum = index; 11 | int leftChild = 2*index + 1; 12 | int rightChild = 2*index + 2; 13 | int swapper; 14 | 15 | //now check if right and left child are greater than parent and the right and left child index are not out of bound. 16 | if(leftChild < size && arr[leftChild] > arr[maximum]){ 17 | maximum = leftChild; 18 | } 19 | if(rightChild < size && arr[rightChild] > arr[maximum]){ 20 | maximum = rightChild; 21 | } 22 | 23 | //if maximum is not equal to its initial declaration(root) then swap. 24 | if(maximum != index){ 25 | swapper = arr[index]; 26 | arr[index] = arr[maximum]; 27 | arr[maximum] = swapper; 28 | 29 | //we will recursively heapify the affected sub-tree 30 | heapify(arr,size,maximum); 31 | } 32 | } 33 | 34 | void sort(int array[]){ 35 | int size = array.length; 36 | int swapper; 37 | 38 | //building max heap using heapify 39 | int index = (size/2) - 1; 40 | while(index >=0){ 41 | heapify(array,size,index); 42 | index--; 43 | } 44 | 45 | //We will extract elements from heap one by one and reduce size of the heap (assuming part of array is sorted controlled by index) 46 | for(index = size -1; index > 0; index--){ 47 | //largest resides on root in max-heap 48 | swapper = array[0]; 49 | array[0] = array[index]; 50 | array[index] = swapper; 51 | 52 | //call heapify on root of reduced heap 53 | heapify(array,index, 0); 54 | } 55 | } 56 | 57 | 58 | public static void main(String args[]) 59 | { 60 | int array[] = { 3, 1, 4, 9, 8, 6 }; 61 | int size = array.length; 62 | HeapSort object = new HeapSort(); 63 | object.sort(array); 64 | System.out.println("After Heap Sort: "); 65 | object.print(array,size); 66 | } 67 | } -------------------------------------------------------------------------------- /CyclicSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | Cyclic Sort-> 5 | When given number from range 1 to N -> use cyclic sort. 6 | Array-> 3,5,2,1,4 {Here the numbers are jumbled but are from 1 to 5} 7 | Let N be 5 8 | When the array is sorted in that case all the numbers are going to be at their correct index 9 | So after sorting -> 1,2,3,4,5 { here after sorting the numbers will be at val-1 index} 10 | Index=value-1 because index starts from 0 11 | Might be you have given the array find the missing number 12 | You're given numbers from 1 to n find the duplicate number? 13 | 14 | Explanation-> 15 | Array-> 3,5,2,1,4 16 | 1. Check is 3 at the correct index if not do 3-1=2 (index=value -1) the swap with correct index. 17 | 2,5,3,1,4 18 | 2. After swapping we know that 3 is at correct position now, but we do not know whether the other number that came 19 | at the position of 3 is correct or not. So, Check again. 20 | as 2 is not at correct index of 2-1=1 we would swap it with the correct index. 21 | 5,2,3,1,4 22 | we would again check for 5 23 | 4,2,3,1,5 24 | again for 4 25 | 1,2,3,4,5 26 | now we will check whether 1 is at correct position, if it is then move forward and so on. 27 | 28 | We know that every unique item is only getting swapped once. 29 | Here we are not incrementing i when we are swapping so that might in more than n iterations of the loop. 30 | Worst Case-> 31 | N-1(Swaps) 32 | N-1 + N 33 | 2N-1 34 | O(N) ->Linear 35 | 36 | 37 | 38 | 39 | */ 40 | 41 | public class CyclicSort { 42 | public static void main(String[] args) { 43 | int[] arr={5,4,2,1,3}; 44 | sort(arr); 45 | System.out.println(Arrays.toString(arr)); 46 | } 47 | 48 | static void sort(int[] arr){ 49 | int i =0; 50 | while(i adj[]; /* adjacency list */ 7 | private Queue que; /* maintaining a queue */ 8 | BFSTraversal(int v) 9 | { 10 | node = v; 11 | adj = new LinkedList[node]; 12 | for (int i=0; i(); 15 | } 16 | que = new LinkedList(); 17 | } 18 | void insertEdge(int v,int w) 19 | { 20 | adj[v].add(w); /* adding an edge to the adjacency list (edges are bidirectional in this example) */ 21 | } 22 | void BFS(int n) 23 | { 24 | boolean nodes[] = new boolean[node]; /* initialize boolean array for holding the data */ 25 | int a = 0; 26 | nodes[n]=true; 27 | que.add(n); /* root node is added to the top of the queue */ 28 | while (que.size() != 0) 29 | { 30 | n = que.poll(); /* remove the top element of the queue */ 31 | System.out.print(n+" "); /* print the top element of the queue */ 32 | for (int i = 0; i < adj[n].size(); i++) /* iterate through the linked list and push all neighbors into queue */ 33 | { 34 | a = adj[n].get(i); 35 | if (!nodes[a]) /* only insert nodes into queue if they have not been explored already */ 36 | { 37 | nodes[a] = true; 38 | que.add(a); 39 | } 40 | } 41 | } 42 | } 43 | public static void main(String args[]) 44 | { 45 | BFSTraversal graph = new BFSTraversal(6); 46 | graph.insertEdge(0, 1); 47 | graph.insertEdge(0, 3); 48 | graph.insertEdge(0, 4); 49 | graph.insertEdge(4, 5); 50 | graph.insertEdge(3, 5); 51 | graph.insertEdge(1, 2); 52 | graph.insertEdge(1, 0); 53 | graph.insertEdge(2, 1); 54 | graph.insertEdge(4, 1); 55 | graph.insertEdge(3, 1); 56 | graph.insertEdge(5, 4); 57 | graph.insertEdge(5, 3); 58 | System.out.println("Breadth First Traversal for the graph is:"); 59 | graph.BFS(0); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /queue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define size 5 4 | 5 | struct queue 6 | { 7 | int front, rear; 8 | int arr[size]; 9 | } s1; 10 | 11 | int enqueue(int arr[], int front, int rear) 12 | { 13 | int qnew; 14 | if (s1.front == s1.rear + 1 || s1.front == 0 && s1.rear == size - 1) 15 | { 16 | printf("\nQueue is full"); 17 | } 18 | else 19 | { 20 | printf("\nEnter a element - "); 21 | scanf("%d", &qnew); 22 | //s1.rear = (s1.rear + 1) % size; 23 | 24 | s1.arr[s1.rear] = qnew; 25 | if (s1.front == -1) 26 | { 27 | s1.front++; 28 | } 29 | s1.rear++; 30 | } 31 | } 32 | 33 | int dequeue(int arr[], int front, int rear) 34 | { 35 | if (s1.front == -1) 36 | { 37 | printf("\nQueue is empty"); 38 | } 39 | else 40 | { 41 | if (s1.front == s1.rear) 42 | { 43 | s1.front = -1; 44 | s1.rear = -1; 45 | } 46 | else 47 | { 48 | s1.front = (s1.front + 1) % size; 49 | } 50 | } 51 | } 52 | 53 | int display(int arr[], int front, int rear) 54 | { 55 | if (s1.front == -1) 56 | { 57 | printf("\nQueue is empty"); 58 | } 59 | else 60 | { 61 | printf("\n Items -> "); 62 | for (int i = s1.front; i != s1.rear; i = (i + 1) % size) 63 | { 64 | printf("%d ", s1.arr[i]); 65 | } 66 | } 67 | } 68 | 69 | int main() 70 | { 71 | int ch; 72 | s1.front = -1; 73 | s1.rear = -1; 74 | s1.arr[size]; 75 | printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\nEnter choice - "); 76 | do 77 | { 78 | scanf("%d", &ch); 79 | switch (ch) 80 | { 81 | case 1: 82 | enqueue(s1.arr, s1.front, s1.rear); 83 | break; 84 | case 2: 85 | dequeue(s1.arr, s1.front, s1.rear); 86 | break; 87 | case 3: 88 | display(s1.arr, s1.front, s1.rear); 89 | break; 90 | case 4: 91 | printf("\nThanks"); 92 | exit(0); 93 | // break; 94 | default: 95 | printf("\nInvalid choice"); 96 | } 97 | printf("\nEnter choice - "); 98 | } while (ch != 4); 99 | return 0; 100 | } -------------------------------------------------------------------------------- /Find Count of Single Valued Subtrees.java: -------------------------------------------------------------------------------- 1 | // Java program to find count of single valued subtrees 2 | 3 | /* Class containing left and right child of current 4 | node and key value*/ 5 | class Node 6 | { 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int item) 11 | { 12 | data = item; 13 | left = right = null; 14 | } 15 | } 16 | 17 | class Count 18 | { 19 | int count = 0; 20 | } 21 | 22 | class BinaryTree 23 | { 24 | Node root; 25 | Count ct = new Count(); 26 | 27 | // This function increments count by number of single 28 | // valued subtrees under root. It returns true if subtree 29 | // under root is Singly, else false. 30 | boolean countSingleRec(Node node, Count c) 31 | { 32 | // Return false to indicate NULL 33 | if (node == null) 34 | return true; 35 | 36 | // Recursively count in left and right subtrees also 37 | boolean left = countSingleRec(node.left, c); 38 | boolean right = countSingleRec(node.right, c); 39 | 40 | // If any of the subtrees is not singly, then this 41 | // cannot be singly. 42 | if (left == false || right == false) 43 | return false; 44 | 45 | // If left subtree is singly and non-empty, but data 46 | // doesn't match 47 | if (node.left != null && node.data != node.left.data) 48 | return false; 49 | 50 | // Same for right subtree 51 | if (node.right != null && node.data != node.right.data) 52 | return false; 53 | 54 | // If none of the above conditions is true, then 55 | // tree rooted under root is single valued, increment 56 | // count and return true. 57 | c.count++; 58 | return true; 59 | } 60 | 61 | // This function mainly calls countSingleRec() 62 | // after initializing count as 0 63 | int countSingle() 64 | { 65 | return countSingle(root); 66 | } 67 | 68 | int countSingle(Node node) 69 | { 70 | // Recursive function to count 71 | countSingleRec(node, ct); 72 | return ct.count; 73 | } 74 | 75 | // Driver program to test above functions 76 | public static void main(String args[]) 77 | { 78 | /* Let us construct the below tree 79 | 5 80 | / \ 81 | 4 5 82 | / \ \ 83 | 4 4 5 */ 84 | BinaryTree tree = new BinaryTree(); 85 | tree.root = new Node(5); 86 | tree.root.left = new Node(4); 87 | tree.root.right = new Node(5); 88 | tree.root.left.left = new Node(4); 89 | tree.root.left.right = new Node(4); 90 | tree.root.right.right = new Node(5); 91 | 92 | System.out.println("The count of single valued sub trees is : " 93 | + tree.countSingle()); 94 | } 95 | } 96 | 97 | // This code has been contributed by Mayank Jaiswal 98 | -------------------------------------------------------------------------------- /InsertionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /* 4 | Insertion Sort-> 5 | Array-> 5,3,4,1,2 6 | For every index put that index element at the correct index of LHS. 7 | 1st pass- 8 | i=1; 9 | j=0 10 | key=arr[i]=3 11 | 5,3,4,1,2 12 | j 13 | 3,5,4,1,2 14 | 2nd pass- 15 | i=2; 16 | j=1; 17 | 3,5,4,1,2 18 | j key=4 19 | j >= 0 && arr[j] > key? 20 | arr[j + 1] = arr[j]; 21 | j = j - 1; 22 | 3,5,5,1,2 23 | j key=4 24 | j >= 0 && arr[j] > key? 25 | arr[j + 1] = arr[j]; 26 | j = j - 1; 27 | 3,3,5,1,2 28 | arr[j+1]=key 29 | 3,4,5,1,2 30 | 3rd pass- 31 | 4th pass- 32 | 33 | Time complexity-> 34 | 1.Worst Case-> O(n^2) 35 | 2.Best Case-> O(n) 36 | 37 | Why to use Insertion sort? 38 | 1.Adaptive : Steps get reduced if array is sorted i.e. no.of swaps are reduced as compared to bubble sort. 39 | 2.Stable Sorting Algorithm 40 | 3.Used for smaller values of n: works good when array is partially sorted. it takes part in hybrid sorting algorithm. 41 | 42 | 43 | */ 44 | 45 | public class InsertionSort { 46 | public static void main(String[] args) { 47 | int[] arr = {6,5,4,3,7,9,1,2,33,45,656,78,43,23,321,535,232,574,67}; 48 | // sort(arr); 49 | insertionSort(arr); 50 | System.out.println(Arrays.toString(arr)); 51 | } 52 | 53 | static void anotherMethod(int[] arr) 54 | { 55 | int n = arr.length; 56 | for (int i = 1; i < n; ++i) { 57 | int key = arr[i]; 58 | int j = i - 1; 59 | 60 | /* Move elements of arr[0..i-1], that are 61 | greater than key, to one position ahead 62 | of their current position */ 63 | while (j >= 0 && arr[j] > key) { 64 | arr[j + 1] = arr[j]; 65 | j = j - 1; 66 | 67 | } 68 | arr[j + 1] = key; 69 | 70 | } 71 | } 72 | 73 | static void insertionSort(int[] arr){ 74 | for(int i=0;i<=arr.length -2;i++){ 75 | for(int j=i+1; j>0;j--){ 76 | if(arr[j] 0 and stack[-1] > arr[i]: 13 | ans.append(stack[-1]) 14 | elif len(stack) > 0 and stack[-1] < arr[i]: 15 | 16 | while (len(stack) != 0 and stack[-1] <= arr[i]): 17 | stack.pop() 18 | 19 | if len(stack) == 0: 20 | ans.append(-1) 21 | else: 22 | ans.append(stack[-1]) 23 | stack.append(arr[i]) 24 | return ans[::-1] 25 | 26 | 27 | 28 | #Q-2 Stock span problem.py 29 | 30 | class Solution: 31 | 32 | #Function to calculate the span of stock’s price for all n days. 33 | def calculateSpan(self,arr,n): 34 | s=[] 35 | ans= [] 36 | 37 | for i in range (0,n): 38 | 39 | 40 | if len(s)==0: 41 | ans.append(-1) 42 | elif (len(s)>0 and s[-1][0]>arr[i]): 43 | ans.append(s[-1][1]) 44 | elif (len(s)>0 and s[-1][0] int: 62 | n=len(arr) 63 | def right(arr): 64 | n=len(arr) 65 | stack =[] 66 | ans = [] 67 | index=n 68 | for i in range (n-1,-1,-1): 69 | if len(stack)==0: 70 | ans.append(index) 71 | elif len(stack)>0 and stack[-1][0] < arr[i]: 72 | ans.append(stack[-1][1]) 73 | elif len(stack)>0 and stack[-1][0] >= arr[i]: 74 | 75 | while (len(stack) !=0 and stack[-1][0] >= arr[i]): 76 | stack.pop() 77 | 78 | if len(stack)==0: 79 | ans.append(index) 80 | else: 81 | ans.append(stack[-1][1]) 82 | stack.append([arr[i],i]) 83 | return ans[::-1] 84 | 85 | def left(arr): 86 | n=len(arr) 87 | stack =[] 88 | ans = [] 89 | 90 | for i in range (0,n): 91 | if len(stack)==0: 92 | ans.append(-1) 93 | elif len(stack)>0 and stack[-1][0] < arr[i]: 94 | ans.append(stack[-1][1]) 95 | elif len(stack)>0 and stack[-1][0] >= arr[i]: 96 | 97 | while (len(stack) !=0 and stack[-1][0] >= arr[i]): 98 | stack.pop() 99 | 100 | if len(stack)==0: 101 | ans.append(-1) 102 | else: 103 | ans.append(stack[-1][1]) 104 | stack.append([arr[i],i]) 105 | return ans 106 | Left= left(arr) 107 | Right= right(arr) 108 | width=[] 109 | area=[] 110 | for i in range (n): 111 | width.append(Right[i]-Left[i]-1) 112 | area.append(width[i]*arr[i]) 113 | return max(area) 114 | 115 | 116 | 117 | Q-4 Max area rectangle in Binary matrix.py 118 | 119 | class Solution: 120 | def maximalRectangle(self, arr: List[List[str]]) -> int: 121 | n=len(arr) 122 | m=len(arr[0]) 123 | def mah(arr): 124 | n=len(arr) 125 | stack =[] 126 | ans1 = [] 127 | index=n 128 | for i in range (n-1,-1,-1): 129 | if len(stack)==0: 130 | ans1.append(index) 131 | elif len(stack)>0 and stack[-1][0] < arr[i]: 132 | ans1.append(stack[-1][1]) 133 | elif len(stack)>0 and stack[-1][0] >= arr[i]: 134 | while (len(stack) !=0 and stack[-1][0] >= arr[i]): 135 | stack.pop() 136 | 137 | if len(stack)==0: 138 | ans1.append(index) 139 | else: 140 | ans1.append(stack[-1][1]) 141 | stack.append([arr[i],i]) 142 | ans1= ans1[::-1] 143 | stack =[] 144 | ans2 = [] 145 | 146 | for i in range (0,n): 147 | if len(stack)==0: 148 | ans2.append(-1) 149 | elif len(stack)>0 and stack[-1][0] < arr[i]: 150 | ans2.append(stack[-1][1]) 151 | elif len(stack)>0 and stack[-1][0] >= arr[i]: 152 | while (len(stack) !=0 and stack[-1][0] >= arr[i]): 153 | stack.pop() 154 | if len(stack)==0: 155 | ans2.append(-1) 156 | else: 157 | ans2.append(stack[-1][1]) 158 | stack.append([arr[i],i]) 159 | ans = -100000000000 160 | for i in range (n): 161 | ans = max(ans,((ans1[i]-ans2[i]-1)*arr[i])) 162 | return ans 163 | 164 | v=[] 165 | for i in range (m): 166 | v.append(int(arr[0][i])) 167 | mx = mah(v) 168 | for i in range (1,n): 169 | for j in range (m): 170 | if arr[i][j]=='0': 171 | v[j]=0 172 | else: 173 | v[j]=v[j]+int(arr[i][j]) 174 | mx = max(mx,mah(v)) 175 | return mx 176 | 177 | Q-5 The celebrity Problem.py 178 | 179 | 180 | class Solution: 181 | 182 | #Function to find if there is a celebrity in the party or not. 183 | def celebrity(self, M, n): 184 | ans = -1 185 | for i in range (n): 186 | 187 | if 1 in M[i]: 188 | pass 189 | else: 190 | ans=i 191 | 192 | if ans == -1: 193 | return -1 194 | if ans+1 == n: 195 | for i in range (ans-1, -1 , -1): 196 | if 1 not in M[i]: 197 | return -1 198 | else: 199 | pass 200 | for j in range (ans, n): 201 | if 1 in M[i]: 202 | pass 203 | else: 204 | return -1 205 | 206 | return ans 207 | 208 | #Q-6 Maximum of minimum for every window size.py 209 | 210 | 211 | def maxmin_window(arr): 212 | 213 | n=len(arr) 214 | stack =[] 215 | ans1 = [] 216 | index=n 217 | for i in range (n-1,-1,-1): 218 | if len(stack)==0: 219 | ans1.append(index) 220 | elif len(stack)>0 and stack[-1][0] < arr[i]: 221 | ans1.append(stack[-1][1]) 222 | elif len(stack)>0 and stack[-1][0] >= arr[i]: 223 | while (len(stack) !=0 and stack[-1][0] >= arr[i]): 224 | stack.pop() 225 | 226 | if len(stack)==0: 227 | ans1.append(index) 228 | else: 229 | ans1.append(stack[-1][1]) 230 | stack.append([arr[i],i]) 231 | ans1= ans1[::-1] 232 | stack =[] 233 | ans2 = [] 234 | 235 | for i in range (0,n): 236 | if len(stack)==0: 237 | ans2.append(-1) 238 | elif len(stack)>0 and stack[-1][0] < arr[i]: 239 | ans2.append(stack[-1][1]) 240 | elif len(stack)>0 and stack[-1][0] >= arr[i]: 241 | while (len(stack) !=0 and stack[-1][0] >= arr[i]): 242 | stack.pop() 243 | if len(stack)==0: 244 | ans2.append(-1) 245 | else: 246 | ans2.append(stack[-1][1]) 247 | stack.append([arr[i],i]) 248 | 249 | ans = [0] * (n + 1) 250 | for i in range(n + 1): 251 | ans[i] = 0 252 | 253 | for i in range(n): 254 | Len = ans1[i] - ans2[i] - 1 255 | ans[Len] = max(ans[Len], arr[i]) 256 | for i in range(n - 1, 0, -1): 257 | ans[i] = max(ans[i], ans[i + 1]) 258 | ans.pop(0) 259 | return ans 260 | --------------------------------------------------------------------------------