├── C++ ├── 0-1 Knapsack ├── 2ndMaximumAmong3Numbers.c++ ├── AVL Tree Implementation.cpp ├── Binary_search.cpp ├── Binary_search_usingrecursion.cpp ├── Bit_Difference.cpp ├── Bitset.cpp ├── Boruvka's_algorithm.cpp ├── BubbleSort.cpp ├── Calculating Area of 2D shapes.cpp ├── Check Armstrong Number of any number of digit.cpp ├── CheckTwoNodesOnSamePath.cpp ├── Check_if_a_queue_can_be_sorted_into_another_queue_using_a_stack.cpp ├── ChocolateProblem.cpp ├── Cyclically rotate an array by one.cpp ├── DNFsort.cpp ├── DSA Array.cpp ├── DSA_Reversing_string_using stack.cpp ├── Detect Cycle in singly linked list.cpp ├── Dijkstra's single source shortest path algorithm.cpp ├── Diwakar-SegregateEvenOdd.cpp ├── Diwakar-StringReverseUsingStack.cpp ├── Double_Hashing.cpp ├── Euclid_GCD.cpp ├── Find_middle_of_a_linkedlist.cpp ├── Find_whether_an_array_is_subset_of_another_array.cpp ├── First_repeating_ele.cpp ├── GDOG.cpp ├── Insertion_sort.cpp ├── K-cores of a Graph.cpp ├── Kadane's Algorithm.cpp ├── Kosarajus_Algorithm.cpp ├── Krushkals_Algorithm.cpp ├── LCA_of_Binary_Tree.cpp ├── Largest subarray with 0 sum ├── Linear_search(simplified).cpp ├── Linear_search.cpp ├── Linearr_Search.cpp ├── LinkedlistInsertion.cpp ├── LongestPathInMatrix.cpp ├── Longest_common_subsequence.cpp ├── Merge Sorted Array.cpp ├── Merge_Two_Sorted_LinkList.cpp ├── Min_Stack.cpp ├── NQueen_Problem.cpp ├── Number of trees in forest.cpp ├── PairFind.cpp ├── Prime no.cpp ├── Queue_as _stack.cpp ├── Remove_duplicates_from_an_unsorted_linked.cpp ├── ReverseLinkedList.cpp ├── ReverseString...cpp ├── ReverseString.cpp ├── Reverse_A_Linklist.cpp ├── Reverse_LlinkedList.cpp ├── Reverse_String_Using_Stack.cpp ├── ReversingQueue.cpp ├── SecondHighest_ofThree.cpp ├── SecondLargestInBST.cpp ├── Segreate_odd_even.cpp ├── Selection_sort.cpp ├── Sorting.cpp ├── Stack_Using_Queue.cpp ├── StringReverseUsingStack.cpp ├── SudokuSolver.cpp ├── SumOfNodes.cpp ├── Swap_Two_Numbers.cpp ├── Swapping with and without using Third Variable ├── Trapping_rain_water_problem.cpp ├── Tree.cpp ├── Union_Of_Two_Arrays.cpp ├── add_two_numbers_represented_by_linked_lists.cpp ├── array-of-vectors.cpp ├── articulation_points.cpp ├── count_set_bits.cpp ├── countsort.cpp ├── cycle_detection_using_dsu.cpp ├── decode_ways.cpp ├── factorial_using_recursion.cpp ├── floydTriangle.cpp ├── graph_traversals.cpp ├── greedypup.cpp ├── heapsort-Abhivansh Bhatnagar.cpp ├── height_of_binary_tree.cpp ├── implementQueueUsingLinkedList.cpp ├── lis.cpp ├── longest_increasing_subsequence.cpp ├── max_heap.cpp ├── menuarr.cpp ├── merge_binarytree.cpp ├── merge_sort.cpp ├── mother_vertex_in_a_graph.cpp ├── nooftreesinforest.cpp ├── optimal pattern merge.cpp ├── path.cpp ├── prim'sminimumspanningtree.cpp ├── prim_MST.cpp ├── queue_using_two_stacks_Pulakitha.cpp ├── queue_using_two_stacks_Pulakitha.exe ├── quicksort.cpp ├── radixsort.cpp ├── removeBSTkeys.cpp ├── remove_duplicates_from_linked_list.cpp ├── remove_duplicates_unsorted_linked_list.cpp ├── reverseString .cpp ├── reverse_Linked_list.cpp ├── reverse_array.cpp ├── reverse_string.cpp ├── sieve of eratosthenes.cpp ├── sortevenodd.cpp └── swapnumber.cpp ├── C ├── BubbleSort.c ├── Counts_Occurences_In_LikedList.c ├── Cyclically_rotate_an_array_by_one.c ├── Hash Table.c ├── Insertion_Sort.c ├── LinklistDeletion.c ├── MultipleParenthesisMatching.c ├── NumberOfGivenInt.c ├── Queue_using_Array.c ├── QuickSort.c ├── Selection_Sort.c ├── countFrequency.c ├── int-count-llist.c ├── linked-list.c ├── linkedListInsertion.c ├── parenthesisMatching.c └── tree.c ├── Java ├── CheckBST.java ├── EvenAfterOddLL.java ├── ExecuteBinarySearchOnAVector.java ├── Happy Number.java ├── InorderSuccessorInBinaryTree.java ├── LeftViewOfBinaryTree.java ├── Linked List Cycle.java ├── ListNode.java ├── MidElementDeletion.java ├── Palindrome_Number.java ├── Radix.java ├── Remove_element.java ├── ReversePath.java ├── Reverse_queue.java ├── RotateMatrixBy90Degrees.java ├── Selection_sort.java ├── SubtreeDifference.java ├── TernarySearch.java ├── TrappingRainWater.java ├── Valid_parantheses.java ├── anagrams.java ├── bubble_sort.java ├── javaAwt.java ├── kadane_algo.java ├── kth _min_max_element ├── linear_search.java ├── max_sum_of_array.java ├── merge_sort.java ├── minSubtree.java ├── minValueNodeinBST.java ├── tic_tac_toe.java └── word serach.java ├── JavaSript ├── Longest Common Prefix.js ├── Pascal's Triangle.js ├── algorithms_Js │ ├── FizzBuzz │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── fizzbuzz.test.js │ │ └── fizzbuzz.js │ ├── RiverSizes │ │ ├── index.js │ │ └── index.test.js │ ├── caesarCipher │ │ ├── __tests__ │ │ │ └── caesarCipher.test.js │ │ └── caesarCipher.js │ ├── firstBadVersion │ │ ├── README.md │ │ ├── index.js │ │ └── index.test.js │ ├── getEvenOccurrences │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── getevenoccurrence.test.js │ │ └── getevenoccurrence.js │ ├── getMaxStack │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── getMaxStack.test.js │ │ └── getMaxStack.js │ ├── getPermutations │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── getpermutations.test.js │ │ └── getpermutations.js │ ├── isPalindrome │ │ ├── README.md │ │ ├── index.js │ │ └── index.test.js │ ├── itertiveBFS_DFS │ │ ├── index.js │ │ └── index.test.js │ ├── meanMedianMode │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── meanMedianMode.test.js │ │ └── index.js │ ├── moveElementToEnd │ │ ├── index.js │ │ └── index.test.js │ ├── nextUntil │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── nextUntil.test.js │ │ └── nextUntil.js │ ├── permutations │ │ ├── README.md │ │ ├── index.js │ │ └── index.test.js │ ├── power │ │ ├── README.md │ │ ├── power.js │ │ └── power.test.js │ ├── queueStacks │ │ ├── README.md │ │ ├── queueTwoStacks.js │ │ └── queueTwoStacks.test.js │ ├── responseHandler │ │ ├── README.md │ │ ├── responseHandler.js │ │ └── responseHandler.test.js │ ├── reverseArrayInPlace │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── reverseArrayInPlace.test.js │ │ └── index.js │ ├── reverseWords │ │ ├── README.md │ │ ├── __tests__ │ │ │ └── reverseWords.test.js │ │ └── index.js │ ├── romanToNumerals │ │ ├── README.md │ │ ├── translateromannumerals.js │ │ └── translateromannumerals.test.js │ ├── sumDigits │ │ ├── README.md │ │ ├── index.js │ │ └── index.test.js │ ├── twoSum │ │ ├── README.md │ │ ├── index.js │ │ └── twoSum.test.js │ └── wordsDictionary │ │ ├── README.md │ │ ├── index.js │ │ └── index.test.js ├── schemeRandomNota.js └── top three repeated numbers.js ├── LICENSE.md ├── Python ├── Lowest Common Ancestor.py ├── Path.py ├── ReversingQueue.py ├── SecondLargestElementBST.py ├── Segregate_even_odd.py ├── Sorting │ ├── bogo_sort.py │ ├── bubble_sort.py │ ├── bucket_sort.py │ ├── heap_sort.py │ ├── merge_sort.py │ ├── pegionhole_sort.py │ ├── quick_sort.py │ └── selection_sort.py ├── SortingQueueWithExtraSpace.py ├── TernarySearch.py ├── averageOddAndEven.py ├── check_if_each_internal_node_of_BST_has_exactly_one_child.py ├── count_tree.py ├── majorityElement.py ├── minimum_value_node_in_bst.py ├── printAllPathsFromSourceToDestinationInGraph.py ├── segregate_even_and_odd.py ├── stockSpan.py └── symmetric_tree.py ├── README.md ├── images └── logo-hacktoberfest-full.f42e3b1.jpg └── topological_sorting.cpp /C++/0-1 Knapsack: -------------------------------------------------------------------------------- 1 | //0-1 Knapsack problem with recursion and memiozation 2 | 3 | #include 4 | using namespace std; 5 | 6 | int dp[101][1001]; 7 | memset(dp,-1,sizeof(dp)); 8 | 9 | int knapSack(int W, int wt[], int val[], int n) 10 | { 11 | if (n==0 || W==0) return 0; 12 | 13 | // memoization 14 | if (dp[n][w]!=-1) return dp[n][w]; 15 | 16 | // if weight of the item in array is less than the max weight then we have 2 choice either include it or exclude it 17 | 18 | if (wt[n-1]<=W) { 19 | return dp[n][w] =max(val[n-1] + knapSack(W-wt[n-1],wt,val,n-1), knapSack(W,wt,val,n-1)); 20 | } 21 | 22 | // if weight of item is more than max weight then we have to exclude it 23 | 24 | else if (wt[n-1] >W) { 25 | return dp[n][w] = knapSack(W,wt,val,n-1); 26 | } 27 | } 28 | 29 | int main() { 30 | n = 3 31 | W = 4 32 | val[] = {1,2,3} 33 | wt[] = {4,5,1} 34 | cout<< knapSack(W, wt, val, n)< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void solve(){ 8 | // Storing Numbers in Array 9 | int a[3], minimum = INT_MAX, maximum = INT_MIN, result; 10 | 11 | // Taking Input 12 | cin>>a[0]>>a[1]>>a[2]; 13 | 14 | // Sorting Array 15 | sort(a, a+3); 16 | 17 | cout<>t; 24 | while(t--){ 25 | solve(); 26 | } 27 | } 28 | 29 | // Code Submitted by Rohan Das - https://github.com/rohan26062001 -------------------------------------------------------------------------------- /C++/Binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool binSearch(vector& arr, int x){ 5 | int n=arr.size(); 6 | int start=0, end=n-1, mid; 7 | while(start<=end){ 8 | mid=(start+end)>>1; 9 | if(arr[mid]==x) 10 | return true; 11 | else if(arr[mid]>x) 12 | end=mid-1; 13 | else start=mid+1; 14 | } 15 | return false; 16 | } 17 | int main() 18 | { 19 | 20 | vector arr={12,14, 17, 9, 78, 6}; 21 | int n=arr.size(); 22 | cout<<"Original Array is:"< search={9, 70, 12}; 28 | for(int i=0; i 2 | using namespace std; 3 | 4 | int binary_search(int A[], int beg, int end, int ele) 5 | { 6 | if (end >= beg) 7 | { 8 | int mid = (beg + end - 1) / 2; 9 | 10 | if (A[mid] == ele) 11 | return mid; 12 | else if (A[mid] > ele) 13 | return binary_search(A, beg, mid, ele); 14 | else 15 | return binary_search(A, mid + 1, end, ele); 16 | } 17 | return -1; 18 | } 19 | int main() 20 | { 21 | int n, ele, index; 22 | cin >> n; 23 | int *A = new int[n]; 24 | for (int i = 0; i < n; i++) 25 | { 26 | cin >> A[i]; 27 | } 28 | cin>>ele; 29 | index = binary_search(A, 0, n-1, ele); 30 | if(index!=-1) 31 | cout<<"Element found at index "< 2 | using namespace std; 3 | 4 | class Solution{ 5 | public: 6 | long long set(int pattern, long long int arr[], int n) 7 | { 8 | /// pairm; 9 | // m.first=0; 10 | // m.second=0; 11 | long long count=0; 12 | for(int i=0;i=0;bit--) 31 | { 32 | res=set(1<>t; 47 | while(t--){ 48 | int N; 49 | cin>>N; 50 | long long int A[N]; 51 | for(int i = 0;i < N; i++) 52 | cin>>A[i]; 53 | 54 | Solution ob; 55 | cout< 2 | using namespace std; 3 | 4 | void swap(int *ab, int *cd) 5 | { 6 | int temp = *ab; 7 | *ab = *cd; 8 | *cd = temp; 9 | } 10 | 11 | // A function to implement bubble sort 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | for (i = 0; i < n-1; i++) 16 | 17 | // Last i elements are already in place 18 | for (j = 0; j < n-i-1; j++) 19 | if (arr[j] > arr[j+1]) 20 | swap(&arr[j], &arr[j+1]); 21 | } 22 | 23 | void printArray(int arr[], int size) 24 | { 25 | int i; 26 | for (i = 0; i < size; i++) 27 | cout << arr[i] << " "; 28 | cout << endl; 29 | } 30 | 31 | int main() 32 | { 33 | int arr[] = {44, 34, 47,1, 89, 32, 90}; 34 | int n = sizeof(arr)/sizeof(arr[0]); 35 | bubbleSort(arr, n); 36 | cout<<"Sorted array: \n"; 37 | printArray(arr, n); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /C++/Calculating Area of 2D shapes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | using namespace std; 7 | 8 | 9 | int main() 10 | 11 | { 12 | 13 | int n; 14 | 15 | float a,b,c,s,lt,bt,side,r,area; 16 | 17 | cout<<"Press 1 for Area of Square\n"; 18 | 19 | cout<<"Press 2 for Area of Rectangle\n"; 20 | 21 | cout<<"Press 3 for Area of Triangle\n"; 22 | 23 | cout<<"Press 4 for Area of Circle\n\n"; 24 | 25 | cin>>n; 26 | 27 | 28 | 29 | switch(n) 30 | 31 | { 32 | 33 | case 1: 34 | 35 | cout<<"Enter the side of square\n"; 36 | 37 | cin>>side; 38 | 39 | area=side*side; 40 | 41 | cout<<"Area="<>lt>>bt; 52 | 53 | area=lt*bt; 54 | 55 | cout<<"Area="<>a>>b>>c; 66 | 67 | s=(a+b+c)/2; 68 | 69 | area=sqrt(s*(s-a)*(s-b)*(s-c)); 70 | 71 | cout<<"Area="<>r; 82 | 83 | area=3.14*r*r; 84 | 85 | cout<<"Area="< 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | 9 | { 10 | 11 | int n,num,rem,i=0; 12 | 13 | float result=0; 14 | 15 | cout<<"Enter the number:"<>n; 18 | 19 | num=n; 20 | 21 | for(num=n;num!=0;++i) //store the number of digits of n in num 22 | 23 | { 24 | 25 | num/=10; 26 | 27 | } 28 | 29 | for(num=n;num!=0;num/=10) 30 | 31 | { 32 | 33 | rem=num%10; 34 | 35 | result+=pow(rem,i); //store the sum of power of each digits in result 36 | 37 | } 38 | 39 | if((int)result==n) 40 | 41 | cout<<"Yes, it is an Armstrong Number"; 42 | 43 | else 44 | 45 | cout<<"No, it is not an Armstrong Number"; 46 | 47 | return 0; 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /C++/CheckTwoNodesOnSamePath.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check if given pairs lie on same path or not. 2 | 3 | #include 4 | using namespace std; 5 | const int MAX = 100001; 6 | 7 | // To keep track of visited vertices in DFS 8 | bool visit[MAX] = {0}; 9 | 10 | // To store start and end time of all vertices 11 | // during DFS. 12 | int intime[MAX]; 13 | int outtime[MAX]; 14 | 15 | // initially timer is zero 16 | int timer = 0; 17 | 18 | // Does DFS of given graph and fills arrays 19 | // intime[] and outtime[]. These arrays are used 20 | // to answer given queries. 21 | void dfs(vector graph[], int v) 22 | { 23 | visit[v] = true; 24 | 25 | // Increment the timer as you enter 26 | // the recursion for v 27 | ++timer; 28 | 29 | // Upgrade the in time for the vertex 30 | intime[v] = timer; 31 | 32 | vector::iterator it = graph[v].begin(); 33 | while (it != graph[v].end()) 34 | { 35 | if (visit[*it]==false) 36 | dfs(graph, *it); 37 | it++; 38 | } 39 | 40 | // increment the timer as you exit the 41 | // recursion for v 42 | ++timer; 43 | 44 | // upgrade the outtime for that node 45 | outtime[v] = timer; 46 | } 47 | 48 | // Returns true if 'u' and 'v' lie on same root to leaf path 49 | // else false. 50 | bool query(int u, int v) 51 | { 52 | return ( (intime[u]outtime[v]) || 53 | (intime[v]outtime[u]) ); 54 | } 55 | 56 | // Driver code 57 | int main() 58 | { 59 | // Let us create above shown tree 60 | int n = 9; // total number of nodes 61 | vector graph[n+1]; 62 | graph[1].push_back(2); 63 | graph[1].push_back(3); 64 | graph[3].push_back(6); 65 | graph[2].push_back(4); 66 | graph[2].push_back(5); 67 | graph[5].push_back(7); 68 | graph[5].push_back(8); 69 | graph[5].push_back(9); 70 | 71 | // Start dfs (here root node is 1) 72 | dfs(graph, 1); 73 | 74 | // below are calls for few pairs of nodes 75 | query(1, 5)? cout << "Yes\n" : cout << "No\n"; 76 | query(2, 9)? cout << "Yes\n" : cout << "No\n"; 77 | query(2, 6)? cout << "Yes\n" : cout << "No\n"; 78 | 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /C++/Check_if_a_queue_can_be_sorted_into_another_queue_using_a_stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool checkSorted(int n, queue& q) 5 | { 6 | stack stk; 7 | int expected = 1; 8 | int fnt; 9 | 10 | while (!q.empty()) { 11 | fnt = q.front(); 12 | q.pop(); 13 | 14 | if (fnt == expected) 15 | expected++; 16 | 17 | else { 18 | 19 | if (stk.empty()) { 20 | stk.push(fnt); 21 | } 22 | 23 | 24 | else if (!stk.empty() && stk.top() < fnt) { 25 | return false; 26 | } 27 | 28 | 29 | else 30 | stk.push(fnt); 31 | } 32 | 33 | 34 | while (!stk.empty() && stk.top() == expected) { 35 | stk.pop(); 36 | expected++; 37 | } 38 | } 39 | 40 | if (expected - 1 == n && stk.empty()) 41 | return true; 42 | 43 | return false; 44 | } 45 | 46 | int main() 47 | { 48 | queue q; 49 | q.push(5); 50 | q.push(1); 51 | q.push(2); 52 | q.push(3); 53 | q.push(4); 54 | 55 | int n = q.size(); 56 | 57 | (checkSorted(n, q) ? (cout << "Yes") : 58 | (cout << "No")); 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /C++/ChocolateProblem.cpp: -------------------------------------------------------------------------------- 1 | /* ------------------------------------------------------------------------------------------------------------------- 2 | Chocolate problem given money , price of each chocolate and number of warpper in exchange with we can get new chocolate4 3 | example = 4 | input : 5 | money = 15; 6 | price (of each chocolate) = 1; (Rs) 7 | wrap = 3; 8 | (means instead of 3 wrapper we will get 1 more chocolate) 9 | 10 | output: 11 | 22 12 | -------------------------------------------------------------------------------------------------------------------*/ 13 | #include 14 | using namespace std; 15 | 16 | 17 | int countNewChoco(int choco,int wrap) 18 | { 19 | if(choco < wrap) 20 | { 21 | return 0; 22 | } 23 | int newChoco = choco / wrap; 24 | return newChoco + countNewChoco(newChoco + choco%wrap , wrap); 25 | } 26 | 27 | 28 | int countMaxChoco(int money,int price,int wrap) 29 | { 30 | int choco = money / price; 31 | return choco + countNewChoco(choco,wrap); 32 | } 33 | int main() 34 | { 35 | int money = 15; 36 | int price = 1; 37 | int wrap = 3; 38 | 39 | cout<<"Maximum chocolate is : "< 16 | using namespace std; 17 | 18 | int main() { 19 | int n; 20 | cin>>n; 21 | for(int i=0;i>s; 25 | int a[s]; 26 | for(int j=0;j>a[j]; 28 | cout< 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int q; 7 | cin>>q; 8 | 9 | 10 | while(q--){ 11 | int c=0; 12 | int m,n; 13 | cin>>m>>n; 14 | for(int i=m;i<=n;i++) 15 | { 16 | if(ceil(sqrt(i))==floor(sqrt(i))) 17 | c++; 18 | } 19 | 20 | cout< 2 | 3 | using namespace std; 4 | 5 | string reverse(string s) 6 | { 7 | string ans = ""; 8 | stack st; 9 | int n = s.length(); // length of string 10 | for (int i = 0 ; i < n ; i++) // push into the stack upto last character 11 | st.push(s[i]); 12 | while (!st.empty()) // run till stack is not empty 13 | { 14 | ans += st.top(); 15 | st.pop(); 16 | } 17 | return ans; 18 | } 19 | 20 | int main() 21 | { 22 | string s; 23 | cout << "Enter the string-"; 24 | cin >> s; 25 | s = reverse(s); 26 | cout << s; //output the string 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /C++/Diwakar-SegregateEvenOdd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | 6 | std::vector even; 7 | std::vector odd; 8 | 9 | int count=0; 10 | std::cout<<"How many numbers you want to enter? \n"; 11 | std::cin>>count; 12 | std::cout<<"Enter above number of numbers and press enter\n"; 13 | int temp=0; 14 | while(count>0){ 15 | std::cin>>temp; 16 | if(temp%2==0){ 17 | even.push_back(temp); 18 | } 19 | if(temp%2!=0){ 20 | odd.push_back(temp); 21 | } 22 | count--; 23 | } 24 | 25 | //prints even values 26 | std::cout<<"The Segregated Even Odd Numbers are:\n"; 27 | for(auto i:even){ 28 | std::cout< 2 | #include 3 | 4 | //my stack implementation 5 | class Stack{ 6 | private: 7 | std::vector stack; 8 | public: 9 | //constructor 10 | Stack(std::string input){ 11 | for(auto i:input){ 12 | push(i); 13 | } 14 | } 15 | 16 | //push elements into stack i.e vector list named stack 17 | void push(char c){ 18 | stack.push_back(c); 19 | } 20 | 21 | //pop elements out of stack and this method returns the popped element 22 | char pop(){ 23 | char temp=stack[stack.size()-1]; 24 | stack.pop_back(); 25 | return temp; 26 | } 27 | 28 | //helper method to know size of the stack 29 | int size(){ 30 | return stack.size(); 31 | } 32 | 33 | //Returns reversed String 34 | std::string reverseStack(){ 35 | std::string reverseStr; 36 | 37 | int count = size(); 38 | 39 | for(int i=0;i>input; 51 | 52 | //creates a new stack 53 | Stack stack {input}; 54 | std::cout<<"Reversed String is: "; 55 | //calling stack reverse method which returns a string of reversed input 56 | std::cout<<(stack.reverseStack()); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /C++/Euclid_GCD.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int gcd(int a, int b) 5 | { 6 | if (b == 0) 7 | { 8 | return a; 9 | } 10 | return gcd(b, a % b); 11 | } 12 | 13 | int main() 14 | { 15 | int a, b; 16 | cout << "Enter first number: "; 17 | cin >> a; 18 | cout << "Enter second number: "; 19 | cin >> b; 20 | 21 | int c = gcd(a, b); 22 | cout << "The greatest common divisor of " << a << " and " << b << " is " << c; 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /C++/Find_middle_of_a_linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class node{ 4 | public: 5 | int data; 6 | node *next;//yaha address store karvana tha toh aysy likha 7 | node(int data){ 8 | this->data=data; 9 | next=NULL; 10 | } 11 | }; 12 | node *middlenode(node *head){ 13 | node *slow=head; 14 | node *fast=head->next; 15 | while(fast && fast->next){ 16 | slow=slow->next; 17 | fast=fast->next->next; 18 | } 19 | if(fast!=NULL){ 20 | return slow->next; 21 | } 22 | return slow; 23 | } 24 | 25 | int main(){ 26 | node n1(81); 27 | node n2(27); 28 | node n3(56); 29 | node *head=&n1;// this head is storing the address of first link list component so that we can access the whole link list through this 30 | n1.next=&n2; 31 | n2.next=&n3;// this is storing address jaha pehle null stored tha 32 | 33 | cout<<"the middle element is "<data; 34 | 35 | 36 | return 0; 37 | 38 | 39 | } 40 | 41 | 42 | //The running time of finding the middle element this way with two pointers is O(n) because once we pass through the entire linked list of n elements, the slower pointer is at the middle node already. 43 | -------------------------------------------------------------------------------- /C++/Find_whether_an_array_is_subset_of_another_array.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find whether an array 2 | // is subset of another array 3 | #include 4 | 5 | /* Return 1 if arr2[] is a subset of 6 | arr1[] */ 7 | bool isSubset(int arr1[], int arr2[], 8 | int m, int n) 9 | { 10 | int i = 0; 11 | int j = 0; 12 | for (i = 0; i < n; i++) { 13 | for (j = 0; j < m; j++) { 14 | if (arr2[i] == arr1[j]) 15 | break; 16 | } 17 | 18 | /* If the above inner loop was 19 | not broken at all then arr2[i] 20 | is not present in arr1[] */ 21 | if (j == m) 22 | return 0; 23 | } 24 | 25 | /* If we reach here then all 26 | elements of arr2[] are present 27 | in arr1[] */ 28 | return 1; 29 | } 30 | 31 | // Driver code 32 | int main() 33 | { 34 | int arr1[] = { 11, 1, 13, 21, 3, 7 }; 35 | int arr2[] = { 11, 3, 7, 1 }; 36 | 37 | int m = sizeof(arr1) / sizeof(arr1[0]); 38 | int n = sizeof(arr2) / sizeof(arr2[0]); 39 | 40 | if (isSubset(arr1, arr2, m, n)) 41 | printf("arr2[] is subset of arr1[] "); 42 | else 43 | printf("arr2[] is not a subset of arr1[]"); 44 | 45 | getchar(); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/First_repeating_ele.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin>>n; 9 | int a[n]; 10 | 11 | for(int i=0;i>a[i]; 14 | } 15 | 16 | const int N=1e6+2; 17 | int k[N]; 18 | 19 | for(int i=0;i 2 | using namespace std; 3 | int main() { 4 | int t,n,k,instance_max,max=0; 5 | cin>>t; 6 | while(t--){ 7 | cin>>n>>k; 8 | max=0; 9 | for(int i=1;i<=k;i++){ 10 | instance_max = n%i; 11 | if(instance_max > max){ 12 | max = instance_max; 13 | } 14 | } 15 | cout< 2 | using namespace std; 3 | 4 | void insertionSort(vector& arr, int n ){ 5 | for(int i=1; i=0 and temp arr={12,14, 17, 9, 78, 6}; 19 | int n=arr.size(); 20 | cout<<"Array before insertion sort is:"< 5 | #include 6 | using namespace std; 7 | 8 | int maxSubArraySum(int a[], int size) 9 | { 10 | int max_so_far = INT_MIN, max_ending_here = 0; 11 | 12 | for (int i = 0; i < size; i++) 13 | { 14 | max_ending_here = max_ending_here + a[i]; 15 | if (max_so_far < max_ending_here) 16 | max_so_far = max_ending_here; 17 | 18 | if (max_ending_here < 0) 19 | max_ending_here = 0; 20 | } 21 | return max_so_far; 22 | } 23 | 24 | int main() 25 | { 26 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 27 | int n = sizeof(a)/sizeof(a[0]); 28 | int max_sum = maxSubArraySum(a, n); 29 | cout << "Maximum contiguous sum is " << max_sum; 30 | return 0; 31 | } -------------------------------------------------------------------------------- /C++/Krushkals_Algorithm.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: 3 | ----------------- 4 | Find a minimum spanning tree of given undirected edge-weighted graph. 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | #define INF 9999999 11 | #define V 5 12 | 13 | int graph[V][V] = {{0, 2, 0, 6, 0}, 14 | {2, 0, 3, 8, 5}, 15 | {0, 3, 0, 0, 7}, 16 | {6, 8, 0, 0, 9}, 17 | {0, 5, 7, 9, 0}}; 18 | 19 | void KrushkalsAlgorithm(vector &distance, vector &parent, int source) 20 | { 21 | int edges = 0; 22 | distance[source] = 0; 23 | 24 | while (edges < V - 1) 25 | { 26 | for (int i = 1; i < V; i++) 27 | for (int j = 1; j <= V; j++) 28 | if (graph[i][j] != 0 and (graph[i][j] < distance[j])) 29 | { 30 | distance[j] = graph[i][j]; 31 | parent[j] = j; 32 | } 33 | edges++; 34 | } 35 | 36 | for (int i = 1; i <= V; i++) 37 | cout << "\nDistance of " << source << " to " << i << " is : " << distance[i]; 38 | 39 | for (int i = 0; i < V; i++) 40 | cout << "Parent of " << i << " is : " << parent[i] << " and Distance : " << distance[i] << endl; 41 | } 42 | 43 | int main() 44 | { 45 | vector distance(V, INF); 46 | vector parent(V, -1); 47 | //vector visited(V, 0); 48 | 49 | KrushkalsAlgorithm(distance, parent, 0); 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C++/LCA_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | // Lowest Common Ancestor of a Binary Tree 2 | 3 | 4 | //Approach 5 | // At first we traverse the tree and match nodes n1 and n2 if we get one of the 6 | // nodes in the left subtree and another one in the right subtree,then the root is the LCA. 7 | 8 | 9 | //Header files 10 | #include 11 | using namespace std; 12 | //Code for Tree node 13 | struct Node{ 14 | int data; 15 | Node* left; 16 | Node* right; 17 | }; 18 | //Code for creating a new node. 19 | Node* create(int x){ 20 | Node* temp=new Node; 21 | temp->data=x; 22 | temp->left=NULL; 23 | temp->right=NULL; 24 | return temp; 25 | } 26 | //function to find lowest common ancestor. 27 | Node *LCA(Node* root ,int n1 ,int n2 ) 28 | { 29 | if(root==NULL) 30 | return NULL; 31 | if(root->data==n1||root->data==n2) 32 | return root; 33 | 34 | Node* left=LCA(root->left,n1,n2); 35 | Node* right=LCA(root->right,n1,n2); 36 | 37 | if(!left&&!right) 38 | return NULL; 39 | if(left&&right) 40 | return root; 41 | if(!left&&right) 42 | return right; 43 | if(!right&&left) 44 | return left; 45 | 46 | } 47 | 48 | //Main fuction. 49 | int main(){ 50 | Node* root=create(11); 51 | root->left=create(20); 52 | root->left->right=create(31); 53 | root->left->right->left=create(49); 54 | root->left->right->right=create(54); 55 | root->right=create(56); 56 | root->right->left=create(60); 57 | root->right->left->right=create(73); 58 | root->right->right=create(76); 59 | Node* temp=LCA(root,73,76); 60 | if(temp) 61 | cout<<"LCA of node 73 and 76 is: "<data< 2 | using namespace std; 3 | 4 | int maxLen(int arr[], int n) 5 | { 6 | mapm1; 7 | int i,sum=0,ans=0; 8 | 9 | for(i=0;i 2 | #include 3 | 4 | int main(){ 5 | 6 | char list[5][10] = {"Apple","Brisket","Quanta","Toronto","Zirconium"}; 7 | char word[] = "Brisket"; 8 | int found = 0; 9 | 10 | for(int i=0;i<5;i++){ 11 | if(strcmp(list[i],word)==0){ 12 | printf("%s present at %d",word,i+1); 13 | found = 1; 14 | break; 15 | } 16 | } 17 | if(found == 0){ 18 | printf("Element not found"); 19 | } 20 | } -------------------------------------------------------------------------------- /C++/Linear_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool linSearch(vector& arr, int x){ 5 | int n=arr.size(); 6 | for(int i=0; i arr={12,14, 17, 9, 78, 6}; 16 | int n=arr.size(); 17 | cout<<"Original Array is:"< search={9, 70, 12}; 24 | for(int i=0; i 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n; 7 | cout<<"Enter the length of the Array : "; 8 | cin>>n; 9 | cout<>search; 25 | cout< 3 | #define n 3 4 | using namespace std; 5 | 6 | int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n]) 7 | { 8 | if (i < 0 || i >= n || j < 0 || j >= n) 9 | return 0; 10 | 11 | if (dp[i][j] != -1) 12 | return dp[i][j]; 13 | 14 | int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN; 15 | 16 | if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1])) 17 | x = 1 + findLongestFromACell(i, j + 1, mat, dp); 18 | 19 | if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1])) 20 | y = 1 + findLongestFromACell(i, j - 1, mat, dp); 21 | 22 | if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j])) 23 | z = 1 + findLongestFromACell(i - 1, j, mat, dp); 24 | 25 | if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j])) 26 | w = 1 + findLongestFromACell(i + 1, j, mat, dp); 27 | 28 | return dp[i][j] = max(x, max(y, max(z, max(w, 1)))); 29 | } 30 | 31 | int finLongestOverAll(int mat[n][n]) 32 | { 33 | int result = 1; 34 | 35 | int dp[n][n]; 36 | memset(dp, -1, sizeof dp); 37 | 38 | for (int i = 0; i < n; i++) { 39 | for (int j = 0; j < n; j++) { 40 | if (dp[i][j] == -1) 41 | findLongestFromACell(i, j, mat, dp); 42 | 43 | result = max(result, dp[i][j]); 44 | } 45 | } 46 | 47 | return result; 48 | } 49 | 50 | int main() 51 | { 52 | int mat[n][n] = { { 1, 2, 9 }, 53 | { 5, 3, 8 }, 54 | { 4, 6, 7 } }; 55 | cout << "Length of the longest path is " 56 | << finLongestOverAll(mat); 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /C++/Longest_common_subsequence.cpp: -------------------------------------------------------------------------------- 1 | // This code prints the longest common subsequence between two strings using dp 2 | #include 3 | using namespace std; 4 | 5 | string printlongestsequence(string a, string b) 6 | { 7 | int n=a.length(), m=b.length(); 8 | int dp[n+1][m+1]; 9 | 10 | // initialising dp matrix 11 | for(int i=0;i<=n;i++) 12 | { 13 | for(int j=0;j<=m;j++) 14 | { 15 | if(i==0 || j==0) 16 | { 17 | dp[i][j]=0; 18 | } 19 | } 20 | } 21 | 22 | //filling dp matrix 23 | for(int i=1;i<=n;i++) 24 | { 25 | for(int j=1;j<=m;j++) 26 | { 27 | if(a[i-1]==b[j-1]) 28 | dp[i][j]= 1+ dp[i-1][j-1]; 29 | else 30 | dp[i][j]= max(dp[i-1][j], dp[i][j-1]); 31 | } 32 | } 33 | 34 | string ans=""; 35 | int i=n,j=m; 36 | 37 | //finding longest subsequence 38 | while(i>0 && j>0) 39 | { 40 | if(a[i-1]==b[j-1]) 41 | { 42 | ans.push_back(a[i-1]); 43 | i--, j--; 44 | } 45 | else{ 46 | if(dp[i-1][j] > dp[i][j-1]) 47 | i--; 48 | else 49 | j--; 50 | } 51 | } 52 | 53 | reverse(ans.begin(), ans.end()); 54 | return ans; 55 | 56 | 57 | } 58 | 59 | int main() 60 | { 61 | string a="abcdgh"; 62 | string b="abldho"; 63 | 64 | cout<< printlongestsequence(a,b); 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /C++/Merge_Two_Sorted_LinkList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class node{ 4 | public: 5 | int data; 6 | node* next; 7 | node(int val){ //constructor 8 | data=val; 9 | next=NULL; 10 | } 11 | }; 12 | 13 | void insertAtTail(node* &head,int val) 14 | { 15 | node* n=new node(val); 16 | 17 | if (head==NULL) 18 | { 19 | head=n; 20 | return; 21 | } 22 | 23 | node* temp=head; 24 | while (temp->next!=NULL) 25 | { 26 | temp=temp->next; 27 | } 28 | 29 | temp->next=n; 30 | } 31 | 32 | 33 | node* recursive(node* &head1, node* &head2) 34 | { 35 | if (head1==NULL) 36 | { 37 | return head2; 38 | } 39 | 40 | if (head2==NULL) 41 | { 42 | return head1; 43 | } 44 | 45 | node* result; 46 | 47 | if (head1->datadata) 48 | { 49 | result=head1; 50 | result->next=recursive(head1->next,head2); 51 | } 52 | else{ 53 | result=head2; 54 | result->next=recursive(head1,head2->next); 55 | } 56 | return result; 57 | } 58 | 59 | 60 | void display(node* head) 61 | { 62 | node* temp=head; 63 | while (temp!=NULL) 64 | { 65 | cout<data<<" -> "; 66 | temp=temp->next; 67 | } 68 | cout<<"NULL"< 2 | using namespace std; 3 | 4 | stacks; 5 | stackt; 6 | 7 | void push(int val) { 8 | s.push(val); 9 | if(t.empty()) 10 | t.push(val); 11 | else{ 12 | if(val>n; 40 | 41 | for(int i=0;i>num; 44 | push(num); 45 | } 46 | 47 | cout<<"The current minimum is : "< 4 | using namespace std; 5 | 6 | // A utility function to add an edge in an 7 | // undirected graph. 8 | void addEdge(vector adj[], int u, int v) 9 | { 10 | adj[u].push_back(v); 11 | adj[v].push_back(u); 12 | } 13 | 14 | // A utility function to do DFS of graph 15 | // recursively from a given vertex u. 16 | void DFSUtil(int u, vector adj[], 17 | vector &visited) 18 | { 19 | visited[u] = true; 20 | for (int i=0; i adj[], int V) 28 | { 29 | vector visited(V, false); 30 | int res = 0; 31 | for (int u=0; u adj[V]; 47 | addEdge(adj, 0, 1); 48 | addEdge(adj, 0, 2); 49 | addEdge(adj, 3, 4); 50 | cout << countTrees(adj, V); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C++/Prime no.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | int n; 5 | cout<<"Enter no: "; 6 | cin>>n; 7 | bool f=false; 8 | for(int i=2;i 4 | using namespace std; 5 | 6 | // Function to check if given queue element 7 | // can be sorted into another queue using a 8 | // stack. 9 | bool checkSorted(int n, queue& q) 10 | { 11 | stack st; 12 | int expected = 1; 13 | int fnt; 14 | 15 | // while given Queue is not empty. 16 | while (!q.empty()) { 17 | fnt = q.front(); 18 | q.pop(); 19 | 20 | // if front element is the expected element 21 | if (fnt == expected) 22 | expected++; 23 | 24 | else { 25 | // if stack is empty, push the element 26 | if (st.empty()) { 27 | st.push(fnt); 28 | } 29 | 30 | // if top element is less than element which 31 | // need to be pushed, then return false. 32 | else if (!st.empty() && st.top() < fnt) { 33 | return false; 34 | } 35 | 36 | // else push into the stack. 37 | else 38 | st.push(fnt); 39 | } 40 | 41 | // while expected element are coming from 42 | // stack, pop them out. 43 | while (!st.empty() && st.top() == expected) { 44 | st.pop(); 45 | expected++; 46 | } 47 | } 48 | 49 | // if the final expected element value is equal 50 | // to initial Queue size and the stack is empty. 51 | if (expected - 1 == n && st.empty()) 52 | return true; 53 | 54 | return false; 55 | } 56 | 57 | // Driven Program 58 | int main() 59 | { 60 | queue q; 61 | int n; 62 | 63 | cout<<"Enter no of elements:"<>n; 65 | cout<<"Enter elements:"<>t; 70 | q.push(t); 71 | } 72 | 73 | (checkSorted(n, q) ? (cout << "Yes") : 74 | (cout << "No")); 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /C++/Remove_duplicates_from_an_unsorted_linked.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int data; 8 | Node *next; 9 | Node(int x) 10 | { 11 | data = x; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | Node *removeDuplicates(Node *head) 17 | { 18 | if (head == NULL) 19 | { 20 | return head; 21 | } 22 | unordered_map isPres; 23 | Node *prev = head; 24 | Node *curr = head; 25 | curr = curr->next; 26 | isPres[head->data] = 1; 27 | 28 | while (curr != NULL) 29 | { 30 | if (!isPres[curr->data]) 31 | { 32 | prev->next = curr; 33 | prev = curr; 34 | isPres[curr->data] = 1; 35 | } 36 | curr = curr->next; 37 | } 38 | 39 | prev->next = NULL; 40 | return head; 41 | } 42 | -------------------------------------------------------------------------------- /C++/ReverseString...cpp: -------------------------------------------------------------------------------- 1 | // C++ program to reverse Vector 2 | // using reverse() in STL 3 | 4 | #include 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | string str ; 10 | cin>>str; 11 | cout << "Before Reverse : "<< str << endl; 12 | reverse(str.begin(), str.end()); 13 | cout <<"After Reverse : " << str << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /C++/ReverseString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void reverse(string &str){ 6 | stack s; 7 | 8 | for (char ch: str) { 9 | s.push(ch); 10 | } 11 | 12 | for (int i = 0; i < str.length(); i++) 13 | { 14 | str[i] = s.top(); 15 | s.pop(); 16 | } 17 | } 18 | 19 | int main(){ 20 | string str; 21 | cin >> str; 22 | 23 | reverse(str); 24 | cout << str; 25 | 26 | return 0; 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /C++/Reverse_A_Linklist.cpp: -------------------------------------------------------------------------------- 1 | // Iterative C++ program to reverse 2 | // a linked list 3 | #include 4 | using namespace std; 5 | 6 | /* Link list node */ 7 | struct Node { 8 | int data; 9 | struct Node* next; 10 | Node(int data) 11 | { 12 | this->data = data; 13 | next = NULL; 14 | } 15 | }; 16 | 17 | struct LinkedList { 18 | Node* head; 19 | LinkedList() { head = NULL; } 20 | 21 | /* Function to reverse the linked list */ 22 | void reverse() 23 | { 24 | // Initialize current, previous and 25 | // next pointers 26 | Node* current = head; 27 | Node *prev = NULL, *next = NULL; 28 | 29 | while (current != NULL) { 30 | // Store next 31 | next = current->next; 32 | 33 | // Reverse current node's pointer 34 | current->next = prev; 35 | 36 | // Move pointers one position ahead. 37 | prev = current; 38 | current = next; 39 | } 40 | head = prev; 41 | } 42 | 43 | /* Function to print linked list */ 44 | void print() 45 | { 46 | struct Node* temp = head; 47 | while (temp != NULL) { 48 | cout << temp->data << " "; 49 | temp = temp->next; 50 | } 51 | } 52 | 53 | void push(int data) 54 | { 55 | Node* temp = new Node(data); 56 | temp->next = head; 57 | head = temp; 58 | } 59 | }; 60 | 61 | /* Driver code*/ 62 | int main() 63 | { 64 | /* Start with the empty list */ 65 | LinkedList ll; 66 | ll.push(20); 67 | ll.push(4); 68 | ll.push(15); 69 | ll.push(85); 70 | 71 | cout << "Given linked list\n"; 72 | ll.print(); 73 | 74 | ll.reverse(); 75 | 76 | cout << "\nReversed Linked list \n"; 77 | ll.print(); 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /C++/Reverse_LlinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node{ 5 | 6 | int data; 7 | struct Node *next; 8 | 9 | Node(int data){ 10 | this->data = data; 11 | next = NULL; 12 | } 13 | }*head=NULL; 14 | 15 | Node *reverseList(Node* head){ 16 | 17 | struct Node *cur = head; 18 | struct Node *nex; 19 | struct Node *prev=NULL; 20 | 21 | while(cur!=NULL){ 22 | 23 | nex=cur->next; 24 | cur->next=prev; 25 | prev=cur; 26 | cur=nex; 27 | } 28 | 29 | return prev; 30 | } 31 | 32 | void printList(struct Node* head){ 33 | 34 | struct Node *p = head; 35 | 36 | while(p!=NULL){ 37 | cout<data<<" "; 38 | p=p->next; 39 | } 40 | } 41 | 42 | 43 | int main(){ 44 | 45 | Node* head = new Node(1); 46 | head->next = new Node(2); 47 | head->next->next = new Node(3); 48 | head->next->next->next = new Node(4); 49 | head->next->next->next->next = new Node(5); 50 | head->next->next->next->next->next = new Node(6); 51 | head->next->next->next->next->next->next = new Node(7); 52 | head->next->next->next->next->next->next->next = new Node(8); 53 | 54 | cout<<"LinkedList = " ; 55 | printList(head); 56 | 57 | cout<<"Reverse List = "; 58 | head = reverseList(head); 59 | printList(head); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /C++/Reverse_String_Using_Stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | string reverse(string str){ 5 | stack stack; //Using stack from STL Libraries 6 | for(int i=0;i 2 | using namespace std; 3 | 4 | void Print(queue& Queue) 5 | { 6 | while (!Queue.empty()) { 7 | cout << Queue.front() << " "; 8 | Queue.pop(); 9 | } 10 | } 11 | 12 | void reverseQueue(queue& Queue) 13 | { 14 | stack Stack; 15 | while (!Queue.empty()) { 16 | Stack.push(Queue.front()); 17 | Queue.pop(); 18 | } 19 | while (!Stack.empty()) { 20 | Queue.push(Stack.top()); 21 | Stack.pop(); 22 | } 23 | } 24 | 25 | int main() 26 | { 27 | queue Queue; 28 | Queue.push(10); 29 | Queue.push(20); 30 | Queue.push(30); 31 | Queue.push(40); 32 | Queue.push(50); 33 | Queue.push(60); 34 | Queue.push(70); 35 | Queue.push(80); 36 | Queue.push(90); 37 | Queue.push(100); 38 | 39 | reverseQueue(Queue); 40 | Print(Queue); 41 | } -------------------------------------------------------------------------------- /C++/SecondHighest_ofThree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int t; 8 | cin>>t; 9 | while(t--) 10 | { 11 | int a,b,c; 12 | cin>>a>>b>>c; 13 | if((a>=b && b>=c) || (c>=b && b>=a)) 14 | { 15 | cout<=c && c>=b) || (b>=c && c>=a)) 18 | { 19 | cout<=a && a>=b) || (b>=a && a>=c)) 22 | { 23 | cout< 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int key; 7 | Node *left, *right; 8 | }; 9 | 10 | Node *newNode(int item) 11 | { 12 | Node *temp = new Node; 13 | temp->key = item; 14 | temp->left = temp->right = NULL; 15 | return temp; 16 | } 17 | 18 | void secondLargestUtil(Node *root, int &c) 19 | { 20 | if (root == NULL || c >= 2) 21 | return; 22 | 23 | secondLargestUtil(root->right, c); 24 | 25 | c++; 26 | 27 | if (c == 2) 28 | { 29 | cout << "2nd largest element is " 30 | << root->key << endl; 31 | return; 32 | } 33 | 34 | secondLargestUtil(root->left, c); 35 | } 36 | 37 | void secondLargest(Node *root) 38 | { 39 | int c = 0; 40 | 41 | secondLargestUtil(root, c); 42 | } 43 | 44 | Node* insert(Node* node, int key) 45 | { 46 | if (node == NULL) return newNode(key); 47 | 48 | if (key < node->key) 49 | node->left = insert(node->left, key); 50 | else if (key > node->key) 51 | node->right = insert(node->right, key); 52 | 53 | return node; 54 | } 55 | 56 | int main() 57 | { 58 | Node *root = NULL; 59 | int n; 60 | cin >> n; 61 | vector v(n); 62 | int x; 63 | for(int i=0;i>x; 65 | v[i] = x; 66 | } 67 | 68 | root = insert(root, v[0]); 69 | for(int i=1;i 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | int n,x; 7 | cin>>n; 8 | vector odd,even; 9 | for(int i=0;i>x; 11 | if(x&1) 12 | odd.push_back(x); 13 | else 14 | even.push_back(x); 15 | } 16 | cout<<"Odd numbers are\n"; 17 | for(int i=0;i 2 | using namespace std; 3 | 4 | void selectionSort(vector& arr, int n ){ 5 | for(int i=0; i arr={12,14, 17, 9, 78, 6}; 22 | int n=arr.size(); 23 | cout<<"Array before insertion sort is:"< 2 | #include 3 | using namespace std; 4 | int main() { 5 | int n,t; 6 | cin >> t; 7 | while(t--){ 8 | cin>>n; 9 | int gl[n],b[n]; 10 | for(int i = 0;i>gl[i];} 12 | for(int i=0;i>b[i]; 14 | } 15 | sort(gl,gl+n); 16 | sort(b,b+n); 17 | int j=n-1,c=0; 18 | for(int i=0;i 2 | using namespace std; 3 | 4 | class stacck 5 | { 6 | int N; 7 | queue q1; 8 | queue q2; 9 | 10 | public: 11 | stacck() 12 | { 13 | N=0; 14 | } 15 | 16 | void push(int val) 17 | { 18 | q2.push(val); 19 | N++; 20 | while (!q1.empty()) 21 | { 22 | q2.push(q1.front()); 23 | q1.pop(); 24 | } 25 | swap(q1,q2); 26 | 27 | } 28 | 29 | void pop() 30 | { 31 | q1.pop(); 32 | N--; 33 | } 34 | 35 | int top() 36 | { 37 | return q1.front(); 38 | } 39 | 40 | int size() 41 | { 42 | return N; 43 | } 44 | }; 45 | 46 | -------------------------------------------------------------------------------- /C++/StringReverseUsingStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Reverse a string using a stack container in C++. 7 | void reverse(string &str) 8 | { 9 | // create an empty stack 10 | stack s; 11 | 12 | // Push each character in the string to the stack 13 | for (char ch: str) { 14 | s.push(ch); 15 | } 16 | 17 | // pop all characters from the stack and append them back to the input string 18 | for (int i = 0; i < str.length(); i++) 19 | { 20 | str[i] = s.top(); 21 | s.pop(); 22 | } 23 | } 24 | 25 | int main() 26 | { 27 | string str = "HacktoberFest 2021"; 28 | 29 | reverse(str); 30 | cout << str; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /C++/SumOfNodes.cpp: -------------------------------------------------------------------------------- 1 | int getSum(BinaryTreeNode* root) { 2 | if(root==NULL){ 3 | return 0; 4 | } 5 | int sum=root->data; 6 | queue*> pending; 7 | pending.push(root); 8 | while(pending.size()!=0){ 9 | BinaryTreeNode* front=pending.front(); 10 | pending.pop(); 11 | if(front->left!=NULL){ 12 | sum=sum+front->left->data; 13 | pending.push(front->left); 14 | } 15 | if(front->right!=NULL){ 16 | sum=sum+front->right->data; 17 | pending.push(front->right); 18 | } 19 | } 20 | return sum; 21 | // Write your code here 22 | } 23 | -------------------------------------------------------------------------------- /C++/Swap_Two_Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int a = 5, b = 10; 8 | 9 | cout << "Before swapping." << endl; 10 | cout << "a = " << a << ", b = " << b << endl; 11 | 12 | a = a + b; 13 | b = a - b; 14 | a = a - b; 15 | 16 | cout << "\nAfter swapping." << endl; 17 | cout << "a = " << a << ", b = " << b << endl; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /C++/Swapping with and without using Third Variable: -------------------------------------------------------------------------------- 1 | //Swapping without using Third Variable 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() 10 | 11 | { 12 | int a,b; 13 | cout<<"Enter the values of a and b:\n"; 14 | cin>>a>>b; 15 | 16 | cout<<"The values of a and b before swapping were:\n"<<"a="<>a>>b; 42 | 43 | cout<<"The values of a and b before swapping were:\n"<<"a="< height; 46 | int n; 47 | cin >> n; 48 | for (int i = 0; i < n; i++) 49 | { 50 | int a; 51 | cin >> a; 52 | height.push_back(a); 53 | } 54 | 55 | int ans = trap(height); 56 | cout << ans; 57 | return 0; 58 | 59 | } -------------------------------------------------------------------------------- /C++/Tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | void insert(vector vec[], int parent, int child){ 5 | vec[parent].push_back(child); 6 | vec[child].push_back(parent); 7 | } 8 | void recurred(int temp, vector vec[], vector &check){ 9 | check[temp] = true; 10 | int size = vec[temp].size(); 11 | for(int i = 0; i < size; i++){ 12 | if (check[vec[temp][i]] == false){ 13 | recurred(vec[temp][i], vec, check); 14 | } 15 | } 16 | } 17 | int Trees_Forest(vector vec[], int vertice){ 18 | int count = 0; 19 | vector check(vertice, false); 20 | for(int i = 0; i < vertice; i++){ 21 | if(check[i] == false){ 22 | recurred(i, vec, check); 23 | count++; 24 | } 25 | } 26 | return count; 27 | } 28 | int main(){ 29 | int vertice = 9; 30 | vector vec[vertice]; 31 | insert(vec, 1, 3); 32 | insert(vec, 2, 8); 33 | insert(vec, 2, 6); 34 | insert(vec, 3, 5); 35 | insert(vec, 3, 7); 36 | insert(vec, 4, 8); 37 | cout<<"Total number of trees in the forest: "< 3 | using namespace std; 4 | 5 | class Solution{ 6 | public: 7 | //Function to return the count of number of elements in union of two arrays. 8 | int doUnion(int a[], int n, int b[], int m) { 9 | int big = n < m ? m : n; 10 | set s; 11 | for(int i = 0;i> t; 27 | 28 | while(t--){ 29 | 30 | int n, m; 31 | cin >> n >> m; 32 | int a[n], b[m]; 33 | 34 | for(int i = 0;i> a[i]; 36 | 37 | for(int i = 0;i> b[i]; 39 | Solution ob; 40 | cout << ob.doUnion(a, n, b, m) << endl; 41 | 42 | } 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /C++/array-of-vectors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | void printv(vector&v){ 6 | 7 | for (int i = 0; i < v.size(); i++){ 8 | 9 | cout<>n; 19 | 20 | vectorv[n];//*n vectors declared 21 | for (int i = 0; i < n; i++){ 22 | int x; 23 | cin>>x; 24 | for (int j = 0; j < x; j++){ 25 | 26 | int y; 27 | cin>> y; 28 | v[i].push_back(y); 29 | } 30 | 31 | } 32 | for (int i = 0; i 2 | using namespace std; 3 | 4 | void dfs(int node, int parent, vector& vis, vector& tin, 5 | vector& low, int& timer, vector adj[], vector& isArticulation) { 6 | 7 | vis[node] = 1; 8 | tin[node] = low[node] = timer++; 9 | int child = 0; 10 | for (auto it : adj[node]) { 11 | if (it == parent) continue; 12 | if (!vis[it]) { 13 | dfs(it, node, vis, tin, low, timer, adj, isArticulation); 14 | low[node] = min(low[node], low[it]); 15 | if (low[it] >= tin[node] && parent != -1) { 16 | isArticulation[node] = 1; 17 | } 18 | child++; 19 | } 20 | else { 21 | low[node] = min(low[node], tin[it]); 22 | } 23 | } 24 | if (parent == -1 && child > 1) { 25 | isArticulation[node] = 1; 26 | } 27 | } 28 | 29 | int main() { 30 | int n, m; 31 | cin >> n >> m; 32 | vector adj[n]; 33 | 34 | for (int i = 0; i < m; i++) { 35 | int u, v; 36 | cin >> u >> v; 37 | adj[u].push_back(v); 38 | adj[v].push_back(u); 39 | } 40 | 41 | vector tin(n, -1); 42 | vector low(n, -1); 43 | vector vis(n, 0); 44 | vector isArticulation(n, 0); 45 | int timer = 0; 46 | for (int i = 0; i < n; i++) { 47 | if (!vis[i]) { 48 | dfs(i, -1, vis, tin, low, timer, adj, isArticulation); 49 | } 50 | } 51 | for (int i = 0; i < n; i++) { 52 | if (isArticulation[i]) { 53 | cout << i << " is a articulation point\n"; 54 | } 55 | } 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /C++/count_set_bits.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Count set bits in an integer 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | unsigned int countSetBits(unsigned int n) 9 | { 10 | unsigned int count = 0; 11 | while (n) { 12 | count += n & 1; 13 | n >>= 1; 14 | } 15 | return count; 16 | } 17 | 18 | 19 | int main() 20 | { 21 | int i = 9; 22 | cout << countSetBits(i); 23 | return 0; 24 | } 25 | 26 | // This code is contributed 27 | // by Nikhil Kumar 28 | -------------------------------------------------------------------------------- /C++/countsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | template 6 | void Print(T& vec, int n, string s){ 7 | cout << s << ": [" << flush; 8 | for (int i=0; i max){ 21 | max = A[i]; 22 | } 23 | } 24 | return max; 25 | } 26 | 27 | void CountSort(int A[], int n){ 28 | int max = Max(A, n); 29 | 30 | // Create count array 31 | int* count = new int [max + 1]; 32 | 33 | // Initialize count array with 0 34 | for (int i=0; i 0){ 48 | A[i++] = j; 49 | count[j]--; 50 | } else { 51 | j++; 52 | } 53 | } 54 | 55 | // Delete heap memory 56 | delete [] count; 57 | } 58 | 59 | int main() { 60 | 61 | int A[] = {2, 5, 8, 12, 3, 6, 7, 10}; 62 | int n = sizeof(A)/sizeof(A[0]); 63 | 64 | Print(A, n, "\t\tA"); 65 | CountSort(A, n); 66 | Print(A, n, " Sorted A"); 67 | 68 | return 0; 69 | } -------------------------------------------------------------------------------- /C++/cycle_detection_using_dsu.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 1e5 + 6; 5 | 6 | vector parent(N); 7 | vector sz(N); 8 | void make_set(int v){ 9 | parent[v] = v; 10 | sz[v] =1; 11 | } 12 | 13 | int find_set(int v){ 14 | if (parent[v]==v) return v; 15 | return parent[v] = find_set(parent[v]); 16 | } 17 | 18 | void union_sets(int a,int b){ 19 | a = find_set(a); 20 | b = find_set(b); 21 | if (a!=b){ 22 | if (sz[a]>sz[b]){ 23 | parent[b] = a; 24 | sz[a] += sz[b]; 25 | } 26 | else{ 27 | parent[a] = b; 28 | sz[b] += sz[a]; 29 | } 30 | } 31 | } 32 | 33 | int main(){ 34 | for (int i=0;i>n>>m; 38 | vector> edges; 39 | for (int i=0;i>u>>v; 41 | edges.push_back({u,v}); 42 | } 43 | bool cycle = 0; 44 | for (auto ele : edges){ 45 | int u = ele[0]; 46 | int v = ele[1]; 47 | int x = find_set(u); 48 | int y = find_set(v); 49 | if (x==y){ 50 | cycle = 1; 51 | } 52 | else{ 53 | union_sets(u,v); 54 | } 55 | } 56 | if (cylcle){ 57 | cout << "Cycle Present\n"; 58 | } 59 | else{ 60 | cout << "Cycle Not Present\n; 61 | } 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /C++/decode_ways.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | int numDecodings(string s) { 7 | int n = s.length(); 8 | vectordp(n + 1, 0); 9 | 10 | dp[0] = 1; 11 | dp[1] = s[0] == '0' ? 0 : 1; 12 | 13 | for (int i = 2; i <= n; i++) 14 | { 15 | dp[i] = 0; 16 | if (s[i - 1] != '0') 17 | dp[i] = dp[i - 1]; 18 | 19 | if (s[i - 2] == '1' || s[i - 2] == '2' && s[i - 1] <= '6') 20 | dp[i] += dp[i - 2]; 21 | } 22 | 23 | return dp[n]; 24 | 25 | } 26 | 27 | int main() 28 | { 29 | #ifndef ONLINE_JUDGE 30 | freopen("input1.txt", "r", stdin); 31 | freopen("output1.txt", "w", stdout); 32 | 33 | #endif 34 | 35 | string s; 36 | cin >> s; 37 | int ans = numDecodings(s); 38 | cout << ans; 39 | return 0; 40 | 41 | } -------------------------------------------------------------------------------- /C++/factorial_using_recursion.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find factorial of given number 2 | #include 3 | using namespace std; 4 | 5 | // function to find factorial of given number 6 | unsigned int factorial(unsigned int n) 7 | { 8 | if (n == 0) 9 | return 1; 10 | return n * factorial(n - 1); 11 | } 12 | 13 | // Driver code 14 | int main() 15 | { 16 | int num = 5; 17 | cout << "Factorial of " 18 | << num << " is " << factorial(num) << endl; 19 | return 0; 20 | } -------------------------------------------------------------------------------- /C++/floydTriangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int rows; 6 | cout<<"enter the number of rows:\n"; 7 | cin>>rows; 8 | int num = 1; 9 | 10 | for (int i = 1; i <= rows; i++) 11 | { 12 | for (int j = 1; j <= i; j++) 13 | { 14 | cout< 2 | using namespace std; 3 | 4 | int main() { 5 | int t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | int n,k; 10 | cin>>n>>k; 11 | int m=0; 12 | for(int i=1; i<=k; i++) 13 | { 14 | int div; 15 | div=n/i; 16 | if(m < (n-(div*i))) 17 | { 18 | m = n-(div*i); 19 | } 20 | 21 | 22 | } 23 | cout << m << endl;// your code goes here 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /C++/heapsort-Abhivansh Bhatnagar.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of Heap Sort 2 | #include 3 | 4 | using namespace std; 5 | 6 | // To heapify a subtree rooted with node i which is 7 | // an index in arr[]. n is size of heap 8 | void heapify(int arr[], int n, int i) 9 | { 10 | int largest = i; // Initialize largest as root 11 | int l = 2 * i + 1; // left = 2*i + 1 12 | int r = 2 * i + 2; // right = 2*i + 2 13 | 14 | // If left child is larger than root 15 | if (l < n && arr[l] > arr[largest]) 16 | largest = l; 17 | 18 | // If right child is larger than largest so far 19 | if (r < n && arr[r] > arr[largest]) 20 | largest = r; 21 | 22 | // If largest is not root 23 | if (largest != i) { 24 | swap(arr[i], arr[largest]); 25 | 26 | // Recursively heapify the affected sub-tree 27 | heapify(arr, n, largest); 28 | } 29 | } 30 | 31 | // main function to do heap sort 32 | void heapSort(int arr[], int n) 33 | { 34 | // Build heap (rearrange array) 35 | for (int i = n / 2 - 1; i >= 0; i--) 36 | heapify(arr, n, i); 37 | 38 | // One by one extract an element from heap 39 | for (int i = n - 1; i > 0; i--) { 40 | // Move current root to end 41 | swap(arr[0], arr[i]); 42 | 43 | // call max heapify on the reduced heap 44 | heapify(arr, i, 0); 45 | } 46 | } 47 | 48 | /* A utility function to print array of size n */ 49 | void printArray(int arr[], int n) 50 | { 51 | for (int i = 0; i < n; ++i) 52 | cout << arr[i] << " "; 53 | cout << "\n"; 54 | } 55 | 56 | // Driver code 57 | int main() 58 | { 59 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 60 | int n = sizeof(arr) / sizeof(arr[0]); 61 | 62 | heapSort(arr, n); 63 | 64 | cout << "Sorted array is \n"; 65 | printArray(arr, n); 66 | } 67 | -------------------------------------------------------------------------------- /C++/height_of_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find height of tree 2 | #include 3 | using namespace std; 4 | 5 | class node 6 | { 7 | public: 8 | int data; 9 | node* left; 10 | node* right; 11 | }; 12 | 13 | 14 | int maxDepth(node* node) 15 | { 16 | if (node == NULL) 17 | return 0; 18 | else 19 | { 20 | int lDepth = maxDepth(node->left); 21 | int rDepth = maxDepth(node->right); 22 | return max(lDepth,rDepth)+1; 23 | } 24 | } 25 | 26 | node* newNode(int data) 27 | { 28 | node* Node = new node(); 29 | Node->data = data; 30 | Node->left = NULL; 31 | Node->right = NULL; 32 | 33 | return(Node); 34 | } 35 | 36 | 37 | int main() 38 | { 39 | node *root = newNode(1); 40 | 41 | root->left = newNode(2); 42 | root->right = newNode(3); 43 | root->left->left = newNode(4); 44 | root->left->right = newNode(5); 45 | 46 | cout << "Height of tree is " << maxDepth(root); 47 | return 0; 48 | } -------------------------------------------------------------------------------- /C++/implementQueueUsingLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node *next; 8 | 9 | Node(int data) { 10 | this->data = data; 11 | next = NULL; 12 | } 13 | }; 14 | 15 | class Queue { 16 | 17 | Node* head; 18 | Node* tail; 19 | int size; 20 | public: 21 | Queue() { 22 | head = NULL; 23 | tail = NULL; 24 | size = 0; 25 | } 26 | 27 | 28 | int getSize() { 29 | return size; 30 | } 31 | 32 | bool isEmpty() { 33 | return size==0; 34 | } 35 | 36 | void enqueue(int data) { 37 | Node* newnode = new Node(data); 38 | if(isEmpty()){ 39 | head = newnode; 40 | tail = newnode; 41 | size++; 42 | return; 43 | } 44 | tail->next = newnode; 45 | tail = newnode; 46 | size++; 47 | } 48 | 49 | int dequeue() { 50 | if(isEmpty()){ 51 | return -1; 52 | } 53 | Node* temp = head; 54 | int ans = head->data; 55 | delete head; 56 | head = temp->next; 57 | size--; 58 | return ans; 59 | } 60 | 61 | int front() { 62 | if(isEmpty()){ 63 | return -1; 64 | } 65 | return head->data; 66 | } 67 | }; 68 | int main() { 69 | Queue q; 70 | 71 | int t; 72 | cin >> t; 73 | 74 | while (t--) { 75 | int choice, input; 76 | cin >> choice; 77 | switch (choice) { 78 | case 1: 79 | cin >> input; 80 | q.enqueue(input); 81 | break; 82 | case 2: 83 | cout << q.dequeue() << "\n"; 84 | break; 85 | case 3: 86 | cout << q.front() << "\n"; 87 | break; 88 | case 4: 89 | cout << q.getSize() << "\n"; 90 | break; 91 | default: 92 | cout << ((q.isEmpty()) ? "true\n" : "false\n"); 93 | break; 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /C++/lis.cpp: -------------------------------------------------------------------------------- 1 | //Time Complexity - O(n^2); 2 | //space Complecxity - O(n); 3 | #include 4 | using namespace std; 5 | 6 | int lengthOfLIS(vector& nums) { 7 | int ans = 0; 8 | int n = nums.size(); 9 | int dp[n]; 10 | for(int i=0;i> n; 28 | vectornums(n); 29 | for(int i=0;i> nums[i]; 31 | } 32 | 33 | int ans = lengthOfLIS(nums); 34 | cout << ans << endl; 35 | } -------------------------------------------------------------------------------- /C++/longest_increasing_subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | 6 | int search(vector&dp, int s, int e, int k) 7 | { 8 | while (s < e) 9 | { 10 | int m = (s + e) / 2; 11 | 12 | if (dp[m] < k) 13 | s = m + 1; 14 | else 15 | e = m; 16 | } 17 | return s; 18 | } 19 | int lengthOfLIS(vector& nums) { 20 | int n = nums.size(); 21 | int ans = 1; 22 | vectordp(n, 0); 23 | 24 | dp[0] = nums[0]; 25 | 26 | for (int i = 0; i < n; i++) 27 | { 28 | int ind = search(dp, 0, ans, nums[i]); 29 | dp[ind] = nums[i]; 30 | 31 | if (ind == ans)ans++; 32 | } 33 | 34 | return ans; 35 | 36 | } 37 | 38 | int main() 39 | { 40 | #ifndef ONLINE_JUDGE 41 | freopen("input1.txt", "r", stdin); 42 | freopen("output1.txt", "w", stdout); 43 | 44 | #endif 45 | 46 | int n; 47 | cin >> n; 48 | vector nums(n); 49 | for (int i = 0; i < n; i++) 50 | cin >> nums[i]; 51 | int ans = lengthOfLIS(nums); 52 | cout << ans; 53 | return 0; 54 | 55 | } -------------------------------------------------------------------------------- /C++/max_heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void max_heap(int *a, int m, int n) { 4 | int j, t; 5 | t = a[m]; 6 | j = 2 * m; 7 | while (j <= n) { 8 | if (j < n && a[j+1] > a[j]) 9 | j = j + 1; 10 | if (t > a[j]) 11 | break; 12 | else if (t <= a[j]) { 13 | a[j / 2] = a[j]; 14 | j = 2 * j; 15 | } 16 | } 17 | a[j/2] = t; 18 | return; 19 | } 20 | void build_maxheap(int *a,int n) { 21 | int k; 22 | for(k = n/2; k >= 1; k--) { 23 | max_heap(a,k,n); 24 | } 25 | } 26 | int main() { 27 | int n, i; 28 | cout<<"enter no of elements of array\n"; 29 | cin>>n; 30 | int a[30]; 31 | for (i = 1; i <= n; i++) { 32 | cout<<"enter elements"<<" "<<(i)<>a[i]; 34 | } 35 | build_maxheap(a,n); 36 | cout<<"Max Heap\n"; 37 | for (i = 1; i <= n; i++) { 38 | cout< 2 | using namespace std; 3 | // Menu driven program for creating, inserting, searching and deleting elements in an array 4 | void disp(int arr[], int n) 5 | { 6 | for(int i=0;i=pos;i--) 14 | arr[i+1]=arr[i]; 15 | arr[pos]=ele; 16 | n+=1; 17 | } 18 | void del(int arr[],int &n, int pos, int ele) 19 | { 20 | for(int i=pos;i>n; 42 | int arr[n]; 43 | for(int i=0;i>arr[i]; 46 | } 47 | do{ 48 | cout<<"Menu\n1.Create\n2.Display\n3.Insert\n4.Delete\n5.Search\n6.Exit\n"; 49 | cin>>ch; 50 | switch(ch) 51 | { 52 | case 2: 53 | disp(arr,n); 54 | break; 55 | case 3: 56 | cout<<"Enter position & element"; 57 | cin>>pos>>ele; 58 | insert(arr,n,pos,ele); 59 | break; 60 | case 4: 61 | cout<<"Enter element to be deleted"; 62 | cin>>d; 63 | pos=search(arr,n,d); 64 | if(pos==-1) 65 | cout<<"Element not found"; 66 | else 67 | del(arr,n,pos,d); 68 | break; 69 | case 5:"Enter element to search"; 70 | cin>>s; 71 | pos=search(arr,n,s); 72 | cout<<"Element found at"<>end; 78 | }while(end==1); 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /C++/merge_binarytree.cpp: -------------------------------------------------------------------------------- 1 | //merge two binary trees 2 | class Solution { 3 | public: 4 | TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { 5 | if ( (t1!=nullptr)&&(t2!=nullptr)) 6 | { 7 | TreeNode * root = new TreeNode(t1->val + t2->val); 8 | root->left = mergeTrees(t1->left, t2->left); 9 | root->right = mergeTrees(t1->right, t2->right); 10 | return root; 11 | } 12 | else { 13 | return t1 ? t1 : t2; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /C++/merge_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void merge(int *arr, int l, int mid, int r) 4 | { 5 | int n1 = mid - l + 1, n2 = r - mid; 6 | int a[n1], b[n2]; 7 | for (int i = 0; i < n1; i++) 8 | { 9 | a[i] = arr[l + i]; 10 | } 11 | for (int i = 0; i < n2; i++) 12 | { 13 | b[i] = arr[mid + 1 + i]; 14 | } 15 | int i = 0, j = 0, k = l; 16 | while (i < n1 && j < n2) 17 | { 18 | if (a[i] < b[j]) 19 | { 20 | arr[k] = a[i]; 21 | k++, i++; 22 | } 23 | else 24 | { 25 | arr[k] = b[j]; 26 | k++, j++; 27 | } 28 | } 29 | while (i < n1) 30 | { 31 | arr[k] = a[i]; 32 | k++, i++; 33 | } 34 | while (j < n2) 35 | { 36 | arr[k] = b[j]; 37 | k++, j++; 38 | } 39 | } 40 | void mergesort(int *arr, int l, int r) 41 | { 42 | if (l >= r) 43 | return; 44 | int mid = (l + r) / 2; 45 | mergesort(arr, l, mid); 46 | mergesort(arr, mid + 1, r); 47 | merge(arr, l, mid, r); 48 | } 49 | 50 | int main() 51 | { 52 | int n; 53 | cin >> n; 54 | int arr[n]; 55 | for (int i = 0; i < n; i++) 56 | cin >> arr[i]; 57 | mergesort(arr, 0, n - 1); 58 | for (int i = 0; i < n; i++) 59 | cout << arr[i] << " "; 60 | } 61 | //Time complexity: T(n)=T(n/2)+n total=nlogn -------------------------------------------------------------------------------- /C++/nooftreesinforest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A utility function to add an edge in an 5 | // undirected graph. 6 | void addEdge(vector adj[], int u, int v) 7 | { 8 | adj[u].push_back(v); 9 | adj[v].push_back(u); 10 | } 11 | 12 | // A utility function to do DFS of graph 13 | // recursively from a given vertex u. 14 | void DFSUtil(int u, vector adj[], 15 | vector &visited) 16 | { 17 | visited[u] = true; 18 | for (int i=0; i adj[], int V) 26 | { 27 | vector visited(V, false); 28 | int res = 0; 29 | for (int u=0; u adj[V]; 45 | addEdge(adj, 0, 1); 46 | addEdge(adj, 0, 2); 47 | addEdge(adj, 3, 4); 48 | cout << countTrees(adj, V); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /C++/optimal pattern merge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int minComputation(int size, int files[]) 6 | { 7 | 8 | 9 | priority_queue, greater > pq; 10 | 11 | for (int i = 0; i < size; i++) { 12 | 13 | 14 | pq.push(files[i]); 15 | } 16 | 17 | 18 | int count = 0; 19 | 20 | while (pq.size() > 1) { 21 | 22 | 23 | int first_smallest = pq.top(); 24 | pq.pop(); 25 | int second_smallest = pq.top(); 26 | pq.pop(); 27 | 28 | int temp = first_smallest + second_smallest; 29 | 30 | 31 | count += temp; 32 | 33 | 34 | pq.push(temp); 35 | } 36 | return count; 37 | } 38 | 39 | 40 | int main() 41 | { 42 | 43 | 44 | int n = 6; 45 | 46 | 47 | int files[] = { 2, 3, 4, 5, 6, 7 }; 48 | 49 | 50 | cout << "Minimum Computations = " 51 | << minComputation(n, files); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /C++/path.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check if two nodes lies on same path or not 2 | 3 | #include 4 | using namespace std; 5 | 6 | int filter(int x, int y, int z) 7 | { 8 | if (x != -1 && y != -1) 9 | { 10 | return z; 11 | } 12 | return x == -1 ? y : x; 13 | } 14 | 15 | int samePathUtil(int mtrx[][7], int vrtx, 16 | int v1, int v2, int i) 17 | { 18 | int ans = -1; 19 | 20 | if (i == v1 || i == v2) 21 | return i; 22 | 23 | for (int j = 0; j < vrtx; j++) 24 | { 25 | 26 | if (mtrx[i][j] == 1) 27 | { 28 | ans = filter(ans, samePathUtil(mtrx, vrtx, v1, v2, j), i); 29 | } 30 | } 31 | 32 | return ans; 33 | } 34 | 35 | bool isVertexAtSamePath(int mtrx[][7], 36 | int vrtx, int v1, 37 | int v2, int i) 38 | { 39 | int lca = samePathUtil(mtrx, 40 | vrtx, v1 - 1, 41 | v2 - 1, i); 42 | 43 | if (lca == v1 - 1 || lca == v2 - 1) 44 | return true; 45 | 46 | return false; 47 | } 48 | 49 | int main() 50 | { 51 | int vrtx = 7, edge = 6; 52 | int mtrx[7][7] = { 53 | {0, 1, 1, 1, 0, 0, 0}, 54 | {0, 0, 0, 0, 1, 0, 0}, 55 | {0, 0, 0, 0, 0, 1, 0}, 56 | {0, 0, 0, 0, 0, 0, 1}, 57 | {0, 0, 0, 0, 0, 0, 0}, 58 | {0, 0, 0, 0, 0, 0, 0}, 59 | {0, 0, 0, 0, 0, 0, 0} 60 | 61 | }; 62 | 63 | int v1 = 1, v2 = 5; 64 | 65 | if (isVertexAtSamePath(mtrx, 66 | vrtx, v1, 67 | v2, 0)) 68 | cout << "Yes"; 69 | 70 | else 71 | cout << "No"; 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /C++/queue_using_two_stacks_Pulakitha.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Queue { 4 | stack stack1, stack2; 5 | void push(int a) 6 | { 7 | 8 | while (!stack1.empty()) { 9 | int top_element = stack1.top(); 10 | stack1.pop(); 11 | stack2.push(top_element); 12 | } 13 | 14 | 15 | stack1.push(a); 16 | 17 | 18 | while (!stack2.empty()) { 19 | int top_element = stack2.top(); 20 | stack2.pop(); 21 | stack1.push(top_element); 22 | } 23 | } 24 | 25 | int pop() 26 | { 27 | if (stack1.empty()) { 28 | cout << "Queue is Empty"; 29 | exit(0); 30 | } 31 | int a = stack1.top(); 32 | stack1.pop(); 33 | return a; 34 | } 35 | }; 36 | 37 | int main() 38 | { 39 | Queue queue; 40 | queue.push(1); 41 | queue.push(2); 42 | cout << queue.pop() << endl; 43 | queue.push(3); 44 | queue.push(5); 45 | cout << queue.pop() << endl; 46 | cout << queue.pop() << endl; 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /C++/queue_using_two_stacks_Pulakitha.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shubham56-droid/DataStruture-and-algroithms-program/eb2040408564179c1d73918cde1b52eaace48b31/C++/queue_using_two_stacks_Pulakitha.exe -------------------------------------------------------------------------------- /C++/quicksort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define ll long long 5 | const ll e = 1000000007; // 10^9+7 6 | 7 | int partition(int *a, int s, int e) 8 | { 9 | int i = s - 1; 10 | int j = s; 11 | int pivot = a[e]; 12 | for (j = s; j < e; j++) 13 | { 14 | if (a[j] <= pivot) 15 | { 16 | i += 1; 17 | swap(a[i], a[j]); 18 | } 19 | } 20 | swap(a[e], a[i + 1]); 21 | return i + 1; 22 | } 23 | 24 | void quicksort(int *a, int s, int e) 25 | { 26 | if (s >= e) 27 | return; 28 | int p = partition(a, s, e); 29 | quicksort(a, s, p - 1); 30 | quicksort(a, p + 1, e); 31 | } 32 | 33 | int main() 34 | { 35 | puts("Enter the number of elements of the list"); 36 | int n; 37 | cin >> n; 38 | int a[n]; 39 | puts("Input the elements of the list"); 40 | for (int i = 0; i < n; ++i) 41 | cin >> a[i]; 42 | quicksort(a, 0, n - 1); 43 | puts("The sorted list is : "); 44 | for (int i = 0; i < n; i++) 45 | cout << a[i] << " "; 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/radixsort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Radix Sort 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to get maximum value in arr[] 6 | int getMax(int arr[], int n) 7 | { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | // A function to do counting sort of arr[] according to 16 | // the digit represented by exp. 17 | void countSort(int arr[], int n, int exp) 18 | { 19 | int output[n]; // output array 20 | int i, count[10] = { 0 }; 21 | 22 | // Store count of occurrences in count[] 23 | for (i = 0; i < n; i++) 24 | count[(arr[i] / exp) % 10]++; 25 | 26 | // Change count[i] so that count[i] now contains actual 27 | // position of this digit in output[] 28 | for (i = 1; i < 10; i++) 29 | count[i] += count[i - 1]; 30 | 31 | // Build the output array 32 | for (i = n - 1; i >= 0; i--) { 33 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 34 | count[(arr[i] / exp) % 10]--; 35 | } 36 | 37 | // Copy the output array to arr[], so that arr[] now 38 | // contains sorted numbers according to current digit 39 | for (i = 0; i < n; i++) 40 | arr[i] = output[i]; 41 | } 42 | 43 | // The main function to that sorts arr[] of size n using 44 | // Radix Sort 45 | void radixsort(int arr[], int n) 46 | { 47 | // Find the maximum number to know number of digits 48 | int m = getMax(arr, n); 49 | 50 | // Do counting sort for every digit. Note that instead 51 | // of passing digit number, exp is passed. exp is 10^i 52 | // where i is current digit number 53 | for (int exp = 1; m / exp > 0; exp *= 10) 54 | countSort(arr, n, exp); 55 | } 56 | 57 | // A utility function to print an array 58 | void print(int arr[], int n) 59 | { 60 | for (int i = 0; i < n; i++) 61 | cout << arr[i] << " "; 62 | } 63 | 64 | // Driver Code 65 | int main() 66 | { 67 | int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; 68 | int n = sizeof(arr) / sizeof(arr[0]); 69 | 70 | // Function Call 71 | radixsort(arr, n); 72 | print(arr, n); 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /C++/remove_duplicates_from_linked_list.cpp: -------------------------------------------------------------------------------- 1 | /* C++ Program to remove duplicates in an unsorted 2 | linked list */ 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | struct Node { 9 | int data; 10 | struct Node* next; 11 | }; 12 | 13 | 14 | struct Node* newNode(int data) 15 | { 16 | Node* temp = new Node; 17 | temp->data = data; 18 | temp->next = NULL; 19 | return temp; 20 | } 21 | 22 | /* Function to remove duplicates from a 23 | unsorted linked list */ 24 | void removeDuplicates(struct Node* start) 25 | { 26 | struct Node *ptr1, *ptr2, *dup; 27 | ptr1 = start; 28 | 29 | 30 | while (ptr1 != NULL && ptr1->next != NULL) { 31 | ptr2 = ptr1; 32 | 33 | 34 | while (ptr2->next != NULL) { 35 | /* If duplicate then delete it */ 36 | if (ptr1->data == ptr2->next->data) { 37 | 38 | ptr2->next = ptr2->next->next; 39 | delete (dup); 40 | } 41 | else 42 | ptr2 = ptr2->next; 43 | } 44 | ptr1 = ptr1->next; 45 | } 46 | } 47 | 48 | /* Function to print nodes in a given linked list */ 49 | void printList(struct Node* node) 50 | { 51 | while (node != NULL) { 52 | printf("%d ", node->data); 53 | node = node->next; 54 | } 55 | } 56 | 57 | /* Driver program to test above function */ 58 | int main() 59 | { 60 | 61 | struct Node* start = newNode(14); 62 | start->next = newNode(12); 63 | start->next->next = newNode(10); 64 | start->next->next->next = newNode(11); 65 | start->next->next->next->next = newNode(12); 66 | start->next->next->next->next->next = newNode(11); 67 | start->next->next->next->next->next->next = newNode(10); 68 | 69 | printf("Linked list before removing duplicates "); 70 | printList(start); 71 | 72 | removeDuplicates(start); 73 | 74 | printf("\nLinked list after removing duplicates "); 75 | printList(start); 76 | 77 | return 0; 78 | 79 | } 80 | -------------------------------------------------------------------------------- /C++/remove_duplicates_unsorted_linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* A linked list node */ 5 | struct Node { 6 | int data; 7 | struct Node* next; 8 | }; 9 | 10 | struct Node* newNode(int data) 11 | { 12 | Node* temp = new Node; 13 | temp->data = data; 14 | temp->next = NULL; 15 | return temp; 16 | } 17 | 18 | /* Function to remove duplicates from a 19 | unsorted linked list */ 20 | void removeDuplicates(struct Node* start) 21 | { 22 | struct Node *ptr1, *ptr2, *dup; 23 | ptr1 = start; 24 | 25 | /* Pick elements one by one */ 26 | while (ptr1 != NULL && ptr1->next != NULL) { 27 | ptr2 = ptr1; 28 | 29 | /* Compare the picked element with rest 30 | of the elements */ 31 | while (ptr2->next != NULL) { 32 | /* If duplicate then delete it */ 33 | if (ptr1->data == ptr2->next->data) { 34 | /* sequence of steps is important here */ 35 | ptr2->next = ptr2->next->next; 36 | delete (dup); 37 | } 38 | else 39 | ptr2 = ptr2->next; 40 | } 41 | ptr1 = ptr1->next; 42 | } 43 | } 44 | 45 | /* Function to print nodes in a given linked list */ 46 | void printList(struct Node* node) 47 | { 48 | while (node != NULL) { 49 | printf("%d ", node->data); 50 | node = node->next; 51 | } 52 | } 53 | 54 | int main() 55 | { 56 | /* The constructed linked list is: 57 | 10->12->11->11->12->11->10*/ 58 | struct Node* start = newNode(10); 59 | start->next = newNode(12); 60 | start->next->next = newNode(11); 61 | start->next->next->next = newNode(11); 62 | start->next->next->next->next = newNode(12); 63 | start->next->next->next->next->next = newNode(11); 64 | start->next->next->next->next->next->next = newNode(10); 65 | 66 | printf("Linked list before removing duplicates "); 67 | printList(start); 68 | 69 | removeDuplicates(start); 70 | 71 | printf("\nLinked list after removing duplicates "); 72 | printList(start); 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /C++/reverseString .cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | string s; 7 | cin>>s; 8 | stack st; 9 | for(int i=0;i 2 | using namespace std; 3 | 4 | struct node 5 | { 6 | int data; 7 | struct node *next; 8 | } *first = NULL; 9 | 10 | void create(int a[], int n) 11 | { 12 | struct node *last; 13 | struct node *t; 14 | first = new node; 15 | first->data = a[0]; 16 | first->next = NULL; 17 | last = first; 18 | 19 | for (int i = 1; i < n; i++) 20 | { 21 | t = new node; 22 | t->data = a[i]; 23 | t->next = NULL; 24 | last->next = t; 25 | last = t; 26 | } 27 | } 28 | 29 | void display(struct node *ptr) 30 | { 31 | while (ptr != NULL) 32 | { 33 | cout << ptr->data << " "; 34 | ptr = ptr->next; 35 | } 36 | cout << endl; 37 | } 38 | 39 | void reverse(struct node **head_ref) { 40 | struct node *temp = NULL; 41 | struct node *prev = NULL; 42 | struct node *current = (*head_ref); 43 | 44 | while(current != NULL) { 45 | temp = current->next; 46 | current->next = prev; 47 | prev = current; 48 | current = temp; 49 | } 50 | (*head_ref) = prev; 51 | } 52 | 53 | 54 | int main(){ 55 | 56 | int n; 57 | cout<<"Enter the length of the Linked List : "; 58 | cin>>n; 59 | cout< 2 | using namespace std; 3 | 4 | void reverse(int arr[],int n){ 5 | int i=0; 6 | while(i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | // There are 2 methods one by using the naive approach for reversing the string and another using the inbuilt function. 7 | 8 | string s1 = "ReverseTheString"; 9 | string ReversedString = ""; 10 | 11 | for(int i=s1.length()-1; i>=0; i--) 12 | { 13 | ReversedString += s1[i]; 14 | } 15 | 16 | cout< 2 | 3 | #define pb push_back 4 | #define MAX 10000000 5 | #define ll long long int 6 | 7 | using namespace std; 8 | 9 | bool status[1000000 + 1]; 10 | 11 | void siv(int N) { 12 | int sq = sqrt(N); 13 | 14 | for (int i = 4; i <= N; i += 2) { 15 | status[i] = 1; 16 | } 17 | 18 | for (int i = 3; i <= sq; i += 2) { 19 | if (status[i] == 0) { 20 | for (int j = i * i; j <= N; j += i) 21 | status[j] = 1; 22 | } 23 | } 24 | 25 | status[1] = 1; 26 | } 27 | 28 | void init() 29 | { 30 | int n; 31 | cin >> n; 32 | 33 | siv(n); // load primes 34 | 35 | if(!status[n]) { 36 | printf("%d is Prime\n", n); 37 | } else { 38 | printf("%d is not Prime\n", n); 39 | } 40 | 41 | } 42 | int main() 43 | { 44 | #ifndef ONLINE_JUDGE 45 | freopen("input.txt","r",stdin); 46 | freopen("output.txt","w",stdout); 47 | #endif 48 | 49 | init(); 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /C++/sortevenodd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | 5 | int Arr[] = {100,123,12,32,3,235,547,296,112,231,547}; 6 | int size = sizeof(Arr)/4; 7 | int odd[size],even[size]; 8 | int o=0,e=0; 9 | 10 | for(int i=0;i 2 | using namespace std; 3 | 4 | void swap(int *ab, int *cd) 5 | { 6 | int temp = *ab; 7 | *ab = *cd; 8 | *cd = temp; 9 | } 10 | 11 | int main() 12 | { 13 | int a = 23; 14 | int b = 42; 15 | 16 | cout<<"Original: \n"; 17 | cout<<"a: "< 2 | 3 | void main(){ 4 | int a[100],i,j,temp,n; 5 | 6 | printf("\nEnter the number of elements: "); 7 | scanf("%d",&n); 8 | 9 | for(i=0;ia[j]) 19 | { 20 | temp=a[i]; 21 | a[i]=a[j]; 22 | a[j]=temp; 23 | } 24 | } 25 | } 26 | 27 | printf("\nThe sorted array is: "); 28 | for(i=0;i 3 | #include 4 | 5 | /* Link list node */ 6 | struct Node 7 | { 8 | int data; 9 | struct Node* next; 10 | }; 11 | 12 | 13 | void push(struct Node** head_ref, int new_data) 14 | { 15 | /* allocate node */ 16 | struct Node* new_node = 17 | (struct Node*) malloc(sizeof(struct Node)); 18 | 19 | 20 | new_node->data = new_data; 21 | new_node->next = (*head_ref); 22 | (*head_ref) = new_node; 23 | } 24 | 25 | /* Counts the no. of occurences of a node 26 | (search_for) in a linked list (head)*/ 27 | int count(struct Node* head, int search_for) 28 | { 29 | struct Node* current = head; 30 | int count = 0; 31 | while (current != NULL) 32 | { 33 | if (current->data == search_for) 34 | count++; 35 | current = current->next; 36 | } 37 | return count; 38 | } 39 | 40 | 41 | int main() 42 | { 43 | 44 | struct Node* head = NULL; 45 | 46 | 47 | push(&head, 1); 48 | push(&head, 3); 49 | push(&head, 1); 50 | push(&head, 2); 51 | push(&head, 1); 52 | 53 | 54 | printf("count of 1 is %d", count(head, 1)); 55 | 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /C/Cyclically_rotate_an_array_by_one.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void rotate(int arr[], int n); 4 | 5 | int main() 6 | { 7 | int t; 8 | scanf("%d",&t); 9 | while(t--) 10 | { 11 | int n; 12 | scanf("%d",&n); 13 | int a[n] , i; 14 | for(i=0;i=0;i--){ 28 | arr[i+1]=arr[i]; 29 | } 30 | arr[0]=temp; 31 | } 32 | -------------------------------------------------------------------------------- /C/Insertion_Sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void main(){ 3 | int a[10],i,j,key,n; 4 | printf("\nEnter the number of elements: "); 5 | scanf("%d",&n); 6 | for(i=0;i=0 && a[j]>key){ 14 | a[j+1]=a[j]; 15 | j=j-1; 16 | } 17 | a[j+1]=key; 18 | } 19 | printf("\nThe sorted array is: "); 20 | for(i=0;i 2 | #include 3 | 4 | struct node 5 | { 6 | int data; 7 | struct node *next; 8 | }; 9 | display(struct node *head) 10 | { 11 | if(head == NULL) 12 | { 13 | printf("NULL\n"); 14 | } 15 | else 16 | { 17 | printf("%d\n", head -> data); 18 | display(head->next); 19 | } 20 | } 21 | 22 | del (struct node *before_del) 23 | { 24 | struct node *temp; 25 | temp = before_del->next; 26 | before_del->next = temp->next; 27 | free(temp); 28 | } 29 | 30 | int main() 31 | { 32 | struct node *prev,*head, *p; 33 | int n,i; 34 | printf ("number of elements:"); 35 | scanf("%d",&n); 36 | head=NULL; 37 | for(i=0;idata); 41 | p->next=NULL; 42 | if(head==NULL) 43 | head=p; 44 | else 45 | prev->next=p; 46 | prev=p; 47 | } 48 | /*node to be deleted is head->next->next*/ 49 | del(head->next); 50 | display(head); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C/NumberOfGivenInt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node { 5 | int data; 6 | struct Node* next; 7 | }; 8 | 9 | void push(struct Node** head_ref, int new_data) 10 | { 11 | struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); 12 | new_node->data = new_data; 13 | new_node->next = (*head_ref); 14 | (*head_ref) = new_node; 15 | } 16 | 17 | int count(struct Node* head, int search_for) 18 | { 19 | struct Node* current = head; 20 | int count = 0; 21 | while (current != NULL) { 22 | if (current->data == search_for) 23 | count++; 24 | current = current->next; 25 | } 26 | return count; 27 | } 28 | 29 | int main() 30 | { 31 | struct Node* head = NULL; 32 | push(&head, 1); 33 | push(&head, 3); 34 | push(&head, 1); 35 | push(&head, 2); 36 | push(&head, 1); 37 | 38 | printf("count of 1 is %d", count(head, 1)); 39 | return 0; 40 | } -------------------------------------------------------------------------------- /C/QuickSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printArray(int *arr, int n) 4 | { 5 | for (int i = 0; i < n; i++) 6 | { 7 | printf("%d ", arr[i]); 8 | } 9 | printf("\n"); 10 | } 11 | 12 | int partition(int arr[], int low, int high) 13 | { 14 | int pivot = arr[low]; 15 | int i = low + 1; 16 | int j = high; 17 | int temp; 18 | 19 | do 20 | { 21 | while (arr[i] <= pivot) 22 | { 23 | i++; 24 | } 25 | 26 | while (arr[j] > pivot) 27 | { 28 | j--; 29 | } 30 | 31 | if (i < j) 32 | { 33 | temp = arr[i]; 34 | arr[i] = arr[j]; 35 | arr[j] = temp; 36 | } 37 | } while (i < j); 38 | 39 | // Swap arr[low] and arr[j] 40 | temp = arr[low]; 41 | arr[low] = arr[j]; 42 | arr[j] = temp; 43 | 44 | return j; 45 | } 46 | 47 | void quickSort(int arr[], int low, int high, int n) 48 | { 49 | int partitionIndex; // Index of Pivot after partition 50 | 51 | if (low < high) 52 | { 53 | partitionIndex = partition(arr, low, high); 54 | // printArray(arr, n); 55 | quickSort(arr, low, partitionIndex - 1, n); // sort left subarray 56 | quickSort(arr, partitionIndex + 1, high, n); // sort right subarray 57 | } 58 | } 59 | 60 | int main() 61 | { 62 | int n; 63 | printf("Enter the size of the array: "); 64 | scanf("%d", &n); 65 | int arr[n]; 66 | printf("Enter the elements of the array: "); 67 | for (int i = 0; i < n; i++) 68 | { 69 | scanf("%d", &arr[i]); 70 | } 71 | printf("Before sorting "); 72 | printArray(arr, n); 73 | printf("Sorting by Quick Sort\n"); 74 | quickSort(arr, 0, n - 1, n); 75 | printf("After sorting by Quick Sort "); 76 | printArray(arr, n); 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /C/Selection_Sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void print(int a[],int n){ 4 | printf("\nThe sorted array is: "); 5 | for(int i=0;i 2 | #include 3 | 4 | /* Link list node */ 5 | struct Node 6 | { 7 | int data; 8 | struct Node* next; 9 | }; 10 | 11 | 12 | void push(struct Node** head_ref, int new_data) 13 | { 14 | /* allocate node */ 15 | struct Node* new_node = 16 | (struct Node*) malloc(sizeof(struct Node)); 17 | 18 | /* put in the data */ 19 | new_node->data = new_data; 20 | 21 | /* link the old list off the new node */ 22 | new_node->next = (*head_ref); 23 | 24 | /* move the head to point to the new node */ 25 | (*head_ref) = new_node; 26 | } 27 | 28 | // Counts the no. of occurences of a node 29 | 30 | int count(struct Node* head, int search_for) 31 | { 32 | struct Node* current = head; 33 | int count = 0; 34 | while (current != NULL) 35 | { 36 | if (current->data == search_for) 37 | count++; 38 | current = current->next; 39 | } 40 | return count; 41 | } 42 | 43 | 44 | int main() 45 | { 46 | /* Start with the empty list */ 47 | struct Node* head = NULL; 48 | 49 | push(&head, 10); 50 | push(&head, 3); 51 | push(&head, 10); 52 | push(&head, 2); 53 | push(&head, 10); 54 | push(&head, 5); 55 | push(&head, 10); 56 | push(&head, 6); 57 | push(&head, 9); 58 | push(&head, 12); 59 | push(&head, 56); 60 | push(&head, 10); 61 | 62 | /* Check the count function */ 63 | printf("Frequency of 10 is %d", count(head, 10)); 64 | return 0; 65 | } 66 | 67 | // output 68 | // Frequency of 10 is 5 69 | -------------------------------------------------------------------------------- /C/int-count-llist.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct llist 5 | { 6 | int value; 7 | struct llist* next; 8 | 9 | }; 10 | 11 | int main() 12 | { 13 | int i, n, num, s, t, count = 0; 14 | 15 | struct llist* head = (struct llist*)malloc(sizeof(struct llist)); 16 | struct llist* prev = (struct llist*)malloc(sizeof(struct llist)); 17 | prev = head; 18 | 19 | printf("No of terms in linked list: "); 20 | scanf("%d", &n); 21 | 22 | printf("\nEnter list values:\n"); 23 | scanf("%d",&t); 24 | prev->value = t; 25 | prev->next = NULL; 26 | 27 | for(i=1;inext = new; 31 | scanf("%d",&t); 32 | new->value = t; 33 | new->next = NULL; 34 | prev = prev->next; 35 | } 36 | 37 | printf("\nEnter the value to be counted: "); 38 | scanf("%d",&s); 39 | 40 | prev = head; 41 | while(prev != NULL) 42 | { 43 | if(prev->value == s) 44 | count++; 45 | prev = prev->next; 46 | } 47 | printf("\nThe value %d occurs %d times.\n",s,count); 48 | return 0; 49 | } -------------------------------------------------------------------------------- /C/linkedListInsertion.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | struct node 6 | { 7 | int data; 8 | struct node *next; 9 | }; 10 | 11 | 12 | void addLast(struct node **head, int val) 13 | { 14 | //create a new node 15 | struct node *newNode = malloc(sizeof(struct node)); 16 | newNode->data = val; 17 | newNode->next = NULL; 18 | 19 | //if head is NULL, it is an empty list 20 | if(*head == NULL) 21 | *head = newNode; 22 | //Otherwise, find the last node and add the newNode 23 | else 24 | { 25 | struct node *lastNode = *head; 26 | 27 | //last node's next address will be NULL. 28 | while(lastNode->next != NULL) 29 | { 30 | lastNode = lastNode->next; 31 | } 32 | 33 | //add the newNode at the end of the linked list 34 | lastNode->next = newNode; 35 | } 36 | 37 | } 38 | 39 | void printList(struct node *head) 40 | { 41 | struct node *temp = head; 42 | 43 | //iterate the entire linked list and print the data 44 | while(temp != NULL) 45 | { 46 | printf("%d->", temp->data); 47 | temp = temp->next; 48 | } 49 | printf("NULL\n"); 50 | } 51 | 52 | int main() 53 | { 54 | struct node *head = NULL; 55 | int n, item; 56 | 57 | 58 | printf("crate a linked list size of : "); 59 | scanf("%d",&n); 60 | printf("Enter items for linked list :"); 61 | for(int i=0; i 2 | #include 3 | struct Stack 4 | { 5 | int top; 6 | int size; 7 | char *arr; 8 | }; 9 | 10 | int isEmpty(struct Stack *sp) 11 | { 12 | if(sp->top <= -1) 13 | { 14 | return 1; 15 | } 16 | else 17 | { 18 | return 0; 19 | } 20 | } 21 | 22 | int isFull(struct Stack *sp) 23 | { 24 | if(sp->top >= sp->size) 25 | { 26 | return 1; 27 | } 28 | else 29 | { 30 | return 0; 31 | } 32 | } 33 | 34 | void push(struct Stack *sp,char val) 35 | { 36 | if(isFull(sp)) 37 | { 38 | printf("Stack overflow\n"); 39 | } 40 | else 41 | { 42 | sp->top = sp->top + 1; 43 | sp->arr[sp->top] = val; 44 | } 45 | } 46 | 47 | void pop(struct Stack*sp) 48 | { 49 | if(isEmpty(sp)) 50 | { 51 | printf("Stack Underflow\n"); 52 | } 53 | else 54 | { 55 | sp->top = sp->top - 1; 56 | } 57 | } 58 | 59 | int parenthesisMatch( char *exp) 60 | { 61 | struct Stack *sp; 62 | sp->size = 100; 63 | sp->top = -1; 64 | sp->arr = (char*)malloc(sizeof(char)); 65 | 66 | for (int i = 0; exp[i]!='\0'; i++) 67 | { 68 | if(exp[i]=='(') 69 | { 70 | push(sp,'('); 71 | } 72 | else if( exp[i]==')') 73 | { 74 | if(isEmpty(sp)) 75 | { 76 | return 0; 77 | } 78 | pop(sp); 79 | } 80 | } 81 | 82 | if(isEmpty(sp)) 83 | { 84 | return 1; 85 | } 86 | else 87 | { 88 | return 0; 89 | } 90 | 91 | } 92 | 93 | int main() 94 | { 95 | char *exp = "8*(9)*(7866(99---))"; 96 | if (parenthesisMatch(exp)) 97 | { 98 | printf("The parenthesis is matching\n"); 99 | } 100 | else 101 | { 102 | printf("The parenthesis is not matching\n"); 103 | } 104 | 105 | return 0; 106 | } 107 | -------------------------------------------------------------------------------- /C/tree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | struct node { 4 | int data; 5 | struct node* left; 6 | struct node* right; 7 | }; 8 | 9 | /* newNode() allocates a new node 10 | with the given data and NULL left 11 | and right pointers. */ 12 | struct node* newNode(int data) 13 | { 14 | // Allocate memory for new node 15 | struct node* node 16 | = (struct node*)malloc(sizeof(struct node)); 17 | 18 | // Assign data to this node 19 | node->data = data; 20 | 21 | // Initialize left and 22 | // right children as NULL 23 | node->left = NULL; 24 | node->right = NULL; 25 | return (node); 26 | } 27 | 28 | int main() 29 | { 30 | /*create root*/ 31 | struct node* root = newNode(1); 32 | /* following is the tree after above statement 33 | 1 34 | / \ 35 | NULL NULL 36 | */ 37 | 38 | root->left = newNode(2); 39 | root->right = newNode(3); 40 | /* 2 and 3 become left and right children of 1 41 | 1 42 | / \ 43 | 2 3 44 | / \ / \ 45 | NULL NULL NULL NULL 46 | */ 47 | 48 | root->left->left = newNode(4); 49 | /* 4 becomes left child of 2 50 | 1 51 | / \ 52 | 2 3 53 | / \ / \ 54 | 4 NULL NULL NULL 55 | / \ 56 | NULL NULL 57 | */ 58 | 59 | getchar(); 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Java/CheckBST.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution 3 | { 4 | static boolean BSTUtil(Node root, int min, int max){ 5 | if(root == null){ 6 | return true; 7 | } 8 | 9 | if(root.data < min || root.data > max){ 10 | return false; 11 | } 12 | 13 | return (BSTUtil(root.left, min, root.data-1) && BSTUtil(root.right,root.data+1,max)); 14 | } 15 | 16 | 17 | //Function to check whether a Binary Tree is BST or not. 18 | boolean isBST(Node root) 19 | { 20 | // code here. 21 | int min = Integer.MIN_VALUE,max = Integer.MAX_VALUE; 22 | if(BSTUtil(root,min,max)){ 23 | return true; 24 | } 25 | else{ 26 | return false; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Java/EvenAfterOddLL.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class EvenAfterOddLL { 4 | 5 | public static Node takeInput() 6 | { 7 | Nodehead=null,tail=null; 8 | Scanner s=new Scanner(System.in); 9 | int data=s.nextInt(); 10 | 11 | while(data!=-1) 12 | { 13 | Nodenode=new Node(data); 14 | if(head==null) 15 | { 16 | head=node; 17 | tail=node; 18 | } 19 | else 20 | { 21 | // Nodetemp=head; 22 | // while(temp.next!=null) 23 | // { 24 | // temp=temp.next; 25 | // } 26 | // temp.next=node; 27 | 28 | tail.next=node; 29 | tail=tail.next; 30 | 31 | } 32 | data=s.nextInt(); 33 | } 34 | return head; 35 | } 36 | 37 | public static Node evenAfterOdd(Node head) { 38 | 39 | Nodeeh=null; 40 | Nodeet=null; 41 | Nodeoh=null; 42 | Nodeot=null; 43 | 44 | while(head!=null) 45 | { 46 | if(head.data%2!=0) //odd 47 | { 48 | if(oh==null) 49 | { 50 | oh=head; 51 | ot=oh; 52 | } 53 | else 54 | { 55 | ot.next=head; 56 | ot=ot.next; 57 | } 58 | } 59 | else 60 | { 61 | if(eh==null) 62 | { 63 | eh=head; 64 | et=eh; 65 | } 66 | else 67 | { 68 | et.next=head; 69 | et=et.next; 70 | } 71 | } 72 | head=head.next; 73 | } 74 | 75 | if(ot==null) 76 | { 77 | return eh; 78 | } 79 | if(eh==null) 80 | { 81 | return oh; 82 | } 83 | 84 | ot.next=eh; 85 | et.next=null; 86 | return oh; 87 | 88 | } 89 | 90 | public static void print(Nodehead) 91 | { 92 | Nodetemp=head; 93 | while(temp!=null) 94 | { 95 | System.out.print(temp.data+" "); 96 | temp=temp.next; 97 | } 98 | } 99 | public static void main(String[] args) { 100 | Nodehead=takeInput(); 101 | Nodeans=evenAfterOdd(head); 102 | print(ans); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /Java/ExecuteBinarySearchOnAVector.java: -------------------------------------------------------------------------------- 1 | import java.util.Collections; 2 | import java.util.Vector; 3 | 4 | public class ExecuteBunarySearchOnVector{ 5 | public static void main(String[] args) { 6 | Vector v = new Vector(); 7 | v.add("X"); 8 | v.add("M"); 9 | v.add("D"); 10 | v.add("A"); 11 | v.add("O"); 12 | Collections.sort(v); 13 | System.out.println(v); 14 | int index = Collections.binarySearch(v, "D"); 15 | System.out.println("Element found at : " + index); 16 | } 17 | } 18 | Result 19 | -------------------------------------------------------------------------------- /Java/Happy Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private int getNext(int n) { 4 | int totalSum = 0; 5 | while (n > 0) { 6 | int d = n % 10; 7 | n = n / 10; 8 | totalSum += d * d; 9 | } 10 | return totalSum; 11 | } 12 | 13 | public boolean isHappy(int n) { 14 | Set seen = new HashSet<>(); 15 | while (n != 1 && !seen.contains(n)) { 16 | seen.add(n); 17 | n = getNext(n); 18 | } 19 | return n == 1; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/LeftViewOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* A Binary Tree node 2 | class Node 3 | { 4 | int data; 5 | Node left, right; 6 | Node(int item) 7 | { 8 | data = item; 9 | left = right = null; 10 | } 11 | }*/ 12 | class Tree 13 | { 14 | static int maxLevel; 15 | static void traverse(Node root, ArrayList leftNodes, int level){ 16 | if(root == null){ 17 | return; 18 | } 19 | if(level > maxLevel){ 20 | leftNodes.add(root.data); 21 | maxLevel = level; 22 | } 23 | 24 | traverse(root.left,leftNodes,level+1); 25 | traverse(root.right, leftNodes,level+1); 26 | } 27 | 28 | //Function to return list containing elements of left view of binary tree. 29 | ArrayList leftView(Node root) 30 | { 31 | // Your code here 32 | ArrayList leftNodes = new ArrayList(); 33 | int level = 0; 34 | maxLevel = -1; 35 | traverse(root, leftNodes, level); 36 | return leftNodes; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Java/Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean hasCycle(ListNode head) { 3 | ListNode a=head; 4 | 5 | ListNode b=head; 6 | 7 | while(a!=null&&b!=null&&b.next!=null){ 8 | a=a.next; 9 | b=b.next.next; 10 | if(a==b){ 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/ListNode.java: -------------------------------------------------------------------------------- 1 | 2 | // * Definition for singly-linked list. 3 | public class ListNode { 4 | int val; 5 | ListNode next; 6 | ListNode() {} 7 | ListNode(int val) { this.val = val; } 8 | ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | } 10 | 11 | class LinkedList { 12 | 13 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 14 | int sum = 0; 15 | int carry=0; 16 | ListNode t = new ListNode(0); 17 | ListNode t_s = t; 18 | 19 | while(l1 != null && l2 != null){ 20 | carry = sum/10; 21 | sum = l1.val+l2.val+carry; 22 | t.next = new ListNode(sum%10); 23 | t = t.next; 24 | l1 = l1.next; 25 | l2 = l2.next; 26 | } 27 | while (l1 != null){ 28 | carry = sum/10; 29 | sum = l1.val+carry; 30 | t.next = new ListNode(sum%10); 31 | t = t.next; 32 | l1 = l1.next; 33 | } 34 | while(l2 != null){ 35 | carry = sum/10; 36 | sum = l2.val+carry; 37 | t.next = new ListNode(sum%10); 38 | t = t.next; 39 | l2 = l2.next; 40 | } 41 | carry = sum/10; 42 | if(carry != 0){ 43 | t.next = new ListNode(carry); 44 | t = t.next; 45 | } 46 | return t_s.next; 47 | } 48 | } -------------------------------------------------------------------------------- /Java/MidElementDeletion.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class GFG { 5 | 6 | static void deleteMid(Stack st, 7 | int n, int curr) 8 | { 9 | 10 | if (st.empty() || curr == n) 11 | return; 12 | 13 | char x = st.pop(); 14 | 15 | deleteMid(st, n, curr+1); 16 | 17 | if (curr != n/2) 18 | st.push(x); 19 | } 20 | 21 | public static void main(String args[]) 22 | { 23 | Stack st = 24 | new Stack(); 25 | 26 | st.push('1'); 27 | st.push('2'); 28 | st.push('3'); 29 | st.push('4'); 30 | st.push('5'); 31 | st.push('6'); 32 | st.push('7'); 33 | 34 | deleteMid(st, st.size(), 0); 35 | 36 | while (!st.empty()) 37 | { 38 | char p=st.pop(); 39 | System.out.print(p + " "); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Java/Palindrome_Number.java: -------------------------------------------------------------------------------- 1 | //contributed by subhash karthik. 2 | 3 | class Solution { 4 | public boolean isPalindrome(int x) { 5 | int temp = x; 6 | 7 | boolean flag = false; 8 | if(x < 0){ 9 | return flag; 10 | } 11 | 12 | int ans = 0; 13 | while(x != 0){ 14 | ans = ans * 10 + (x % 10); 15 | x = x / 10; 16 | } 17 | 18 | if(ans == temp){ 19 | flag = true; 20 | } 21 | 22 | return flag; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/Remove_element.java: -------------------------------------------------------------------------------- 1 | // code by subhash karthik 2 | 3 | class Solution { 4 | public int removeElement(int[] nums, int val) { 5 | 6 | int cnt = 0; 7 | for(int i = 0; i < nums.length; i++){ 8 | if(nums[i] != val){ 9 | nums[cnt] = nums[i]; 10 | cnt++; 11 | } 12 | } 13 | 14 | return cnt; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/Reverse_queue.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | import java.util.Stack; 4 | 5 | public class Reverse_k_element_queue { 6 | 7 | static Queue queue; 8 | 9 | // Function to reverse the first 10 | // K elements of the Queue 11 | static void reverseQueueFirstKElements(int k) 12 | { 13 | if (queue.isEmpty() == true 14 | || k > queue.size()) 15 | return; 16 | if (k <= 0) 17 | return; 18 | 19 | Stack stack = new Stack(); 20 | 21 | // Push the first K elements into a Stack 22 | for (int i = 0; i < k; i++) { 23 | stack.push(queue.peek()); 24 | queue.remove(); 25 | } 26 | 27 | // Enqueue the contents of stack 28 | // at the back of the queue 29 | while (!stack.empty()) { 30 | queue.add(stack.peek()); 31 | stack.pop(); 32 | } 33 | 34 | // Remove the remaining elements and enqueue 35 | // them at the end of the Queue 36 | for (int i = 0; i < queue.size() - k; i++) { 37 | queue.add(queue.peek()); 38 | queue.remove(); 39 | } 40 | } 41 | 42 | // Utility Function to print the Queue 43 | static void Print() 44 | { 45 | while (!queue.isEmpty()) { 46 | System.out.print(queue.peek() + " "); 47 | queue.remove(); 48 | } 49 | } 50 | 51 | // Driver code 52 | public static void main(String args[]) 53 | { 54 | queue = new LinkedList(); 55 | queue.add(10); 56 | queue.add(20); 57 | queue.add(30); 58 | queue.add(40); 59 | queue.add(50); 60 | queue.add(60); 61 | queue.add(70); 62 | queue.add(80); 63 | queue.add(90); 64 | queue.add(100); 65 | 66 | int k = 5; 67 | reverseQueueFirstKElements(k); 68 | Print(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Java/RotateMatrixBy90Degrees.java: -------------------------------------------------------------------------------- 1 | public class RotateMatrixBy90Degrees 2 | { 3 | // Takes Matrix and Size of Matrix and performs Clockwise or Right Rotation by 90 degrees. 4 | static void rightRotate(int matrix[][],int n) 5 | { 6 | 7 | //At first we perform transpose of the matrix 8 | //by swapping elements of every i'th row with j'th column 9 | for(int i=0;i[]edge, int subtree[]) 10 | { 11 | int sum = subtree[u]; 12 | 13 | for (int i = 0; i < edge[u].size (); i++) 14 | { 15 | int v = edge[u].get (i); 16 | 17 | if (v != parent) 18 | { 19 | dfs (v, u, totalSum, edge, subtree); 20 | sum += subtree[v]; 21 | } 22 | } 23 | 24 | subtree[u] = sum; 25 | 26 | if (u != 0 && Math.abs (totalSum - 2 * sum) < res) 27 | res = Math.abs (totalSum - 2 * sum); 28 | } 29 | 30 | static int getMinSubtreeSumDifference (int vertex[], int[][]edges, int N) 31 | { 32 | int totalSum = 0; 33 | int[] subtree = new int[N]; 34 | 35 | for (int i = 0; i < N; i++) 36 | { 37 | subtree[i] = vertex[i]; 38 | totalSum += vertex[i]; 39 | } 40 | 41 | @SuppressWarnings ("unchecked") 42 | ArrayList < Integer >[]edge = new ArrayList[N]; 43 | for (int i = 0; i < N; i++) 44 | { 45 | edge[i] = new ArrayList <> (); 46 | } 47 | for (int i = 0; i < N - 1; i++) 48 | { 49 | edge[edges[i][0]].add (edges[i][1]); 50 | edge[edges[i][1]].add (edges[i][0]); 51 | } 52 | 53 | dfs (0, -1, totalSum, edge, subtree); 54 | return res; 55 | } 56 | 57 | public static void main (String[]args) 58 | { 59 | res = Integer.MAX_VALUE; 60 | 61 | int[] vertex = { 4, 2, 1, 6, 3, 5, 2 }; 62 | int[][] edges = { {0, 1}, {0, 2}, 63 | {0, 3}, {2, 4}, 64 | {2, 5}, {3, 6} 65 | }; 66 | int N = vertex.length; 67 | 68 | System.out.println (getMinSubtreeSumDifference (vertex, edges, N)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Java/TernarySearch.java: -------------------------------------------------------------------------------- 1 | class TernarySearcher { 2 | 3 | static int search(int l, int r, int key, int ar[]) 4 | { 5 | if (r >= l) { 6 | int mid1 = l + (r - l) / 3; 7 | int mid2 = r - (r - l) / 3; 8 | 9 | if (ar[mid1] == key) { 10 | return mid1; 11 | } 12 | if (ar[mid2] == key) { 13 | return mid2; 14 | } 15 | 16 | if (key < ar[mid1]) { 17 | return search(l, mid1 - 1, key, ar); 18 | } 19 | else if (key > ar[mid2]) { 20 | return search(mid2 + 1, r, key, ar); 21 | } 22 | else { 23 | return search(mid1 + 1, mid2 - 1, key, ar); 24 | } 25 | } 26 | return -1; 27 | } 28 | public static void main(String args[]) 29 | { 30 | int l, r, p, key; 31 | int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 32 | l = 0; 33 | r = 9; 34 | key = 5; 35 | p = search(l, r, key, ar); 36 | System.out.println("Index of " + key + " is " + p); 37 | key = 50; 38 | p = search(l, r, key, ar); 39 | System.out.println("Index of " + key + " is " + p); 40 | } 41 | } -------------------------------------------------------------------------------- /Java/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | // Problem link: https://leetcode.com/problems/trapping-rain-water/# 2 | class Solution { 3 | public int trap(int[] A) { 4 | int n = A.length; 5 | int temp,hght,lvl=0; 6 | int[] left = new int[n]; 7 | int[] right= new int[n]; 8 | int i,lmax=0,rmax=0; 9 | for(i=0;ilmax) 11 | lmax=A[i]; 12 | left[i]=lmax; 13 | } 14 | for(i=n-1;i>=0;i--){ 15 | if(A[i]>rmax) 16 | rmax=A[i]; 17 | right[i]=rmax; 18 | } 19 | for(i=0;i st = new Stack<>(); 6 | 7 | for(int i = 0; i < str.length(); i++){ 8 | char ch = str.charAt(i); 9 | if(ch == '[' || ch == '{' || ch == '('){ 10 | st.push(ch); 11 | }else if(ch == ']'){ 12 | if(st.size() == 0){ 13 | return false; 14 | }else if(st.peek() != '['){ 15 | return false; 16 | }else{ 17 | st.pop(); 18 | } 19 | }else if(ch == '}'){ 20 | if(st.size() == 0){ 21 | return false; 22 | }else if(st.peek() != '{'){ 23 | return false; 24 | }else{ 25 | st.pop(); 26 | } 27 | }else if(ch == ')'){ 28 | if(st.size() == 0){ 29 | return false; 30 | }else if(st.peek() != '('){ 31 | return false; 32 | }else{ 33 | st.pop(); 34 | } 35 | } 36 | } 37 | 38 | if(st.size() == 0){ 39 | return true; 40 | }else{ 41 | return false; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Java/bubble_sort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Bubble Sort 2 | class BubbleSort 3 | { 4 | void bubbleSort(int arr[]) 5 | { 6 | int n = arr.length; 7 | for (int i = 0; i < n-1; i++) 8 | for (int j = 0; j < n-i-1; j++) 9 | if (arr[j] > arr[j+1]) 10 | { 11 | // swap arr[j+1] and arr[j] 12 | int temp = arr[j]; 13 | arr[j] = arr[j+1]; 14 | arr[j+1] = temp; 15 | } 16 | } 17 | 18 | /* Prints the array in compilers*/ 19 | void printArray(int arr[]) 20 | { 21 | int n = arr.length; 22 | for (int i=0; i0) { 7 | int n=sc.nextInt(); 8 | int []arr=new int[n]; 9 | for(int i=0;i=0){ 15 | cm=cm+arr[i]; 16 | } 17 | else{ 18 | cm=arr[i]; 19 | } 20 | if(cm>res){ 21 | res=cm; 22 | } 23 | } 24 | System.out.println(res); 25 | t--; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Java/kth _min_max_element: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class kth_min_max_Element { 3 | static void sort(int arr[], int n,int k){ 4 | int i,j,temp; 5 | for(i=1;i0 && arr[j-1]>temp){ 9 | arr[j]=arr[j-1]; 10 | j=j-1; 11 | } 12 | arr[j]=temp; 13 | 14 | } 15 | for(i=0;i= board.length || j < 0 || j >= board[i].length || word.charAt(count) != board[i][j]) 25 | return false; 26 | 27 | char temp = board[i][j]; 28 | board[i][j] = ' '; 29 | boolean found = dfs(board, i+1, j, count+1, word) || 30 | dfs(board, i-1, j, count+1, word) || 31 | dfs(board, i, j-1, count+1, word) || 32 | dfs(board, i, j+1, count+1, word); 33 | 34 | board[i][j] = temp; 35 | return found; 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /JavaSript/Longest Common Prefix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} strs 3 | * @return {string} 4 | */ 5 | var longestCommonPrefix = function(strs) { 6 | let ans=''; 7 | if(strs.length<=0) return ans; 8 | 9 | let first=strs[0]; 10 | let j=0; 11 | for(let c of first){ 12 | for(let i=1;i=strs[i].length || c!=strs[i][j]){ 14 | return ans; 15 | } 16 | } 17 | ans+=c; 18 | j++ 19 | 20 | } 21 | return ans 22 | }; 23 | -------------------------------------------------------------------------------- /JavaSript/Pascal's Triangle.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} numRows 3 | * @return {number[][]} 4 | */ 5 | var generate = function(numRows) { 6 | let outer=[]; 7 | let first_row=[1]; 8 | outer.push(first_row); 9 | for(let i=1;i Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. 8 | 9 | [check the code](fizzbuzz.js) and the [test](__tests__/fizzbuzz.test.js) 10 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/FizzBuzz/fizzbuzz.js: -------------------------------------------------------------------------------- 1 | export const fizzBuzz1 = (num) => { 2 | return [...Array(num).keys()] 3 | .map((_, i) => i + 1) 4 | .map((i) => 5 | i % 15 === 0 6 | ? 'FizzBuzz' 7 | : i % 3 === 0 8 | ? 'Fizz' 9 | : i % 5 === 0 10 | ? 'Buzz' 11 | : i 12 | ); 13 | }; 14 | 15 | /* 16 | 17 | Break-down: 18 | 19 | [...Array(100).keys()] 20 | creates an empty array of length 100, and returns its keys, which are then used to build a new array, so we get [0 ... 99] 21 | 22 | .map((_, i) => i + 1) 23 | this replaces each element with its index incremented by 1, so we now have [1 ... 100] 24 | 25 | .map(i => ...) 26 | now we apply FizzBuzz logic, by testing all the possible combinations in the correct order, using the ternary operator 27 | 28 | */ 29 | 30 | export const fizzBuzz2 = (num) => { 31 | let fizzedBuzzedArr = []; 32 | 33 | for (let i = 1; i <= num; i++) { 34 | if (i % 3 === 0 && i % 5 === 0) { 35 | fizzedBuzzedArr.push('FizzBuzz'); 36 | } else if (i % 3 === 0) { 37 | fizzedBuzzedArr.push('Fizz'); 38 | } else if (i % 5 === 0) { 39 | fizzedBuzzedArr.push('Buzz'); 40 | } else { 41 | fizzedBuzzedArr.push(i); 42 | } 43 | } 44 | 45 | return fizzedBuzzedArr; 46 | }; 47 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/RiverSizes/index.js: -------------------------------------------------------------------------------- 1 | function riverSizes(matrix) { 2 | const sizes = []; 3 | const visited = matrix.map((row) => row.map(() => false)); 4 | for (let i = 0; i < matrix.length; i++) { 5 | for (let j = 0; j < matrix[i].length; j++) { 6 | if (visited[i][j]) continue; 7 | traverseNode(i, j, matrix, visited, sizes); 8 | } 9 | } 10 | return sizes; 11 | } 12 | 13 | function traverseNode(i, j, matrix, visited, sizes) { 14 | let currentRiverSize = 0; 15 | const nodesToExplore = [[i, j]]; 16 | while (nodesToExplore.length) { 17 | const currentNode = nodesToExplore.pop(); 18 | i = currentNode[0]; 19 | j = currentNode[1]; 20 | if (visited[i][j]) continue; 21 | visited[i][j] = true; 22 | if (matrix[i][j] === 0) continue; 23 | currentRiverSize++; 24 | const unvisitedNeighbors = getUnvisitedNeighbors(i, j, matrix, visited); 25 | for (const neighbor of unvisitedNeighbors) { 26 | nodesToExplore.push(neighbor); 27 | } 28 | } 29 | if (currentRiverSize > 0) sizes.push(currentRiverSize); 30 | } 31 | 32 | function getUnvisitedNeighbors(i, j, matrix, visited) { 33 | const unvisitedNeighbors = []; 34 | if (i > 0 && !visited[i - 1][j]) unvisitedNeighbors.push([i - 1, j]); 35 | if (i < matrix.length - 1 && !visited[i + 1][j]) 36 | unvisitedNeighbors.push([i + 1, j]); 37 | if (j > 0 && !visited[i][j - 1]) unvisitedNeighbors.push([i, j - 1]); 38 | if (j < matrix[0].length - 1 && !visited[i][j + 1]) 39 | unvisitedNeighbors.push([i, j + 1]); 40 | return unvisitedNeighbors; 41 | } 42 | 43 | export default riverSizes; 44 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/RiverSizes/index.test.js: -------------------------------------------------------------------------------- 1 | import riverSizes from '.'; 2 | 3 | describe('Name of the group', () => { 4 | it('should return the length of each river (1s) in the map', () => { 5 | const matrix = [ 6 | [1, 0, 0, 1, 0], 7 | [1, 0, 1, 0, 0], 8 | [0, 0, 1, 0, 1], 9 | [1, 0, 1, 0, 1], 10 | [1, 0, 1, 1, 0], 11 | ]; 12 | 13 | expect(riverSizes(matrix)).toEqual([2, 1, 5, 2, 2]); 14 | }); 15 | 16 | it('should return correctly', () => { 17 | expect(riverSizes([[1]])).toEqual([1]); 18 | 19 | expect(riverSizes([[0]])).toEqual([]); 20 | 21 | expect(riverSizes([[1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0]])).toEqual([3, 2, 1]); 22 | 23 | expect( 24 | riverSizes([ 25 | [1, 0, 0, 1], 26 | [1, 0, 1, 0], 27 | [0, 0, 1, 0], 28 | [1, 0, 1, 0], 29 | ]) 30 | ).toEqual([2, 1, 3, 1]); 31 | 32 | expect( 33 | riverSizes([ 34 | [1, 0, 0, 0, 0, 0, 1], 35 | [0, 1, 0, 0, 0, 1, 0], 36 | [0, 0, 1, 0, 1, 0, 0], 37 | [0, 0, 1, 1, 1, 0, 0], 38 | [0, 0, 1, 0, 1, 0, 0], 39 | [0, 1, 0, 0, 0, 1, 0], 40 | [1, 0, 0, 0, 0, 0, 1], 41 | ]) 42 | ).toEqual([1, 1, 1, 1, 7, 1, 1, 1, 1]); 43 | 44 | expect( 45 | riverSizes([ 46 | [0, 0, 0, 0, 0, 0, 0], 47 | [0, 0, 0, 0, 0, 0, 0], 48 | [0, 0, 0, 0, 0, 0, 0], 49 | [0, 0, 0, 0, 0, 0, 0], 50 | [0, 0, 0, 0, 0, 0, 0], 51 | [0, 0, 0, 0, 0, 0, 0], 52 | [0, 0, 0, 0, 0, 0, 0], 53 | ]) 54 | ).toEqual([]); 55 | }); 56 | }); 57 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/firstBadVersion/README.md: -------------------------------------------------------------------------------- 1 | isBadVersion 2 | 3 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 4 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 5 | 6 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 7 | 8 | Example: 9 | Given n = 5, and version = 4 is the first bad version. 10 | 11 | ``` 12 | call isBadVersion(3) -> false 13 | call isBadVersion(5) -> true 14 | call isBadVersion(4) -> true 15 | Then 4 is the first bad version. 16 | ``` 17 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/firstBadVersion/index.js: -------------------------------------------------------------------------------- 1 | export const firstBadVersionNaive = (n, isBadVersionFn) => { 2 | for (let i = 0; i < n; i++) { 3 | if (isBadVersionFn(i)) return i; 4 | } 5 | }; 6 | 7 | const firstBadVersionHelper = (left, right, isBadVersionFn) => { 8 | const middle = Math.floor((left + right) / 2); 9 | const isBadVersion = isBadVersionFn(middle); 10 | if (right - left === 1) { 11 | return middle + 1; 12 | } else if (isBadVersion) { 13 | return firstBadVersionHelper(left, middle, isBadVersionFn); 14 | } else { 15 | return firstBadVersionHelper(middle + 1, right, isBadVersionFn); 16 | } 17 | }; 18 | 19 | const firstBadVersion = (n, isBadVersionFn) => { 20 | return firstBadVersionHelper(0, n, isBadVersionFn); 21 | }; 22 | 23 | export default firstBadVersion; 24 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/firstBadVersion/index.test.js: -------------------------------------------------------------------------------- 1 | import {displayPerfTime} from '../../utils/perf-utils'; 2 | 3 | import firstBadVersion, {firstBadVersionNaive} from '.'; 4 | 5 | describe('firstBadVersion', () => { 6 | const isBadVersionMockFn = jest 7 | .fn() 8 | .mockImplementation((v) => (v > 167 ? true : false)); 9 | 10 | beforeEach(() => { 11 | isBadVersionMockFn.mockClear(); 12 | }); 13 | 14 | it('find the first bad version naively', () => { 15 | expect(firstBadVersionNaive(999, isBadVersionMockFn)).toEqual(168); 16 | expect(isBadVersionMockFn).toHaveBeenCalledTimes(169); 17 | }); 18 | 19 | it('find the first bad version', () => { 20 | expect(firstBadVersion(999, isBadVersionMockFn)).toEqual(168); 21 | expect(isBadVersionMockFn).toHaveBeenCalledTimes(10); 22 | }); 23 | 24 | describe('Performance', () => { 25 | it('will display perftime', () => { 26 | displayPerfTime('firstBadVersion(999)', () => { 27 | firstBadVersion(999, isBadVersionMockFn); 28 | }); 29 | }); 30 | 31 | it('will display perftime with another n', () => { 32 | displayPerfTime('firstBadVersion(100000000)', () => { 33 | firstBadVersion(100000000, isBadVersionMockFn); 34 | }); 35 | }); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getEvenOccurrences/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Get Even Occurrences 2 | 3 | Find the first even occurrence of a number in an array 4 | 5 | [Check the code](getevenoccurrence.js) and the [test](__tests__/getevenoccurrence.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getEvenOccurrences/__tests__/getevenoccurrence.test.js: -------------------------------------------------------------------------------- 1 | import getEvenOccurrence from '../getevenoccurrence'; 2 | 3 | describe('Even occurrence', () => { 4 | it('should return the first even occurrence of a number', () => { 5 | expect(getEvenOccurrence([])).toEqual(null); 6 | expect(getEvenOccurrence([1, 2, 3])).toEqual(null); 7 | expect(getEvenOccurrence([1, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6])).toEqual(2); 8 | expect(getEvenOccurrence([1, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6])).toEqual( 9 | 5 10 | ); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getEvenOccurrences/getevenoccurrence.js: -------------------------------------------------------------------------------- 1 | const getEvenOccurrence = (array) => { 2 | let storage = {}; 3 | 4 | array.forEach((value) => { 5 | storage[value] = storage[value] + 1 || 1; 6 | }); 7 | 8 | for (let i = 0; i < array.length; i++) { 9 | const current = array[i]; 10 | 11 | if (storage[current] % 2 === 0) { 12 | return current; 13 | } 14 | } 15 | 16 | return null; 17 | }; 18 | 19 | export default getEvenOccurrence; 20 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getMaxStack/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Get Max Stack 2 | 3 | Get the largest item in a stack 4 | 5 | [Check the code](getMaxStack.js) and the [test](__tests__/getMaxStack.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getMaxStack/__tests__/getMaxStack.test.js: -------------------------------------------------------------------------------- 1 | import GetMaxStack from '../getMaxStack'; 2 | 3 | describe('Get the max stack', () => { 4 | it('return the largest item in the stack', () => { 5 | const getMaxStack = new GetMaxStack(); 6 | 7 | getMaxStack.push(1); 8 | getMaxStack.push(5); 9 | getMaxStack.push(2); 10 | getMaxStack.push(12); 11 | getMaxStack.push(3); 12 | 13 | expect(getMaxStack.getMax()).toEqual(12); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getMaxStack/getMaxStack.js: -------------------------------------------------------------------------------- 1 | class Stack { 2 | constructor() { 3 | this.items = []; 4 | } 5 | 6 | push(item) { 7 | this.items.push(item); 8 | } 9 | 10 | pop() { 11 | // if the stack is empty, return null 12 | // (it would also be reasonable to throw an exception) 13 | if (!this.items.length) { 14 | return null; 15 | } 16 | return this.items.pop(); 17 | } 18 | 19 | peek() { 20 | if (!this.items.length) { 21 | return null; 22 | } 23 | return this.items[this.items.length - 1]; 24 | } 25 | } 26 | 27 | class GetMaxStack { 28 | constructor() { 29 | this.stack = new Stack(); 30 | this.maxesStack = new Stack(); 31 | } 32 | 33 | push(item) { 34 | this.stack.push(item); 35 | if (!this.maxesStack.peek() || item >= this.maxesStack.peek()) { 36 | this.maxesStack.push(item); 37 | } 38 | } 39 | 40 | pop() { 41 | var item = this.stack.pop(); 42 | if (item === this.maxesStack.peek()) { 43 | this.maxesStack.pop(); 44 | } 45 | return item; 46 | } 47 | 48 | getMax() { 49 | return this.maxesStack.peek(); 50 | } 51 | } 52 | 53 | export default GetMaxStack; 54 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getPermutations/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Get Permutations 2 | 3 | Get all the permutations of a string 4 | 5 | [Check the code](getpermutations.js) and the [test](__tests__/getpermutations.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getPermutations/__tests__/getpermutations.test.js: -------------------------------------------------------------------------------- 1 | import getPermutations from '../getpermutations'; 2 | 3 | describe('Get all permutations of a strinf', () => { 4 | it('should return all the permutations of a string', () => { 5 | const expectedPermutations = ['a']; 6 | expect(getPermutations('a')).toEqual(expectedPermutations); 7 | }); 8 | it('should return all the permutations of a string', () => { 9 | const expectedPermutations = ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']; 10 | expect(getPermutations('abc')).toEqual(expectedPermutations); 11 | }); 12 | it('should return all the permutations of a string', () => { 13 | const expectedPermutations = ['123', '132', '213', '231', '312', '321']; 14 | expect(getPermutations('123')).toEqual(expectedPermutations); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/getPermutations/getpermutations.js: -------------------------------------------------------------------------------- 1 | const getAllPermutations = (string) => { 2 | let results = []; 3 | 4 | if (string.length === 1) { 5 | results.push(string); 6 | return results; 7 | } 8 | 9 | for (let i = 0; i < string.length; i++) { 10 | const firstChar = string[i]; 11 | const charsLeft = string.substring(0, i) + string.substring(i + 1); 12 | const innerPermutations = getAllPermutations(charsLeft); 13 | 14 | for (let j = 0; j < innerPermutations.length; j++) { 15 | results.push(firstChar + innerPermutations[j]); 16 | } 17 | } 18 | return results; 19 | }; 20 | 21 | export default getAllPermutations; 22 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/isPalindrome/README.md: -------------------------------------------------------------------------------- 1 | # ⚗️ isPalindrome 2 | 3 | A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or “taco cat” or racecar. Sentence-length palindromes may be written when allowances are made for adjustments to capital letters, punctuation, and word dividers, such as "A man, a plan, a canal, Panama!", "Was it a car or a cat I saw?" or "No 'x' in Nixon". 4 | 5 | Given a string, check if it's a palindrome. 6 | 7 | [check the code](isPalindrome.js) and the [test](isPalindrome.test.js) 8 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/isPalindrome/index.js: -------------------------------------------------------------------------------- 1 | export const isPalindrome = (string) => { 2 | const validChars = 'abcdefghijklmnopqrstuvwxyz'; 3 | 4 | const stringArr = string 5 | .toLowerCase() 6 | .split('') 7 | .filter((char) => validChars.indexOf(char) !== -1); 8 | 9 | return stringArr.join('') === stringArr.reverse().join(''); 10 | }; 11 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/isPalindrome/index.test.js: -------------------------------------------------------------------------------- 1 | import {displayPerfTime} from '../../utils/perf-utils'; 2 | 3 | import {isPalindrome} from '.'; 4 | 5 | describe('isPalindrome', () => { 6 | it('should spot the palindrome right', () => { 7 | expect(isPalindrome("Madam, I'm Adam")).toBeTruthy(); 8 | }); 9 | it('should spot the palindrome right', () => { 10 | expect( 11 | isPalindrome( 12 | "T. Eliot, top bard, notes putrid tang emanating, is sad; I'd assign it a name: gnat dirt upset on drab pot toilet." 13 | ) 14 | ).toBeTruthy(); 15 | }); 16 | 17 | it('should spot a not-palindrome', () => { 18 | expect(isPalindrome("Madam, I'm Larry")).toBeFalsy(); 19 | }); 20 | 21 | describe('Performance', () => { 22 | it('will display perftime', () => { 23 | displayPerfTime('isPalindrome("Madam, I\'m Adam")', () => { 24 | isPalindrome("Madam, I'm Adam"); 25 | }); 26 | }); 27 | 28 | it('will display perftime with another palindrome', () => { 29 | displayPerfTime('isPalindrome("long one")', () => { 30 | isPalindrome( 31 | "T. Eliot, top bard, notes putrid tang emanating, is sad; I'd assign it a name: gnat dirt upset on drab pot toilet." 32 | ); 33 | }); 34 | }); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/meanMedianMode/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Mean Median Mode averages: 2 | 3 | To calculate the Mean 4 | 5 | Add the numbers together and divide by the number of numbers. 6 | (The sum of values divided by the number of values). 7 | 8 | To determine the Median 9 | 10 | Arrange the numbers in order, find the middle number. 11 | (The middle value when the values are ranked). 12 | 13 | To determine the Mode 14 | 15 | Count how many times each value occurs the highest is the mode. 16 | (The most frequently occurring value) 17 | 18 | ``` 19 | const meanMedianMode = new MeanMedianMode([10, 3, 3, 23, 9]) 20 | 21 | expect(meanMedianMode.getMeanMedianMode()).toEqual({ mean: 9.6, median: 9, mode: ['3'] }) 22 | ``` 23 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/meanMedianMode/__tests__/meanMedianMode.test.js: -------------------------------------------------------------------------------- 1 | import MeanMedianMode from '../'; 2 | 3 | describe('meanMedianMode', () => { 4 | it('should behave...', () => { 5 | const meanMedianMode = new MeanMedianMode([9, 10, 23, 10, 23, 9]); 6 | 7 | expect(meanMedianMode.getMeanMedianMode()).toEqual({ 8 | mean: 14, 9 | median: 10, 10 | mode: [], 11 | }); 12 | }); 13 | 14 | it('should behave even now...', () => { 15 | const meanMedianMode = new MeanMedianMode([2, 10, 23, 3, 23, 9]); 16 | 17 | expect(meanMedianMode.getMeanMedianMode()).toEqual({ 18 | mean: 11.666666666666666, 19 | median: 9.5, 20 | mode: ['23'], 21 | }); 22 | }); 23 | 24 | it('should behave even now...and now..', () => { 25 | const meanMedianMode = new MeanMedianMode([10, 3, 3, 23, 9]); 26 | 27 | expect(meanMedianMode.getMeanMedianMode()).toEqual({ 28 | mean: 9.6, 29 | median: 9, 30 | mode: ['3'], 31 | }); 32 | }); 33 | 34 | it('should behave even now...and now..hey! Put some effort with test titles!', () => { 35 | const meanMedianMode = new MeanMedianMode([10, 3, 3, 23, 9, 23, 9]); 36 | 37 | expect(meanMedianMode.getMeanMedianMode()).toEqual({ 38 | mean: 11.428571428571429, 39 | median: 9, 40 | mode: ['3', '9', '23'], 41 | }); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/meanMedianMode/index.js: -------------------------------------------------------------------------------- 1 | class meanMedianMode { 2 | constructor(arr) { 3 | this.arr = arr; 4 | } 5 | 6 | getMean(arr) { 7 | return arr.reduce((acc, num) => acc + num) / arr.length; 8 | } 9 | 10 | getMedian(arr) { 11 | arr.sort((a, b) => a - b); 12 | 13 | let median; 14 | 15 | const isOddLength = arr.length % 2 !== 0; 16 | 17 | if (isOddLength) { 18 | median = arr[Math.floor(arr.length / 2)]; 19 | } else { 20 | const mid1 = arr[arr.length / 2 - 1]; 21 | const mid2 = arr[arr.length / 2]; 22 | median = (mid1 + mid2) / 2; 23 | } 24 | 25 | return median; 26 | } 27 | 28 | getMode(arr) { 29 | const modeObj = arr.reduce((obj, num) => { 30 | if (!obj[num]) obj[num] = 0; 31 | obj[num]++; 32 | 33 | return obj; 34 | }, {}); 35 | 36 | let maxFrequency = 0; 37 | 38 | return Object.keys(modeObj) 39 | .reduce((acc, num) => { 40 | if (modeObj[num] > maxFrequency) { 41 | acc = [num]; 42 | maxFrequency = modeObj[num]; 43 | } else if (modeObj[num] === maxFrequency) { 44 | acc.push(num); 45 | } 46 | return acc; 47 | }, []) 48 | .filter((num, i, arr) => arr.length !== Object.keys(modeObj).length); 49 | } 50 | 51 | getMeanMedianMode() { 52 | return { 53 | mean: this.getMean(this.arr), 54 | median: this.getMedian(this.arr), 55 | mode: this.getMode(this.arr), 56 | }; 57 | } 58 | } 59 | 60 | export default meanMedianMode; 61 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/moveElementToEnd/index.js: -------------------------------------------------------------------------------- 1 | function moveElementToEnd(array, toMove) { 2 | let i = 0; 3 | let j = array.length - 1; 4 | 5 | while (i < j) { 6 | while (i < j && array[j] === toMove) { 7 | j -= 1; 8 | } 9 | 10 | if (array[i] === toMove) { 11 | const tempj = array[j]; 12 | array[j] = array[i]; 13 | array[i] = tempj; 14 | } 15 | 16 | i += 1; 17 | } 18 | 19 | return array; 20 | } 21 | 22 | export default moveElementToEnd; 23 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/moveElementToEnd/index.test.js: -------------------------------------------------------------------------------- 1 | import moveElementToEnd from './'; 2 | 3 | describe('moveElementToEnd', () => { 4 | it('should pass', () => { 5 | expect(moveElementToEnd([2, 1, 2, 2, 2, 3, 4, 2], 2)).toEqual([ 6 | 4, 7 | 1, 8 | 3, 9 | 2, 10 | 2, 11 | 2, 12 | 2, 13 | 2, 14 | ]); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/nextUntil/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ nextUntil 2 | 3 | Gets all sibling elements following an element until you reach an element with a particular selector. 4 | 5 | [Check the code](nextUntil.js) and the [test](__tests__/nextUntil.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/nextUntil/__tests__/nextUntil.test.js: -------------------------------------------------------------------------------- 1 | import NextUntil from '../nextUntil'; 2 | 3 | const redline = [ 4 | { 5 | name: 'paraMarker', 6 | }, 7 | { 8 | name: 'change', 9 | type: 'del', 10 | value: 'foo', 11 | }, 12 | { 13 | name: 'paraMarker', 14 | }, 15 | { 16 | name: 'span', 17 | value: 'The Directors', 18 | }, 19 | { 20 | name: 'paraMarker', 21 | }, 22 | { 23 | name: 'change', 24 | type: 'replace', 25 | value: 'foo', 26 | }, 27 | { 28 | name: 'span', 29 | value: ' Bonds Plc Issuer Plc', 30 | }, 31 | { 32 | name: 'paraMarker', 33 | }, 34 | { 35 | name: 'span', 36 | value: 37 | 'The Lead Manager and the other Managers (as defined in paragraph 2 below)', 38 | }, 39 | { 40 | name: 'paraMarker', 41 | }, 42 | { 43 | name: 'span', 44 | value: '[Date]', 45 | }, 46 | { 47 | name: 'paraMarker', 48 | }, 49 | { 50 | name: 'span', 51 | value: 'Dear Sirs,', 52 | }, 53 | { 54 | name: 'paraMarker', 55 | }, 56 | { 57 | name: 'span', 58 | value: 'PROPOSED ', 59 | }, 60 | { 61 | name: 'change', 62 | type: 'replace', 63 | value: 'bar', 64 | }, 65 | { 66 | name: 'span', 67 | value: ' BONDS PLC ISSUE BY ', 68 | }, 69 | { 70 | name: 'change', 71 | type: 'replace', 72 | value: 'foo', 73 | }, 74 | { 75 | name: 'span', 76 | value: ' BONDS PLC ISSUER PLC (“the Issuer”)', 77 | }, 78 | { 79 | name: 'paraMarker', 80 | }, 81 | ]; 82 | 83 | describe('Get the max stack', () => { 84 | it('return the largest item in the stack', () => { 85 | const nextUntil = new NextUntil(redline); 86 | 87 | expect(nextUntil).toEqual({}); 88 | }); 89 | }); 90 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/nextUntil/nextUntil.js: -------------------------------------------------------------------------------- 1 | class NextUntil { 2 | constructor(array) {} 3 | } 4 | 5 | export default NextUntil; 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/permutations/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shubham56-droid/DataStruture-and-algroithms-program/eb2040408564179c1d73918cde1b52eaace48b31/JavaSript/algorithms_Js/permutations/README.md -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/permutations/index.js: -------------------------------------------------------------------------------- 1 | function getPermutations(array) { 2 | const permutations = []; 3 | permutationsHelper(array, [], permutations); 4 | return permutations; 5 | } 6 | 7 | function permutationsHelper(array, currentPermutation, permutations) { 8 | if (!array.length && currentPermutation.length) { 9 | permutations.push(currentPermutation); 10 | } else { 11 | for (let i = 0; i < array.length; i++) { 12 | const newArray = array.slice(0, i).concat(array.slice(i + 1)); 13 | const newPermutation = currentPermutation.concat([array[i]]); 14 | permutationsHelper(newArray, newPermutation, permutations); 15 | } 16 | } 17 | } 18 | 19 | // console.log(getPermutations([1, 2, 3])) 20 | 21 | export default getPermutations; 22 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/permutations/index.test.js: -------------------------------------------------------------------------------- 1 | import getPermutations from '.'; 2 | 3 | describe('getPermutations', () => { 4 | it('should', () => { 5 | const permutations = getPermutations([1, 2, 3]); 6 | expect(permutations).toEqual([ 7 | [1, 2, 3], 8 | [1, 3, 2], 9 | [2, 1, 3], 10 | [2, 3, 1], 11 | [3, 1, 2], 12 | [3, 2, 1], 13 | ]); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/power/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Response Handler 2 | 3 | Add handlers and implement fallbacks 4 | 5 | [Check the code](responseHandler.js) and the [test](__tests__/responseHandler.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/power/power.js: -------------------------------------------------------------------------------- 1 | const power = (a, b) => { 2 | if (b < 0) { 3 | return 0; 4 | } else if (b === 0) { 5 | return 1; 6 | } else { 7 | const res = a * power(a, b - 1); 8 | 9 | return res; 10 | } 11 | }; 12 | 13 | export default power; 14 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/power/power.test.js: -------------------------------------------------------------------------------- 1 | import power from './power'; 2 | 3 | describe('power', () => { 4 | it('should have 1 handler', () => { 5 | const p = power(2, 4); 6 | expect(p).toEqual(16); 7 | }); 8 | }); 9 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/queueStacks/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Queue Stacks 2 | 3 | Implement a queue with 2 stacks 4 | 5 | [check the code](queueTwoStacks.js) and the [test](__tests__/queueTwoStacks.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/queueStacks/queueTwoStacks.js: -------------------------------------------------------------------------------- 1 | class QueueTwoStacks { 2 | constructor() { 3 | this.inStack = []; 4 | this.outStack = []; 5 | } 6 | 7 | enqueue(item) { 8 | this.inStack.push(item); 9 | } 10 | 11 | dequeue() { 12 | if (this.outStack.length === 0) { 13 | // Move items from inStack to outStack, reversing order 14 | while (this.inStack.length > 0) { 15 | const newestInStackItem = this.inStack.pop(); 16 | this.outStack.push(newestInStackItem); 17 | } 18 | 19 | // If outStack is still empty, raise an error 20 | if (this.outStack.length === 0) { 21 | return undefined; 22 | } 23 | } 24 | return this.outStack.pop(); 25 | } 26 | } 27 | 28 | export default QueueTwoStacks; 29 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/queueStacks/queueTwoStacks.test.js: -------------------------------------------------------------------------------- 1 | import QueueTwoStacks from './queueTwoStacks'; 2 | 3 | describe('Queue with two stacks', () => { 4 | it('should be FIFO, first in first out', () => { 5 | const queue = new QueueTwoStacks(); 6 | 7 | queue.enqueue(2); 8 | queue.enqueue(3); 9 | queue.enqueue(4); 10 | queue.enqueue(5); 11 | 12 | expect(queue.dequeue()).toEqual(2); 13 | }); 14 | 15 | it('should be FIFO, first in first out', () => { 16 | const queue = new QueueTwoStacks(); 17 | 18 | queue.enqueue(2); 19 | 20 | expect(queue.dequeue()).toEqual(2); 21 | 22 | queue.enqueue(3); 23 | queue.enqueue(4); 24 | 25 | queue.dequeue(); 26 | 27 | queue.enqueue(5); 28 | 29 | expect(queue.dequeue()).toEqual(4); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/responseHandler/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Response Handler 2 | 3 | Add handlers and implement fallbacks 4 | 5 | [Check the code](responseHandler.js) and the [test](__tests__/responseHandler.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/responseHandler/responseHandler.js: -------------------------------------------------------------------------------- 1 | class ResponseHandler { 2 | constructor(handlers = []) { 3 | this.handlers = handlers; 4 | } 5 | 6 | add(code, handler) { 7 | this.handlers.push({ 8 | code, 9 | handler, 10 | }); 11 | } 12 | 13 | handle(response) { 14 | const status = response.status; 15 | 16 | let handlers = this.handlers.filter((handle) => handle.code === status); 17 | 18 | if (handlers.length === 0) { 19 | handlers = this.handlers.filter( 20 | (handle) => handle.code === Math.floor(status / 100) * 100 21 | ); 22 | } 23 | 24 | if (handlers.length === 0) { 25 | handlers = this.handlers.filter((handle) => handle.code === 0); 26 | } 27 | 28 | handlers.forEach((handler) => { 29 | handler.handler(response); 30 | }); 31 | } 32 | } 33 | 34 | export default ResponseHandler; 35 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/responseHandler/responseHandler.test.js: -------------------------------------------------------------------------------- 1 | import ResponseHandler from './responseHandler'; 2 | 3 | describe('ResponseHandler', () => { 4 | let responseHandler; 5 | 6 | beforeEach(() => { 7 | responseHandler = new ResponseHandler(); 8 | }); 9 | 10 | it('should have 1 handler', () => { 11 | responseHandler.add('1', null); 12 | expect(responseHandler.handlers).toHaveLength(1); 13 | }); 14 | 15 | it('should handle multiple handlers with same code', () => { 16 | const mockCallback = jest.fn(); 17 | 18 | responseHandler.add(120, mockCallback); 19 | responseHandler.add(120, mockCallback); 20 | 21 | responseHandler.handle({ 22 | status: 120, 23 | }); 24 | 25 | expect(mockCallback.mock.calls.length).toBe(2); 26 | }); 27 | 28 | it('should fallback to series', () => { 29 | const seriesCb = jest.fn(); 30 | 31 | responseHandler.add(400, seriesCb); 32 | 33 | responseHandler.handle({ 34 | status: 404, 35 | }); 36 | 37 | expect(seriesCb.mock.calls.length).toBe(1); 38 | }); 39 | it('should fallback to 0', () => { 40 | const mockCallback = jest.fn(); 41 | 42 | responseHandler.add(0, mockCallback); 43 | responseHandler.add(500, null); 44 | responseHandler.add(301, null); 45 | responseHandler.add(609, null); 46 | 47 | responseHandler.handle({ 48 | status: 404, 49 | }); 50 | 51 | expect(mockCallback.mock.calls.length).toBe(1); 52 | }); 53 | }); 54 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/reverseArrayInPlace/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Reverse Array In Place: 2 | 3 | Be sure to manipulate the passed array, do not return a new one. 4 | 5 | ``` 6 | import reverseArrayInPlace from '../' 7 | 8 | const inputArr = [1, 2, 3, 4, 5, 6, 7, 8] 9 | const outputArr = [8, 7, 6, 5, 4, 3, 2, 1] 10 | 11 | expect(reverseArrayInPlace(inputArr)).toEqual(outputArr) 12 | ``` 13 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/reverseArrayInPlace/__tests__/reverseArrayInPlace.test.js: -------------------------------------------------------------------------------- 1 | import reverseArrayInPlace from '../'; 2 | 3 | describe('reverseArrayInPlace', () => { 4 | it('should behave...', () => { 5 | const inputArr = [1, 2, 3, 4, 5, 6, 7, 8]; 6 | const outputArr = [8, 7, 6, 5, 4, 3, 2, 1]; 7 | 8 | expect(reverseArrayInPlace(inputArr)).toEqual(outputArr); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/reverseArrayInPlace/index.js: -------------------------------------------------------------------------------- 1 | const reverseArrayInPlace = (arr) => { 2 | for (let i = 0; i < arr.length / 2; i++) { 3 | const tempVar = arr[i]; 4 | arr[i] = arr[arr.length - 1 - i]; 5 | arr[arr.length - 1 - i] = tempVar; 6 | } 7 | 8 | return arr; 9 | }; 10 | 11 | export default reverseArrayInPlace; 12 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/reverseWords/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Reverse words 2 | 3 | Reverse the letters in every word ut don't use Array.reverse() 4 | 5 | ``` 6 | import reverseWords from '../' 7 | 8 | expect(reverseWords('I like JavaScript problems')).toEqual('I ekil tpircSavaJ smelborp') 9 | ``` 10 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/reverseWords/__tests__/reverseWords.test.js: -------------------------------------------------------------------------------- 1 | import reverseWords from '../'; 2 | 3 | describe('reverseWords', () => { 4 | it('should behave...', () => { 5 | expect(reverseWords('I like JavaScript problems')).toEqual( 6 | 'I ekil tpircSavaJ smelborp' 7 | ); 8 | }); 9 | }); 10 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/reverseWords/index.js: -------------------------------------------------------------------------------- 1 | const reverseWords = (string) => { 2 | return string 3 | .split(' ') 4 | .map((word) => { 5 | let reversedWord = ''; 6 | for (let i = word.length - 1; i >= 0; i--) { 7 | reversedWord += word[i]; 8 | } 9 | return reversedWord; 10 | }) 11 | .join(' '); 12 | }; 13 | 14 | export default reverseWords; 15 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/romanToNumerals/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Roman to Numerals 2 | 3 | Translate Romans into numerals 4 | 5 | [Check the code](translateromannumerals.js) and the [test](__tests__/translateromannumerals.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/romanToNumerals/translateromannumerals.js: -------------------------------------------------------------------------------- 1 | const translateRomanNumeral = (romanNumeral) => { 2 | const DIGIT_VALUES = { 3 | I: 1, 4 | V: 5, 5 | X: 10, 6 | L: 50, 7 | C: 100, 8 | D: 500, 9 | M: 1000, 10 | }; 11 | 12 | let result = 0; 13 | const input = romanNumeral.split(''); 14 | 15 | for (let i = 0; i < input.length; i++) { 16 | const currentLetter = DIGIT_VALUES[input[i]]; 17 | const nextLetter = DIGIT_VALUES[input[i + 1]]; 18 | if (!currentLetter) { 19 | return 'null'; 20 | } else { 21 | if (currentLetter < nextLetter) { 22 | result += nextLetter - currentLetter; 23 | i++; 24 | } else { 25 | result += currentLetter; 26 | } 27 | } 28 | } 29 | 30 | return result; 31 | }; 32 | 33 | export default translateRomanNumeral; 34 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/romanToNumerals/translateromannumerals.test.js: -------------------------------------------------------------------------------- 1 | import translateRomanNumerals from './translateromannumerals'; 2 | 3 | describe('Translate Roman numbers to numerals', () => { 4 | it('should translate a roman number', () => { 5 | expect(translateRomanNumerals('XI')).toEqual(11); 6 | expect(translateRomanNumerals('IX')).toEqual(9); 7 | expect(translateRomanNumerals('XXX')).toEqual(30); 8 | }); 9 | }); 10 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/sumDigits/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Response Handler 2 | 3 | Add handlers and implement fallbacks 4 | 5 | [Check the code](responseHandler.js) and the [test](__tests__/responseHandler.test.js) 6 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/sumDigits/index.js: -------------------------------------------------------------------------------- 1 | const sumDigits = (n) => { 2 | let sum = 0; 3 | while (n > 0) { 4 | sum += n % 10; 5 | n /= 10; 6 | } 7 | 8 | return parseInt(sum, 10); 9 | }; 10 | 11 | export default sumDigits; 12 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/sumDigits/index.test.js: -------------------------------------------------------------------------------- 1 | import sumDigits from '.'; 2 | 3 | describe('sumDigits', () => { 4 | it('should', () => { 5 | const s = sumDigits(27); 6 | expect(s).toEqual(9); 7 | }); 8 | }); 9 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/twoSum/README.md: -------------------------------------------------------------------------------- 1 | # ⚗ Two Sum: 2 | 3 | Find all the pair of numbers in the passed array that adds up to the passed sum. 4 | 5 | Any number in the array can be used for multiple pairs. 6 | 7 | ``` 8 | expect(twoSum([1, 6, 4, 5, 3, 3], 7)).toEqual([[6, 1], [3, 4], [3, 4]]) 9 | ``` 10 | 11 | Let's also implement it efficiently O(n) or less efficiently O(n^2) 12 | 13 | With 1000 numbers in the passed array 14 | 15 | ⏱ 🚀 Call to twoSum took 0.4094ms. 16 | 17 | ⏱ 🚀 Call to twoSumInefficient took 7.8309ms. 18 | 19 | With 10000 numbers in the passed array: 20 | 21 | ⏱ 🚀 Call to twoSum took 28.5429ms. 22 | 23 | ⏱ 🚀 Call to twoSumInefficient took 732.7597ms. 24 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/twoSum/index.js: -------------------------------------------------------------------------------- 1 | export const twoSum = (arr, sum) => { 2 | let pairs = []; 3 | let hashTable = []; 4 | 5 | for (let i = 0; i < arr.length; i++) { 6 | const currNum = arr[i]; 7 | const counterPart = sum - currNum; 8 | 9 | if (hashTable.indexOf(counterPart) !== -1) { 10 | pairs.push([currNum, counterPart]); 11 | } 12 | 13 | hashTable.push(currNum); 14 | } 15 | 16 | return pairs; 17 | }; 18 | 19 | export const twoSumInefficient = (arr, sum) => { 20 | let pairs = []; 21 | 22 | for (let i = 0; i < arr.length; i++) { 23 | const currNum = arr[i]; 24 | const counterPart = sum - currNum; 25 | 26 | for (let z = i; z < arr.length; z++) { 27 | const scurrNum = arr[z]; 28 | 29 | if (scurrNum === counterPart) { 30 | pairs.push([counterPart, currNum]); 31 | } 32 | } 33 | } 34 | 35 | return pairs; 36 | }; 37 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/twoSum/twoSum.test.js: -------------------------------------------------------------------------------- 1 | import {displayPerfTime} from '../../utils/perf-utils'; 2 | 3 | import {twoSum, twoSumInefficient} from '.'; 4 | 5 | describe('twoSum', () => { 6 | it('should return an array of pairs', () => { 7 | expect(twoSum([25, 1, 6, 4, 5, 3, 3, 79], 7)).toEqual([ 8 | [6, 1], 9 | [3, 4], 10 | [3, 4], 11 | ]); 12 | }); 13 | 14 | it('twoSum', () => { 15 | expect(twoSum([4, 5, 7, 8, 9, 10, 11, 14, 16], 24)).toEqual([ 16 | [14, 10], 17 | [16, 8], 18 | ]); 19 | }); 20 | }); 21 | 22 | describe('twoSum inefficient On^2', () => { 23 | it('should return an array of pairs i', () => { 24 | expect(twoSumInefficient([25, 1, 6, 4, 5, 3, 3, 79], 7)).toEqual([ 25 | [6, 1], 26 | [3, 4], 27 | [3, 4], 28 | ]); 29 | }); 30 | 31 | it('twoSum i', () => { 32 | expect(twoSumInefficient([4, 5, 7, 8, 9, 10, 11, 14, 16], 24)).toEqual([ 33 | [16, 8], 34 | [14, 10], 35 | ]); 36 | }); 37 | }); 38 | 39 | describe('Performance', () => { 40 | const bigArray = [...new Array(1000)].map(() => 41 | Math.floor(Math.random() * 10 + 1) 42 | ); 43 | 44 | it('will display perftime', () => { 45 | displayPerfTime('twoSum', () => { 46 | twoSum(bigArray, 7); 47 | }); 48 | displayPerfTime('twoSumInefficient', () => { 49 | twoSumInefficient(bigArray, 7); 50 | }); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/wordsDictionary/README.md: -------------------------------------------------------------------------------- 1 | ### Design a data structure that supports the following two operations: 2 | 3 | ``` 4 | void addWord(word) 5 | bool search(word) 6 | ``` 7 | 8 | `search(word)` can search a literal word or a regular expression string containing only letters `a-z` or `.`. 9 | 10 | A `.` means it can represent any one letter. 11 | 12 | Example: 13 | 14 | ``` 15 | addWord("bad") 16 | addWord("dad") 17 | addWord("mad") 18 | search("pad") -> false 19 | search("bad") -> true 20 | search(".ad") -> true 21 | search("b..") -> true 22 | ``` 23 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/wordsDictionary/index.js: -------------------------------------------------------------------------------- 1 | class WordDictionary { 2 | constructor() { 3 | this.data = []; 4 | } 5 | addWord(word) { 6 | const words = (this.data[word.length] = 7 | this.data[word.length] || new Set()); 8 | words.add(word); 9 | } 10 | search(input) { 11 | const words = this.data[input.length]; 12 | if (words === undefined) { 13 | return false; 14 | } 15 | 16 | const regex = new RegExp(input); 17 | return !![...words].some((nextWord) => regex.test(nextWord)); 18 | } 19 | } 20 | 21 | export default WordDictionary; 22 | -------------------------------------------------------------------------------- /JavaSript/algorithms_Js/wordsDictionary/index.test.js: -------------------------------------------------------------------------------- 1 | import WordDictionary from '.'; 2 | 3 | describe('WordDictionary', () => { 4 | let wordDictionary = ''; 5 | 6 | beforeEach(() => { 7 | wordDictionary = new WordDictionary(); 8 | wordDictionary.addWord('bad'); 9 | wordDictionary.addWord('dad'); 10 | wordDictionary.addWord('mad'); 11 | }); 12 | 13 | it('should not find "pad"', () => { 14 | expect(wordDictionary.search('pad')).toBeFalsy(); 15 | }); 16 | 17 | it('should find "bad"', () => { 18 | expect(wordDictionary.search('bad')).toBeTruthy(); 19 | }); 20 | 21 | it('should find ".ad"', () => { 22 | expect(wordDictionary.search('.ad')).toBeTruthy(); 23 | }); 24 | 25 | it('should find "b.."', () => { 26 | expect(wordDictionary.search('b..')).toBeTruthy(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /JavaSript/schemeRandomNota.js: -------------------------------------------------------------------------------- 1 | const schemeTransactionNumber = (id) => { 2 | let data = parseInt(id, 10); 3 | 4 | const a = 'abcdefghijklmnopqrstuvwxyz123456789'.toUpperCase().split("") 5 | 6 | let result = '' 7 | 8 | while(true) { 9 | if(data > 35) { 10 | const temp = data % 35; 11 | if(data % 35 === 0) { 12 | result = result.concat(a[34]) 13 | data = parseInt(data/35, 10) - 1 14 | } else { 15 | result = result.concat(a[temp - 1]) 16 | data = parseInt(data/35, 10) 17 | } 18 | } else { 19 | result = result.concat(a[data - 1]) 20 | break; 21 | } 22 | } 23 | 24 | return result.split("").reverse("").join(""); 25 | } 26 | 27 | const createSchemeNumber = (prefix = 'INV', id = '1', suffix = 'DWN') => 28 | `${prefix}/${schemeTransactionNumber(id)}/${suffix}` 29 | 30 | export { createSchemeNumber }; 31 | 32 | //example 33 | console.log(createSchemeNumber()); // => INV/A/DWN 34 | console.log(createSchemeNumber('INV', 100)) // => INV/A/DWN 35 | 36 | //sandbox 37 | //https://codesandbox.io/s/thirsty-liskov-renhi?file=/src/index.js -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Shubham Bawankar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python/Lowest Common Ancestor.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, data, left = None, right = None): 3 | self.data = data 4 | self.left = left 5 | self.right = right 6 | class Solution(): 7 | def lowestCommonAncestor(self, root, p, q): 8 | if not root: 9 | return None 10 | if p == root or q==root: 11 | return root 12 | left = self.lowestCommonAncestor(root.left, p, q) 13 | right = self.lowestCommonAncestor(root.right, p, q) 14 | if left and right: 15 | return root 16 | return left or right 17 | def insert(temp,data): 18 | que = [] 19 | que.append(temp) 20 | while (len(que)): 21 | temp = que[0] 22 | que.pop(0) 23 | if (not temp.left): 24 | temp.left = TreeNode(data) 25 | break 26 | else: 27 | que.append(temp.left) 28 | if (not temp.right): 29 | temp.right = TreeNode(data) 30 | break 31 | else: 32 | que.append(temp.right) 33 | def make_tree(elements): 34 | Tree = TreeNode(elements[0]) 35 | for element in elements[1:]: 36 | insert(Tree, element) 37 | return Tree 38 | def search_node(root, element): 39 | if (root == None): 40 | return None 41 | if (root.data == element): 42 | return root 43 | res1 = search_node(root.left, element) 44 | if res1: 45 | return res1 46 | res2 = search_node(root.right, element) 47 | return res2 48 | 49 | root = make_tree([7,3,7,0,5,7,9,None,None,3,5]) 50 | ob1 = Solution() 51 | op = ob1.lowestCommonAncestor(root, search_node(root, 2), search_node(root, 8)) 52 | print(op.data) 53 | -------------------------------------------------------------------------------- /Python/Path.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Graph: 4 | 5 | def __init__(self,vertices): 6 | self.V= vertices 7 | 8 | 9 | self.graph = defaultdict(list) 10 | 11 | def addEdge(self,u,v): 12 | self.graph[u].append(v) 13 | 14 | def printAllPathsUtil(self, u, d, visited, path): 15 | 16 | visited[u]= True 17 | path.append(u) 18 | 19 | if u ==d: 20 | print path 21 | else: 22 | 23 | for i in self.graph[u]: 24 | if visited[i]==False: 25 | self.printAllPathsUtil(i, d, visited, path) 26 | 27 | path.pop() 28 | visited[u]= False 29 | 30 | def printAllPaths(self,s, d): 31 | 32 | visited =[False]*(self.V) 33 | 34 | path = [] 35 | self.printAllPathsUtil(s, d,visited, path) 36 | 37 | g = Graph(4) 38 | g.addEdge(0, 1) 39 | g.addEdge(0, 2) 40 | g.addEdge(0, 3) 41 | g.addEdge(2, 0) 42 | g.addEdge(2, 1) 43 | g.addEdge(1, 3) 44 | 45 | s = 2 ; d = 3 46 | print ("Paths from node %d to %d : " %(s, d)) 47 | g.printAllPaths(s, d) 48 | -------------------------------------------------------------------------------- /Python/ReversingQueue.py: -------------------------------------------------------------------------------- 1 | from queue import Queue 2 | 3 | def Print(queue): 4 | while (not queue.empty()): 5 | print(queue.queue[0], end = ", ") 6 | queue.get() 7 | 8 | def reverseQueue(queue): 9 | Stack = [] 10 | while (not queue.empty()): 11 | Stack.append(queue.queue[0]) 12 | queue.get() 13 | while (len(Stack) != 0): 14 | queue.put(Stack[-1]) 15 | Stack.pop() 16 | 17 | if __name__ == '__main__': 18 | queue = Queue() 19 | queue.put(10) 20 | queue.put(20) 21 | queue.put(30) 22 | queue.put(40) 23 | queue.put(50) 24 | queue.put(60) 25 | queue.put(70) 26 | queue.put(80) 27 | queue.put(90) 28 | queue.put(100) 29 | 30 | reverseQueue(queue) 31 | Print(queue) -------------------------------------------------------------------------------- /Python/SecondLargestElementBST.py: -------------------------------------------------------------------------------- 1 | class node: 2 | def __init__(self,data): 3 | self.left=None 4 | self.right=None 5 | self.data=data 6 | 7 | #inserting nodes according to BST rule 8 | 9 | def insert(root,node): 10 | if root==None: 11 | root=node 12 | else: 13 | if root.data arr[i+1]: 30 | return False 31 | i += 1 32 | 33 | 34 | return True 35 | while not is_sorted(arr): 36 | random.shuffle(arr) 37 | 38 | if simulation: 39 | iteration = iteration + 1 40 | print("iteration",iteration,":",*arr) 41 | 42 | return arr 43 | 44 | def main(): 45 | array = [1,5,8,0,150,44,4,3,6] #static inputs 46 | result = bogo_sort(array) 47 | print(result) 48 | 49 | if __name__=="__main__": 50 | main() -------------------------------------------------------------------------------- /Python/Sorting/bubble_sort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(list1): 2 | # Outer loop for traverse the entire list 3 | for i in range(0,len(list1)-1): 4 | for j in range(len(list1)-1): 5 | if(list1[j]>list1[j+1]): 6 | temp = list1[j] 7 | list1[j] = list1[j+1] 8 | list1[j+1] = temp 9 | return list1 10 | 11 | list1 = [5, 3, 8, 6, 7, 2] 12 | print("The unsorted list is: ", list1) 13 | print("The sorted list is: ", bubble_sort(list1)) 14 | -------------------------------------------------------------------------------- /Python/Sorting/bucket_sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Bucket Sort 3 | 4 | Bucket sort works as follows: 5 | 6 | 1. Set up an array of initially empty "buckets". 7 | 2. Scatter: Go over the original array, putting each object in its bucket. 8 | 3. Sort each non-empty bucket. 9 | 4. Gather: Visit the buckets in order and put all elements back into the original array. 10 | 11 | https://en.wikipedia.org/wiki/Bucket_sort 12 | 13 | Complexity: O(n^2) 14 | The complexity is dominated by nextSort 15 | ''' 16 | 17 | 18 | def bucket_sort(arr): 19 | 20 | # The number of buckets and make buckets 21 | num_buckets = len(arr) 22 | buckets = [[] for bucket in range(num_buckets)] 23 | 24 | # Assign values into bucket_sort 25 | for value in arr: 26 | index = value * num_buckets // (max(arr) + 1) 27 | buckets[index].append(value) 28 | 29 | # Sort 30 | sorted_list = [] 31 | for i in range(num_buckets): 32 | sorted_list.extend(next_sort(buckets[i])) 33 | return sorted_list 34 | 35 | def next_sort(arr): 36 | # We will use insertion sort here. 37 | for i in range(1, len(arr)): 38 | j = i - 1 39 | key = arr[i] 40 | while arr[j] > key and j >= 0: 41 | arr[j+1] = arr[j] 42 | j = j - 1 43 | arr[j + 1] = key 44 | return arr 45 | 46 | def main(): 47 | array = [1,5,8,0,150,44,4,3,6] #static inputs 48 | result = bucket_sort(array) 49 | print(result) 50 | 51 | if __name__=="__main__": 52 | main() -------------------------------------------------------------------------------- /Python/Sorting/merge_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Merge Sort 4 | 5 | https://en.wikipedia.org/wiki/Merge_sort 6 | 7 | Complexity: O(n log(n)) 8 | 9 | """ 10 | 11 | def merge_sort(arr): 12 | 13 | # Our recursive base case 14 | if len(arr) <= 1: 15 | return arr 16 | mid = len(arr) // 2 17 | # Perform merge_sort recursively on both halves 18 | left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:]) 19 | 20 | # Merge each side together 21 | return merge(left, right, arr.copy()) 22 | 23 | 24 | def merge(left, right, merged): 25 | """ Merge helper 26 | Complexity: O(n) 27 | """ 28 | 29 | left_cursor, right_cursor = 0, 0 30 | 31 | while left_cursor < len(left) and right_cursor < len(right): 32 | 33 | # Sort each one and place into the result 34 | if left[left_cursor] <= right[right_cursor]: 35 | merged[left_cursor+right_cursor]=left[left_cursor] 36 | left_cursor += 1 37 | else: 38 | merged[left_cursor + right_cursor] = right[right_cursor] 39 | right_cursor += 1 40 | 41 | # Add the left overs if there's any left to the result 42 | for left_cursor in range(left_cursor, len(left)): 43 | merged[left_cursor + right_cursor] = left[left_cursor] 44 | 45 | # Add the left overs if there's any left to the result 46 | for right_cursor in range(right_cursor, len(right)): 47 | merged[left_cursor + right_cursor] = right[right_cursor] 48 | 49 | # Return result 50 | return merged 51 | 52 | def main(): 53 | array = [1,5,8,0,150,44,4,3,6] #static inputs 54 | result =merge_sort(array) 55 | print(result) 56 | 57 | if __name__=="__main__": 58 | main() 59 | -------------------------------------------------------------------------------- /Python/Sorting/pegionhole_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pigeon Hole Sort 3 | 4 | https://en.wikipedia.org/wiki/Pigeonhole_sort 5 | 6 | Time complexity: O(n + Range) 7 | where n = number of elements and Range = possible values in the array 8 | 9 | Suitable for lists where the number of elements and key values are mostly the same. 10 | 11 | """ 12 | 13 | 14 | def pigeonhole_sort(arr): 15 | Max = max(arr) 16 | Min = min(arr) 17 | size = Max - Min + 1 18 | 19 | holes = [0]*size 20 | 21 | for i in arr: 22 | holes[i-Min] += 1 23 | 24 | i = 0 25 | for count in range(size): 26 | while holes[count] > 0: 27 | holes[count] -= 1 28 | arr[i] = count + Min 29 | i += 1 30 | return arr 31 | 32 | def main(): 33 | array = [1,5,8,0,-9,150,44,4,3,6] #static inputs 34 | result = pigeonhole_sort(array) 35 | print(result) 36 | 37 | if __name__=="__main__": 38 | main() -------------------------------------------------------------------------------- /Python/Sorting/quick_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quick Sort 3 | 4 | https://en.wikipedia.org/wiki/Quick_sort 5 | 6 | Complexity: best O(n log(n)) 7 | avg O(n log(n)) 8 | worst O(N^2) 9 | 10 | If you call quick_sort(arr,True), you can see the process of the sort 11 | 12 | Default is simulation = False 13 | 14 | """ 15 | 16 | def quick_sort(arr, simulation=False): 17 | 18 | iteration = 0 19 | if simulation: 20 | print("iteration",iteration,":",*arr) 21 | arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation) 22 | return arr 23 | 24 | def quick_sort_recur(arr, first, last, iteration, simulation): 25 | if first < last: 26 | pos = partition(arr, first, last) 27 | # Start our two recursive calls 28 | if simulation: 29 | iteration = iteration + 1 30 | print("iteration",iteration,":",*arr) 31 | 32 | _, iteration = quick_sort_recur(arr, first, pos - 1, iteration, simulation) 33 | _, iteration = quick_sort_recur(arr, pos + 1, last, iteration, simulation) 34 | 35 | return arr, iteration 36 | 37 | def partition(arr, first, last): 38 | wall = first 39 | for pos in range(first, last): 40 | if arr[pos] < arr[last]: # last is the pivot 41 | arr[pos], arr[wall] = arr[wall], arr[pos] 42 | wall += 1 43 | arr[wall], arr[last] = arr[last], arr[wall] 44 | return wall 45 | 46 | def main(): 47 | array = [1,5,8,0,-7,150,44,4,3,6] #static inputs 48 | result = quick_sort(array) 49 | print(result) 50 | 51 | if __name__=="__main__": 52 | main() -------------------------------------------------------------------------------- /Python/Sorting/selection_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | Selection Sort 3 | 4 | https://en.wikipedia.org/wiki/Selection_sort 5 | 6 | Worst-case performance: O(N^2) 7 | 8 | If you call selection_sort(arr,True), you can see the process of the sort 9 | 10 | Default is simulation = False 11 | 12 | """ 13 | 14 | def selection_sort(arr, simulation=False): 15 | 16 | iteration = 0 17 | if simulation: 18 | print("iteration",iteration,":",*arr) 19 | 20 | for i in range(len(arr)): 21 | minimum = i 22 | 23 | for j in range(i + 1, len(arr)): 24 | # "Select" the correct value 25 | if arr[j] < arr[minimum]: 26 | minimum = j 27 | 28 | arr[minimum], arr[i] = arr[i], arr[minimum] 29 | 30 | if simulation: 31 | iteration = iteration + 1 32 | print("iteration",iteration,":",*arr) 33 | 34 | return arr 35 | 36 | def main(): 37 | array = [1,5,8,5,150,44,4,3,6] #static inputs 38 | result = selection_sort(array) 39 | print(result) 40 | 41 | if __name__=="__main__": 42 | main() 43 | -------------------------------------------------------------------------------- /Python/SortingQueueWithExtraSpace.py: -------------------------------------------------------------------------------- 1 | # Python3 program to implement sorting a 2 | # queue data structure 3 | from queue import Queue 4 | def minIndex(q, sortedIndex): 5 | min_index = -1 6 | min_val = 999999999999 7 | n = q.qsize() 8 | for i in range(n): 9 | curr = q.queue[0] 10 | q.get() 11 | 12 | if (curr <= min_val and i <= sortedIndex): 13 | min_index = i 14 | min_val = curr 15 | q.put(curr) 16 | 17 | return min_index 18 | 19 | def insertMinToRear(q, min_index): 20 | min_val = None 21 | n = q.qsize() 22 | for i in range(n): 23 | curr = q.queue[0] 24 | q.get() 25 | if (i != min_index): 26 | q.put(curr) 27 | else: 28 | min_val = curr 29 | q.put(min_val) 30 | 31 | def sortQueue(q): 32 | for i in range(1, q.qsize() + 1): 33 | min_index = minIndex(q, q.qsize() - i) 34 | insertMinToRear(q, min_index) 35 | 36 | 37 | q = Queue() 38 | q.put(30) 39 | q.put(11) 40 | q.put(15) 41 | q.put(4) 42 | 43 | sortQueue(q) 44 | while (q.empty() == False): 45 | print(q.queue[0], end = " ") 46 | q.get() 47 | 48 | 49 | -------------------------------------------------------------------------------- /Python/TernarySearch.py: -------------------------------------------------------------------------------- 1 | import math as mt 2 | 3 | def ternarySearch(l, r, key, ar): 4 | 5 | if (r >= l): 6 | 7 | mid1 = l + (r - l) //3 8 | mid2 = r - (r - l) //3 9 | if (ar[mid1] == key): 10 | return mid1 11 | 12 | if (ar[mid2] == key): 13 | return mid2 14 | 15 | if (key < ar[mid1]): 16 | return ternarySearch(l, mid1 - 1, key, ar) 17 | 18 | elif (key > ar[mid2]): 19 | return ternarySearch(mid2 + 1, r, key, ar) 20 | 21 | else: 22 | return ternarySearch(mid1 + 1, 23 | mid2 - 1, key, ar) 24 | 25 | return -1 26 | l, r, p = 0, 9, 5 27 | ar = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 28 | l = 0 29 | r = 9 30 | key = 5 31 | p = ternarySearch(l, r, key, ar) 32 | print("Index of", key, "is", p) 33 | key = 50 34 | p = ternarySearch(l, r, key, ar) 35 | print("Index of", key, "is", p) -------------------------------------------------------------------------------- /Python/averageOddAndEven.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | odd,even,oddcount,evencount = 0,0,0,0 4 | for x in range(1,11): 5 | text = "Enter number {}: ".format(x) 6 | n = int(input(text)) 7 | if n%2 == 0: 8 | even+=n 9 | evencount+=1 10 | else: 11 | odd+=n 12 | oddcount+=1 13 | print("Average of odd numbers =",odd,"/",oddcount,"=",(odd/oddcount)) 14 | print("Average of even numbers =",even,"/",evencount,"=",(even/evencount)) 15 | 16 | -------------------------------------------------------------------------------- /Python/check_if_each_internal_node_of_BST_has_exactly_one_child.py: -------------------------------------------------------------------------------- 1 | def hasOnlyOneChild(pre,size): 2 | min=0; max=0 3 | if pre[size-1] > pre[size-2] : 4 | max = pre[size-1] 5 | min = pre[size-2] 6 | else : 7 | max = pre[size-2] 8 | min = pre[size-1] 9 | for i in range(size-3, 0, -1): 10 | if pre[i] < min: 11 | min = pre[i] 12 | elif pre[i] > max: 13 | max = pre[i] 14 | else: 15 | return False 16 | return True 17 | 18 | # Main 19 | if __name__ == "__main__": 20 | pre = [8, 3, 5, 7, 6] 21 | size = len(pre) 22 | if (hasOnlyOneChild(pre, size)): 23 | print("Yes") 24 | else: 25 | print("No") 26 | -------------------------------------------------------------------------------- /Python/count_tree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Program to count number of trees in a forest. 3 | 4 | Approach: 5 | 6 | The idea is to apply Depth First Search on every node. 7 | If every connected node is visited from one source then increment count by one. 8 | If some nodes yet not visited again perform DFS traversal. 9 | Return the count. 10 | 11 | Example: 12 | Input : edges[] = {0, 1}, {0, 2}, {3, 4} 13 | Output : 2 14 | Explanation : There are 2 trees 15 | 0 3 16 | / \ \ 17 | 1 2 4 18 | 19 | Input : edges[] = {0, 1}, {0, 2}, {3, 4}, {5, 6} 20 | Output : 3 21 | Explanation : There are 3 trees 22 | 0 3 5 23 | / \ \ \ 24 | 1 2 4 6 25 | 26 | ''' 27 | 28 | def Insert_Edge(Graph, u, v): 29 | Graph[u].append(v) 30 | Graph[v].append(u) 31 | 32 | def Depth_First_Search_Traversal(u, Graph, Check_visited): 33 | Check_visited[u] = True 34 | for i in range(len(Graph[u])): 35 | if (Check_visited[Graph[u][i]] == False): 36 | Depth_First_Search_Traversal(Graph[u][i], Graph, Check_visited) 37 | 38 | def Count_Tree(Graph, V): 39 | Check_visited = [False] * V 40 | res = 0 41 | for u in range(V): 42 | if (Check_visited[u] == False): 43 | Depth_First_Search_Traversal(u, Graph, Check_visited) 44 | res += 1 45 | return res 46 | 47 | # Driver code 48 | if __name__ == '__main__': 49 | 50 | V = 7 51 | Graph = [[] for i in range(V)] 52 | Insert_Edge(Graph, 0, 1) 53 | Insert_Edge(Graph, 0, 2) 54 | Insert_Edge(Graph, 3, 4) 55 | Insert_Edge(Graph, 5, 6) 56 | print(Count_Tree(Graph, V)) -------------------------------------------------------------------------------- /Python/majorityElement.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | import math 3 | 4 | class Solution: 5 | def majorityElement(self, A): 6 | frequency = Counter(A) 7 | size = len(A) 8 | for (key, value) in frequency.items(): 9 | if (value > math.floor(size/2)): 10 | return key 11 | 12 | fun = Solution() 13 | A = [2, 2, 1] 14 | print(fun.majorityElement(A)) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Python/minimum_value_node_in_bst.py: -------------------------------------------------------------------------------- 1 | # A binary tree node 2 | class Node: 3 | def __init__(self, key): 4 | self.data = key 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | def insert(node, data): 10 | 11 | # 1. If the tree is empty, return a new, 12 | # single node 13 | if node is None: 14 | return (Node(data)) 15 | 16 | else: 17 | # 2. Otherwise, recur down the tree 18 | if data <= node.data: 19 | node.left = insert(node.left, data) 20 | else: 21 | node.right = insert(node.right, data) 22 | 23 | # Return the (unchanged) node pointer 24 | return node 25 | 26 | 27 | def minValue(node): 28 | current = node 29 | 30 | # loop down to find the lefmost leaf 31 | while(current.left is not None): 32 | current = current.left 33 | 34 | return current.data 35 | 36 | 37 | root = None 38 | root = insert(root, 4) 39 | insert(root, 2) 40 | insert(root, 1) 41 | insert(root, 3) 42 | insert(root, 6) 43 | insert(root, 5) 44 | 45 | print("Minimum value in BST is", minValue(root)) 46 | -------------------------------------------------------------------------------- /Python/segregate_even_and_odd.py: -------------------------------------------------------------------------------- 1 | # Python program to segregate even and odd elements of array 2 | 3 | def segregateEvenOdd(arr): 4 | 5 | # Initialize left and right indexes 6 | left,right = 0,len(arr)-1 7 | 8 | while left < right: 9 | 10 | # Increment left index while we see 0 at left 11 | while (arr[left]%2==0 and left < right): 12 | left += 1 13 | 14 | # Decrement right index while we see 1 at right 15 | while (arr[right]%2 == 1 and left < right): 16 | right -= 1 17 | 18 | if (left < right): 19 | # Swap arr[left] and arr[right]*/ 20 | arr[left],arr[right] = arr[right],arr[left] 21 | left += 1 22 | right = right-1 23 | 24 | 25 | # Driver function to test above function 26 | arr = [12, 34, 45, 9, 8, 90, 3] 27 | segregateEvenOdd(arr) 28 | print ("Array after segregation "), 29 | for i in range(0,len(arr)): 30 | print arr[i], 31 | # This code is contributed by Devesh Agrawal 32 | -------------------------------------------------------------------------------- /Python/stockSpan.py: -------------------------------------------------------------------------------- 1 | def stockSpan(price, n, sol): 2 | sol[0] = 1 3 | for i in range(1, n): 4 | sol[i] = 1 5 | j = i - 1 6 | while (j >= 0) and (price[i] >= price[j]): 7 | sol[i] += 1 8 | j -= 1 9 | 10 | 11 | def printArray(arr, n): 12 | for i in range(n): 13 | print(arr[i], end=" ") 14 | print("") 15 | 16 | 17 | price = [10, 4, 5, 90, 120, 80, 85] 18 | 19 | 20 | def main(price): 21 | n = len(price) 22 | S = [None] * n 23 | stockSpan(price, n, S) 24 | printArray(S, n) 25 | 26 | 27 | main(price) 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DataStruture-and-algroithms-program 2 | This repository has DSA questions for practice 3 | -------------------------------------------------------------------------------- /images/logo-hacktoberfest-full.f42e3b1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shubham56-droid/DataStruture-and-algroithms-program/eb2040408564179c1d73918cde1b52eaace48b31/images/logo-hacktoberfest-full.f42e3b1.jpg -------------------------------------------------------------------------------- /topological_sorting.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print topological sorting of a DAG 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Graph { 9 | int V; 10 | 11 | list* adj; 12 | 13 | void topologicalSortUtil(int v, bool visited[], 14 | stack& Stack); 15 | 16 | public: 17 | Graph(int V); 18 | 19 | void addEdge(int v, int w); 20 | 21 | void topologicalSort(); 22 | }; 23 | 24 | Graph::Graph(int V) 25 | { 26 | this->V = V; 27 | adj = new list[V]; 28 | } 29 | 30 | void Graph::addEdge(int v, int w) 31 | { 32 | adj[v].push_back(w); 33 | } 34 | 35 | void Graph::topologicalSortUtil(int v, bool visited[], 36 | stack& Stack) 37 | { 38 | visited[v] = true; 39 | 40 | list::iterator i; 41 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 42 | if (!visited[*i]) 43 | topologicalSortUtil(*i, visited, Stack); 44 | 45 | Stack.push(v); 46 | } 47 | 48 | void Graph::topologicalSort() 49 | { 50 | stack Stack; 51 | 52 | bool* visited = new bool[V]; 53 | for (int i = 0; i < V; i++) 54 | visited[i] = false; 55 | 56 | for (int i = 0; i < V; i++) 57 | if (visited[i] == false) 58 | topologicalSortUtil(i, visited, Stack); 59 | 60 | while (Stack.empty() == false) { 61 | cout << Stack.top() << " "; 62 | Stack.pop(); 63 | } 64 | } 65 | 66 | int main() 67 | { 68 | Graph g(6); 69 | g.addEdge(5, 2); 70 | g.addEdge(5, 0); 71 | g.addEdge(4, 0); 72 | g.addEdge(4, 1); 73 | g.addEdge(2, 3); 74 | g.addEdge(3, 1); 75 | 76 | cout << "Following is a Topological Sort of the given " 77 | "graph \n"; 78 | 79 | g.topologicalSort(); 80 | 81 | return 0; 82 | } 83 | --------------------------------------------------------------------------------