├── C++ ├── 1-Sparse Matrix │ └── Sparse Matrix(Array Implementation).cpp ├── 10-Searching │ ├── 1-Linear Search │ │ └── 1-Linear Search.cpp │ └── 2-Binary Search │ │ └── 2-Binary Search.cpp ├── 11-Sorting Algorithms │ ├── 1-Selection Sort.cpp │ ├── 10-Tree Sort.cpp │ ├── 11-binary_insertion_sort.cpp │ ├── 2-Bubble Sort.cpp │ ├── 3-Insertion Sort.cpp │ ├── 4-Shell Sort.cpp │ ├── 5-Count Sort.cpp │ ├── 6-Radix Sort.cpp │ ├── 7-Merge Sort.cpp │ ├── 8-Quick Sort.cpp │ └── 9-Heap Sort.cpp ├── 12. Labs & Tasks │ ├── .DS_Store │ ├── Lab1 │ │ ├── DSA lab1 task1.cpp │ │ └── DSA lab1 task2.cpp │ ├── Lab2 │ │ ├── DSA lab2 task1.cpp │ │ └── DSA lab2 task2(imp).cpp │ ├── Lab3 │ │ └── sorting.cpp │ ├── Lab4 │ │ └── dsa lab4.cpp │ ├── Task (13-06-19) │ │ └── Task (13-06-19).cpp │ ├── Task(08-05-19) │ │ └── task 8-may-19.cpp │ ├── Task(10-05-19) │ │ └── Task DSA(10-05-19)(important).cpp │ ├── Task(18-05-19) │ │ └── DSA Task (18-05-19).cpp │ ├── Task(27-04-19) │ │ └── DSA task(27-04-19).cpp │ ├── Task(27-06-19) │ │ └── BST(LinkedList Implementation).cpp │ ├── Tasks(03-05-19) │ │ └── DSA lab 03-05-19.cpp │ ├── Tasks(11-07-19) │ │ └── T1_DSA_199_Lab(11-07-19).cpp │ └── Tasks(17-05-19) │ │ └── DSA task 17-05-19.cpp ├── 13-Bit Manipulation │ ├── 1-counting_the_number_of_setbits.cpp │ ├── 10-Monk_and_the_box_of_cookies(Hackerearth).cpp │ ├── 11-Power_of_two.cpp │ ├── 12-Sanasa _ XOR(HackerRank) │ ├── 12-Sanasa _ XOR(HackerRank).cpp │ ├── 13-Total_sum_of_all_pair.cpp │ ├── 14-xor_of_array_elements.cpp │ ├── 2-check_ith_bit_is_set_or_not.cpp │ ├── 3-bitwise_left_shift.cpp │ ├── 4-bitwise_right_shift.cpp │ ├── 5-countig_bits(leetcode).cpp │ ├── 6-is_power_of_2.cpp │ ├── 7-All_pair_sum_Xor.cpp │ ├── 8-K_th_bit_set_or_not.cpp │ └── 9-minimum_flips_to_make_A_OR_B_equal_C.cpp ├── 2-Singly Linked List │ ├── 1-Singly Linked List code.cpp │ ├── 2-Reversing a singly linked list(important).cpp │ ├── 3-Singly Linked List All Methods.cpp │ ├── 4-A1_T4_DSA_199(edited by sir noman).cpp │ ├── 5-DSA PP-14 Q-3 Exchange Nodes Method.cpp │ └── 6-Removing Duplicates.cpp ├── 3-Doubly Linked List │ ├── 1-Doubly Linked List.cpp │ └── 2-Doubly Linked List all Methods in one file.cpp ├── 4-Circular singly linked list │ └── 1-Circular Linked List.cpp ├── 5-Stack │ ├── .DS_Store │ ├── 1-Stack(Array Implementation) │ │ └── 1-Stack(Array Implementation).cpp │ ├── 2-Stack(LinkedList Implementation) │ │ └── 2-Stack(LinkedList Implementation).cpp │ └── 3-Imp Problem(Interview) │ │ ├── 3-Task DSA(10-05-19)(important).cpp │ │ └── parenthesesCheck.cpp ├── 6-Recursion │ ├── 1-sum of first n positive numbers.cpp │ ├── 2-sum of squares of n numbers.cpp │ ├── 3-recursion that returns power.cpp │ ├── 4-Factorial of a number.cpp │ ├── 5-Maximum in array using recursion.cpp │ ├── Recursion Practice Exercises.pdf │ └── Recursion Practice exercise.txt ├── 7-Queue │ ├── 1-Circular Queue(Array Implementation).cpp │ ├── 2-Queue(LinkedList Implementation).cpp │ └── 3-Double Ended Queue(Linked L Representation).cpp ├── 8-BST(Binary Search tree) │ ├── .DS_Store │ ├── 0-BST Methods │ │ └── BST all( Methods).cpp │ ├── 1-BST(insertion & traversals) │ │ └── 1-BST(Insertion & Traversals).cpp │ ├── 14-FullBinaryTree.cpp │ ├── 2-BST(searching) │ │ └── 2-BST(searching).cpp │ ├── 3-BST(Find max & min) │ │ ├── 1-BST(Find min and max) iteratively.cpp │ │ └── 2-BST(Find min and max) recursively.cpp │ ├── 4-BST(find height) │ │ └── 4-BST(find height).cpp │ ├── 5-Level Order(BFS) using QUEUE │ │ └── 5-Level Order Traversal(using QUEUE).cpp │ ├── 6-Delete Node from BST │ │ └── 6-delete a node from bst.cpp │ ├── 7-Check tree is BST or Not │ │ └── 7-Check Tree is BST or Not.cpp │ └── 8-InOrder successor of a Node in BST │ │ └── 8-InOrder Successor in BST.cpp ├── 9-Heaps │ ├── Array is Min heap or not.cpp │ ├── DSA PP-12 Q-4 Max heap or not.cpp │ ├── Max Heap.cpp │ └── Min Heap(Array Representation).cpp ├── Binary Tree │ ├── Burn_Binary_Tree.cpp │ ├── Children Sum property.cpp │ ├── DiameterBinaryTree.cpp │ ├── Height of a Binary Tree.cpp │ ├── Inorder.cpp │ ├── LeftView.cpp │ ├── Lowest Common Ancestor.cpp │ ├── Postorder.cpp │ ├── Preorder.cpp │ └── RightView.cpp ├── Graphs │ └── Adjencency_List_Implementation │ │ ├── BFS │ │ └── Itteration.cpp │ │ ├── BasicStructure.cpp │ │ └── DFS │ │ └── Itteration.cpp ├── Red-Black-Tree │ ├── Implementation.cpp │ └── Theoretical-Background.md └── SlidingWindow │ ├── 239. Sliding Window Maximum │ ├── 3. Longest Substring Without Repeating Characters │ ├── 632. Smallest Range Covering Elements from K Lists.cpp │ └── Nice_subarrays.cpp ├── CONTRIBUTING.md ├── Java ├── Binary Search Tree │ └── BinarySearchTree.java ├── Circular Linked List │ └── CircularLinkedList.java ├── Doubly Linked List │ └── DoublyLinkedList.java ├── Programs and Task │ ├── PyramidPattern.java │ └── UnexpectedDemand.java ├── Queue │ ├── .DS_Store │ └── Queue.java ├── Recursion │ ├── Factorial.java │ ├── Power.java │ ├── SumOfPositiveNumber.java │ └── SumOfSquareOfPositiveNumbers.java ├── Searching │ ├── BinarySearch.java │ ├── LinearSearch.java │ └── TernarySearch.java ├── Singly Linked List │ └── SinglyLinkedList.java ├── Sorting Algorithm │ ├── BubbleSort.java │ ├── CountingSort.java │ ├── HeapSort.java │ ├── InsertionSort.java │ ├── MergeSortAlgo.java │ ├── QuickSort.java │ ├── SelectionSort.java │ ├── TreeSort.java │ └── shellsort.java ├── Sparse Matrix │ └── SparseMatrix.java └── Stack │ └── Stack.java ├── LEARN.md ├── LICENSE ├── Python ├── Heaps │ ├── max_heap_usingOOP.py │ └── min_heap_usingOOP.py ├── LinkedList │ └── LinkedList.py ├── Queue │ ├── priority_queue.py │ └── queue_using_stack.py ├── Sorting │ ├── BubbleSort.py │ ├── InsertionSort.py │ ├── QuickSort.py │ ├── Selection_sort.py │ └── ShellSort.py ├── Sorting_visualization │ └── Sort_vi.py └── Stack │ └── StackImplementationList.py └── README.md /C++/10-Searching/1-Linear Search/1-Linear Search.cpp: -------------------------------------------------------------------------------- 1 | // Linear Search 2 | // Average number of comparisons will be (n+1)/2 3 | // the worst case efficiency of this algorithm is O(n) 4 | 5 | #include 6 | using namespace std; 7 | 8 | void seqSearch(int A[], int size, int key); 9 | int main() { 10 | int size; 11 | cout << "Enter size of Array:"; 12 | cin >> size; 13 | 14 | int *A = new int[size]; 15 | 16 | cout << "Enter values in Array:" << endl; 17 | for (int i = 0; i < size; i++) { 18 | cin >> A[i]; 19 | } 20 | int key; 21 | cout << "Enter Number to find:"; 22 | cin >> key; 23 | 24 | seqSearch(A, size, key); 25 | 26 | delete[] A; 27 | 28 | system("pause"); 29 | return 0; 30 | } 31 | 32 | void seqSearch(int A[], int size, int key) { 33 | bool flag = 1; 34 | for (int i = 0; i < size; i++) { 35 | if (A[i] == key) { 36 | flag = 0; 37 | cout << "search successfull" << endl; 38 | } 39 | } 40 | if (flag == 1) 41 | cout << "Search Unsuccessful" << endl; 42 | } -------------------------------------------------------------------------------- /C++/10-Searching/2-Binary Search/2-Binary Search.cpp: -------------------------------------------------------------------------------- 1 | // Binary Search 2 | // It works only on sorted Array 3 | // Time Complexity : O(log base 2 n) 4 | 5 | #include 6 | using namespace std; 7 | 8 | void binSearch(int A[], int size, int key); 9 | void sortArray(int A[], int size); 10 | 11 | int main() { 12 | int size; 13 | cout << "Enter Size of Array:"; 14 | cin >> size; 15 | 16 | int *A = new int[size]; 17 | cout << "Enter values in Array:" << endl; 18 | for (int i = 0; i < size; i++) 19 | cin >> A[i]; 20 | 21 | sortArray(A, size); 22 | cout << "Sorted Array is:" << endl; 23 | for (int i = 0; i < size; i++) 24 | cout << A[i]<<" "; 25 | 26 | int key; 27 | cout << "\nEnter value to find:"; 28 | cin >> key; 29 | 30 | binSearch(A, size, key); 31 | 32 | delete [] A; 33 | 34 | system("pause"); 35 | return 0; 36 | } 37 | void sortArray(int A[], int size){ 38 | int temp; 39 | for (int i = 0; i < size; i++) { 40 | for (int j = 0; j < size - 1; j++) { 41 | if (A[j] > A[j + 1]) { 42 | temp = A[j]; 43 | A[j]= A[j + 1] ; 44 | 45 | A[j + 1] = temp; 46 | } 47 | } 48 | } 49 | } 50 | 51 | 52 | void binSearch(int A[], int size, int key) { 53 | //here l=lower bound, u=upper bound , m=middle 54 | 55 | int l = 0; 56 | int u = size - 1; 57 | int m; 58 | while (l <= u) { 59 | m = (l + u) / 2; 60 | if (key == A[m]) { 61 | cout << "Search Successful \nValue found at index " << m << endl; 62 | return; 63 | } 64 | else if (key > A[m]) 65 | l = m + 1; 66 | else 67 | u = m - 1; 68 | } 69 | 70 | cout << "Search Unsucsessful \nValue not found" << endl; 71 | } 72 | -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/1-Selection Sort.cpp: -------------------------------------------------------------------------------- 1 | //Selection Sort. 2 | //Time Complexity: O(n^2) 3 | //Space Complexity: O(1) auxiliary 4 | // Stable-> no 5 | // inPlace-> Yes 6 | 7 | #include 8 | using namespace std; 9 | 10 | void SelectionSort(int A[], int size); 11 | int Min(int A[], int size, int start); 12 | 13 | int main() { 14 | int size; 15 | cout << "Enter size of Array:"; 16 | cin >> size; 17 | 18 | int *A = new int[size]; 19 | 20 | cout << "Enter values in array:" << endl; 21 | for (int i = 0; i < size; i++) 22 | cin >> A[i]; 23 | 24 | cout << "Original values in Array :"; 25 | for (int i = 0; i < size; i++) 26 | cout << A[i] << " "; 27 | cout << "\n\n"; 28 | SelectionSort(A, size); 29 | 30 | cout << "Sorted Array is:"; 31 | for (int i = 0; i < size; i++) 32 | cout << A[i] << " "; 33 | cout << endl; 34 | delete[] A; 35 | 36 | system("pause"); 37 | return 0; 38 | } 39 | 40 | //function of selection sort 41 | void SelectionSort(int A[], int size) { 42 | //here loc is the variable having index of minimum value 43 | int loc, temp; 44 | 45 | for (int i = 0; i <= size - 2; i++) { 46 | //firstly, it finds the index of minimum value and the swap it with the value at A[i] 47 | loc = Min(A, size, i); 48 | //swapping 49 | temp = A[i]; 50 | A[i] = A[loc]; 51 | A[loc] = temp; 52 | } 53 | } 54 | 55 | //function that finds the index of minimum value in an array. 56 | int Min(int A[], int size, int start) { 57 | //here start is the starting index. 58 | int min,loc; 59 | 60 | min = A[start]; 61 | loc = start; 62 | 63 | for (int i = start+1; i <= size - 1; i++) { 64 | if (min > A[i]) { 65 | min = A[i]; 66 | loc = i; 67 | } 68 | } 69 | //we return the index of minimum value. 70 | return (loc); 71 | } -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/10-Tree Sort.cpp: -------------------------------------------------------------------------------- 1 | //Tree Sort 2 | //Time Complexity: O(n^2) | Average case: O(nlogn) 3 | //Space Complexity: O(n) Auxiliary 4 | //Stable: Yes 5 | //In-Place: Not 6 | 7 | #include 8 | using namespace std; 9 | 10 | class Node { 11 | public: 12 | //data will have the value that the node has 13 | int data; 14 | //left child stores the address of left child 15 | Node *leftChild; 16 | //right child stores the address of right child 17 | Node *rightChild; 18 | 19 | //Paremeterized constructor which initialize all the data members of class Node to 0 and NULL. 20 | Node(int d = 0, Node *left = NULL, Node *right = NULL) { 21 | data = d; 22 | leftChild = left; 23 | rightChild = right; 24 | } 25 | }; 26 | 27 | class BST { 28 | public: 29 | 30 | //the definitions of all these functions is outside the class. 31 | Node* insert(Node *root, int d); 32 | void storeSorted(Node *root, int A[], int &i); 33 | void treeSort(int A[], int n); 34 | void print(int A[],int size); 35 | }; 36 | 37 | //insert function is used to insert a new node in a tree. 38 | Node* BST::insert(Node *root, int d) { 39 | 40 | if (root == NULL) { 41 | Node *tempNode = new Node(d); 42 | return tempNode; 43 | } 44 | if (d <= root->data) { 45 | root->leftChild = insert(root->leftChild, d); 46 | } 47 | else if (d > root->data) { 48 | root->rightChild = insert(root->rightChild, d); 49 | } 50 | 51 | return root; 52 | } 53 | 54 | //Function to store inOrder traversal of BST in array. 55 | void BST::storeSorted(Node *root, int A[], int &i) { 56 | 57 | if (root != NULL) { 58 | //here we use recursion 59 | storeSorted(root->leftChild, A, i); 60 | A[i++] = root->data; 61 | storeSorted(root->rightChild, A, i); 62 | } 63 | } 64 | //Function for tree sort 65 | void BST::treeSort(int A[], int n) { 66 | Node *root = NULL; 67 | //first node will be inserted at root 68 | root = insert(root, A[0]); 69 | for (int i = 1; i < n; i++) { 70 | insert(root, A[i]); 71 | } 72 | 73 | int i = 0; 74 | storeSorted(root, A, i); 75 | } 76 | void BST::print(int A[],int size) { 77 | cout << "Sorted Array is: "; 78 | for (int i = 0; i < size; i++) 79 | cout << A[i] << " "; 80 | cout << endl; 81 | } 82 | 83 | int main() { 84 | int size; 85 | cout << "How many values you wanna enter:"; 86 | cin >> size; 87 | 88 | int *A = new int[size]; 89 | 90 | for (int i = 0; i < size; i++) 91 | cin >> A[i]; 92 | 93 | BST t; 94 | t.treeSort(A, size); 95 | 96 | t.print(A, size); 97 | 98 | delete[] A; 99 | 100 | system("pause"); 101 | return 0; 102 | } -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/2-Bubble Sort.cpp: -------------------------------------------------------------------------------- 1 | //Bubble Sort. 2 | //Time Complexity: O(n^2) 3 | //Space Complexity: O(1) auxiliary 4 | // Stable-> Yes 5 | // inPlace-> Yes 6 | 7 | 8 | #include 9 | using namespace std; 10 | 11 | //declarations of functions that will be used in program 12 | void bubbleSort(int arr[], int size); 13 | void swap(int *a,int *b); 14 | void input(int arr[],int size); 15 | void display(int arr[],int size); 16 | 17 | 18 | int main() { 19 | //input size of array 20 | int size; 21 | cout << "Enter Size of Array:"; 22 | cin >> size; 23 | 24 | //allocation of memory on heap 25 | int *arr = new int[size]; 26 | 27 | //input values 28 | input(arr, size); 29 | 30 | //bubble sort 31 | bubbleSort(arr, size); 32 | 33 | //display values 34 | display(arr, size); 35 | 36 | //de-allocation memory 37 | delete[] arr; 38 | 39 | system("pause"); 40 | return 0; 41 | 42 | } 43 | 44 | //function for bubble sort 45 | void bubbleSort(int arr[], int size) { 46 | for (int outer = 0; outer < size; outer++) { 47 | for (int inner = 0; inner < size - 1; inner++) { 48 | if (arr[inner] > arr[inner + 1]) { 49 | swap(&arr[inner], &arr[inner + 1]); 50 | } 51 | } 52 | } 53 | cout << "\n\n"; 54 | } 55 | 56 | //function that takes input in an array 57 | void input(int arr[],int size) { 58 | cout << "Enter "<> arr[i]; 61 | } 62 | 63 | 64 | //function to display array after bubble sort 65 | void display(int arr[],int size) { 66 | cout << "Array after bubble sort: "; 67 | for (int i = 0; i < size; i++) 68 | cout << arr[i] << " "; 69 | 70 | cout << "\n\n"; 71 | } 72 | 73 | //function to swap to values 74 | void swap(int *a, int *b) { 75 | int temp; 76 | temp = *a; 77 | *a = *b; 78 | *b = temp; 79 | } 80 | -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/3-Insertion Sort.cpp: -------------------------------------------------------------------------------- 1 | //Insertion Sort. 2 | //Time Complexity: O(n^2) 3 | //Space Complexity: O(1) auxiliary 4 | // Stable-> Yes 5 | // inPlace-> Yes 6 | 7 | #include 8 | using namespace std; 9 | 10 | //declarations of functions that will be used in program 11 | void input(int arr[], int size); 12 | void display(int arr[], int size); 13 | void insertionSort(int arr[], int size); 14 | void swap(int *a, int *b); 15 | 16 | int main() { 17 | //input size of array 18 | int size; 19 | cout << "Enter size of array:"; 20 | cin >> size; 21 | 22 | //allocation of memory on heap 23 | int *arr = new int[size]; 24 | 25 | //input values 26 | input(arr, size); 27 | 28 | //insertion sort 29 | insertionSort(arr, size); 30 | 31 | //display values 32 | display(arr, size); 33 | 34 | //de-allocation of memory 35 | delete[] arr; 36 | 37 | 38 | system("pause"); 39 | return 0; 40 | } 41 | 42 | //function for insertion sort 43 | void insertionSort(int arr[], int size) { 44 | int inner, outer; 45 | 46 | //here we start outer=1 because in insertion sort 0 index in considered to be sorted . 47 | for (outer = 1; outer < size; outer++) { 48 | inner = outer; 49 | while (inner > 0 && arr[inner - 1] > arr[inner]) { 50 | swap(&arr[inner - 1], &arr[inner]); 51 | 52 | inner--; 53 | } 54 | } 55 | cout << "\n\n"; 56 | } 57 | 58 | //function to take input values in array 59 | void input(int arr[], int size) { 60 | cout << "Enter " << size << " values in Array:" << endl; 61 | for (int i = 0; i < size; i++) 62 | cin >> arr[i]; 63 | } 64 | 65 | //function to display array 66 | void display(int arr[], int size) { 67 | cout << "Array after Insertion Sort: "; 68 | for (int i = 0; i < size; i++) 69 | cout << arr[i] << " "; 70 | 71 | cout << "\n\n"; 72 | } 73 | 74 | //function to swap two values 75 | void swap(int *a, int *b) { 76 | int temp; 77 | temp = *a; 78 | *a = *b; 79 | *b = temp; 80 | } 81 | 82 | 83 | -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/4-Shell Sort.cpp: -------------------------------------------------------------------------------- 1 | //Shell Sort. 2 | //Time Complexity:The time complexity of code below is: O(n^2) 3 | //Time complexity of Shell Sort depends on gap sequence.Its best case time complexity is O(n* logn) and worst case is O(n* log2n). 4 | //Space Complexity: O(1) auxiliary 5 | // Stable-> No 6 | // inPlace-> Yes 7 | 8 | #include 9 | using namespace std; 10 | 11 | void ShellSort(int A[], int size); 12 | 13 | int main() { 14 | int size; 15 | cout << "Enter size of Array:"; 16 | cin >> size; 17 | 18 | int *A = new int[size]; 19 | cout << "Enter " << size << " values in Array:" << endl; 20 | for (int i = 0; i < size; i++) 21 | cin >> A[i]; 22 | 23 | ShellSort(A, size); 24 | 25 | cout << "Sorted Array is:"; 26 | for (int i = 0; i < size; i++) 27 | cout << A[i] << " "; 28 | cout << endl; 29 | 30 | delete[] A; 31 | 32 | system("pause"); 33 | return 0; 34 | } 35 | 36 | 37 | void ShellSort(int A[], int size) { 38 | //in shell sort the gap/interval is size of array / 2 39 | int gap = size / 2; 40 | 41 | while (gap > 0) { 42 | 43 | int j = 0; 44 | 45 | for (int i = gap; i < size; i++) { 46 | //here we place the value at A[i] in temp 47 | int temp = A[i]; 48 | //here we use 'j' variable because we don't want to alter/change the value of 'i' that is in the above loop 49 | 50 | //here we are not swapping the values in that manner that we are doing in previous algorithms. 51 | //but in shell sort look how we are swapping here... 52 | 53 | for (j = i; j >= gap && A[j - gap] > temp; j = j - gap) { 54 | 55 | A[j] = A[j - gap]; 56 | 57 | } 58 | 59 | A[j] = temp; 60 | 61 | } 62 | 63 | //at the end of above loops the value of gap is reduced by gap/2 64 | gap = gap / 2; 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/5-Count Sort.cpp: -------------------------------------------------------------------------------- 1 | //Count Sort. 2 | //Count sort is not included in our course DSA(IT-207) but we are doing this because Shell Sort(included in our course) can not be implemented without 3 | //count sort. 4 | //Time Complexity: O(n+k) 5 | //If you don't understand what is happening then see a video whose link is: 6 | // https://youtu.be/pEJiGC-ObQE 7 | 8 | #include 9 | using namespace std; 10 | 11 | int max(int A[], int size); 12 | void countSort(int A[], int size, int k); 13 | 14 | int main() { 15 | int size; 16 | cout << "Enter size of Array:"; 17 | cin >> size; 18 | 19 | int *A = new int[size]; 20 | 21 | cout << "Input " << size << " Values in Array:" << endl; 22 | for (int i = 0; i < size; i++) { 23 | cin >> A[i]; 24 | 25 | } 26 | 27 | int k; 28 | k = max(A, size); 29 | 30 | countSort(A, size, k); 31 | 32 | cout << "Sorted Array is:"; 33 | for (int i = 0; i < size; i++) 34 | cout << A[i] << " "; 35 | cout << endl; 36 | 37 | delete[] A; 38 | 39 | system("pause"); 40 | return 0; 41 | } 42 | 43 | //function that finds maximum in an array. 44 | int max(int A[], int size) { 45 | int max = 0; 46 | for (int i = 0; i < size; i++) { 47 | if (A[i] > max) 48 | max = A[i]; 49 | } 50 | return max; 51 | } 52 | 53 | //Code for count sort. 54 | void countSort(int A[], int size, int k) { 55 | //here 'k' is the maximum value in an array 56 | //here we created a new array of size k+1 and initialized it with 0. 57 | int *count = new int[k+1]; 58 | //initializing the whole array with 0 59 | for (int i = 0; i < k+1; i++) { 60 | count[i] = 0; 61 | } 62 | 63 | //to check how many times a value is repeated.We will increment every time the value is repeated. 64 | for (int i = 0; i < size; i++) { 65 | ++count[A[i]]; 66 | } 67 | 68 | //so to store each value at its range we are updating the count array. and we start from i=1. 69 | for (int i = 1; i <= k; i++) { 70 | count[i] = count[i] + count[i - 1]; 71 | } 72 | 73 | //now we create another array B of actual size. 74 | int *B = new int[size]; 75 | 76 | //this will place every value at its range and at right place. and the array is sorted. 77 | for (int i = size - 1; i >= 0; i--) { 78 | B[--count[A[i]]] = A[i]; 79 | } 80 | 81 | //now copy the array B into array A 82 | for (int i = 0; i < size; i++) { 83 | A[i] = B[i]; 84 | } 85 | 86 | delete[] count; 87 | delete[] B; 88 | } -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/6-Radix Sort.cpp: -------------------------------------------------------------------------------- 1 | //Radix Sort. 2 | //In this we will use count sort as well. 3 | //Time Complexity: O(d*(n+k)) 4 | // where d is number of digits in maximum number. 'n' is the size of actual array. 'b' is the base. 5 | //to understand vist: 6 | // https://www.youtube.com/watch?v=Il45xNUHGp0&t=651s 7 | 8 | #include 9 | using namespace std; 10 | 11 | int maximum(int A[], int size); 12 | void countSort(int A[], int size, int pass); 13 | void radixSort(int A[], int size); 14 | 15 | int main() { 16 | int size; 17 | cout << "Enter size of Array:"; 18 | cin >> size; 19 | 20 | int *A = new int[size]; 21 | 22 | cout << "Input " << size << " Values in Array:" << endl; 23 | for (int i = 0; i < size; i++) { 24 | cin >> A[i]; 25 | 26 | } 27 | 28 | radixSort(A, size); 29 | 30 | cout << "Sorted Array is:"; 31 | for (int i = 0; i < size; i++) 32 | cout << A[i] << " "; 33 | cout << endl; 34 | 35 | delete[] A; 36 | 37 | 38 | 39 | system("pause"); 40 | return 0; 41 | } 42 | //function that finds maximum in an array. 43 | int maximum(int A[], int size) { 44 | int max = 0; 45 | for (int i = 0; i < size; i++) { 46 | if (A[i] > max) 47 | max = A[i]; 48 | } 49 | return max; 50 | } 51 | 52 | void radixSort(int A[], int size) { 53 | int max = maximum(A, size); 54 | 55 | for (int pass = 1; max / pass > 0; pass = pass * 10) { 56 | countSort(A, size, pass); 57 | } 58 | 59 | } 60 | 61 | //Code for count sort. 62 | void countSort(int A[], int size, int pass) { 63 | //as we are dealing with decimal no. system so base is 10 therefore we created an array of size 10 64 | int count[10] = { 0 }; 65 | 66 | 67 | //to check how many times a value is repeated.We will increment every time the value is repeated. 68 | for (int i = 0; i < size; i++) { 69 | ++count[(A[i] / pass) % 10]; 70 | } 71 | 72 | //so to store each value at its range we are updating the count array. and we start from i=1. 73 | for (int i = 1; i < 10; i++) { 74 | count[i] = count[i] + count[i - 1]; 75 | } 76 | 77 | //now we create another array B of actual size. 78 | int *B = new int[size]; 79 | 80 | //this will place every value at its range and at right place. and the array is sorted. 81 | for (int i = size - 1; i >= 0; i--) { 82 | B[count[(A[i] / pass) % 10] - 1] = A[i]; 83 | count[(A[i] / pass) % 10]--; 84 | } 85 | 86 | //now copy the array B into array A 87 | for (int i = 0; i < size; i++) { 88 | A[i] = B[i]; 89 | } 90 | 91 | delete[] B; 92 | } 93 | -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/7-Merge Sort.cpp: -------------------------------------------------------------------------------- 1 | //Merge Sort 2 | //Time Complexity: O(nlogn) in all best , average and worst case. 3 | //Space Complexity: O(n) auxiliary 4 | //Algorithmic Paradigm: Divide & Conquer 5 | //Stable: yes 6 | //In Place: No 7 | //If you wanna understand how to do this then go to link given below: 8 | // https://www.youtube.com/watch?v=jlHkDBEumP0&t=298s 9 | 10 | #include 11 | using namespace std; 12 | 13 | void MergeSort(int A[], int lb, int ub); 14 | void merge(int A[], int lb, int mid, int ub); 15 | 16 | int main() { 17 | int size; 18 | cout << "How many Values you wanna enter:"; 19 | cin >> size; 20 | 21 | int *A = new int[size]; 22 | 23 | cout << "Enter " << size << " values :" << endl; 24 | for (int i = 0; i < size; i++) 25 | cin >> A[i]; 26 | 27 | MergeSort(A, 0, size-1); //here we pass size-1 remember. i have spent 2 hours on finding this run time error.Now the time is 12:45 am night. 28 | //and i have just found this bug. That i have to pass size-1 before i was passing only size. 29 | 30 | cout << "Sorted Array is: "; 31 | for (int i = 0; i < size; i++) 32 | cout << A[i] << " "; 33 | cout << endl; 34 | 35 | delete[] A; 36 | 37 | 38 | system("pause"); 39 | return 0; 40 | } 41 | 42 | 43 | void MergeSort(int A[], int lb, int ub) { 44 | int mid; 45 | if (lb < ub) { 46 | mid = (lb+ub) / 2; 47 | MergeSort(A, lb, mid); 48 | MergeSort(A, mid + 1, ub); 49 | merge(A, lb, mid, ub); 50 | } 51 | } 52 | 53 | //function which merge the sub-arrays in sorted manner. 54 | //This merge function is the back bone of Merge Sort 55 | void merge(int A[], int lb, int mid, int ub) { 56 | int i = lb, j = mid+1, k = 0; 57 | int *B = new int[ub]; 58 | 59 | //comparing the values and placing them in Array B in sorted order. 60 | while (i <= mid && j <= ub) { 61 | if (A[i] <= A[j]) { 62 | B[k] = A[i]; 63 | i++; 64 | } 65 | else { 66 | B[k] = A[j]; 67 | j++; 68 | } 69 | k++; 70 | } 71 | //Here we are checking if any values left in any one array after the exhausting of other array. 72 | //if left array is exhausted then place all the values left in right array as it is in Array B. 73 | 74 | while (j <= ub) { 75 | B[k] = A[j]; 76 | j++; 77 | k++; 78 | } 79 | 80 | //if right array is exhausted then place all the values left in left sub array as it is in Array B. 81 | 82 | while (i <= mid) { 83 | B[k] = A[i]; 84 | i++; 85 | k++; 86 | } 87 | //copy the values from Array B into Array A(actual array) 88 | for ( i= lb ; i <= ub; i++) { 89 | A[i] = B[i-lb]; 90 | } 91 | } -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/8-Quick Sort.cpp: -------------------------------------------------------------------------------- 1 | //Quick Sort (Partition-Exchange Sort) 2 | //Time Complexity: O(n^2) | best or average case: O(nlogn) 3 | //Space Complexity: O(logn) 4 | //Stable: No 5 | //In-Place: Yes 6 | //Algorithmic Paradigm: Divide & Conquer 7 | //To understand watch the video on link given below: 8 | // https://www.youtube.com/watch?v=QN9hnmAgmOc 9 | 10 | #include 11 | using namespace std; 12 | 13 | void QuickSort(int A[], int lb, int ub); 14 | int partition(int A[], int lb, int ub); 15 | void swap(int *a, int *b); 16 | 17 | int main() { 18 | int size; 19 | cout << "How many Values you wanna enter:"; 20 | cin >> size; 21 | 22 | int *A = new int[size]; 23 | 24 | cout << "Enter " << size << " values:" << endl; 25 | for (int i = 0; i < size; i++) { 26 | cin >> A[i]; 27 | } 28 | 29 | QuickSort(A, 0, size - 1); 30 | 31 | cout << "Sorted Array is:"; 32 | for (int i = 0; i < size; i++) 33 | cout << A[i] << " "; 34 | cout << endl; 35 | 36 | delete[] A; 37 | 38 | system("pause"); 39 | return 0; 40 | } 41 | 42 | //Function for quick sort. 43 | void QuickSort(int A[], int lb, int ub) { 44 | if (lb < ub) { 45 | int loc; //loc is a variable that will store the end value index. 46 | loc = partition(A, lb, ub); 47 | QuickSort(A, lb, loc - 1); //Recursive call 48 | QuickSort(A, loc + 1, ub); //Recursive call 49 | } 50 | } 51 | 52 | //Function to swap two array values 53 | void swap(int *a, int *b) { 54 | int temp; 55 | temp = *a; 56 | *a = *b; 57 | *b = temp; 58 | } 59 | 60 | //The partition function is the back bone of quick sort. 61 | int partition(int A[], int lb, int ub) { 62 | int pivot, start, end; 63 | pivot = A[lb]; //here we select first element of array as pivot. but it depends on you , you can select any element as pivot. 64 | start = lb; 65 | end = ub; 66 | while (start < end) { 67 | 68 | //placing all the values <= pivot at left 69 | while (A[start] <= pivot) { 70 | start++; 71 | } 72 | //placing all the values > pivot at right 73 | while (A[end] > pivot) { 74 | end--; 75 | } 76 | 77 | //when start is less than end then swap start & end. 78 | if (start < end) { 79 | swap(&A[start], &A[end]); 80 | } 81 | } 82 | //this will run only when start is not less than end. then in this case we will swap pivot and end. 83 | swap(&A[lb], &A[end]); 84 | 85 | //this function returns the end value index. 86 | return end; 87 | } -------------------------------------------------------------------------------- /C++/11-Sorting Algorithms/9-Heap Sort.cpp: -------------------------------------------------------------------------------- 1 | //Heap Sort 2 | //Time Complexity: Time complexity of heapify is O(Logn). 3 | //Time complexity of createAndBuildHeap() is O(n) and 4 | //overall time complexity of Heap Sort is O(nLogn). 5 | 6 | //Space Complexity: O(1) auxiliary 7 | //Stable: No 8 | //In Place: Yes 9 | 10 | //To understand heap sort watch the following videos: 11 | // 1- https://www.youtube.com/watch?v=zDlTxrEwxvg 12 | // 2- https://www.youtube.com/watch?v=NEtwJASLU8Q&list=PLdo5W4Nhv31bEiyP4tclZMc5mP_X7OD7k&index=6 13 | // 3- https://www.youtube.com/watch?v=Q_eia3jC9Ts&list=PLdo5W4Nhv31bEiyP4tclZMc5mP_X7OD7k&index=7 14 | 15 | #include 16 | using namespace std; 17 | 18 | void HeapSort(int A[],int n); 19 | 20 | void heapify(int A[], int n, int i); 21 | 22 | void swap(int *a,int *b); 23 | 24 | int main() { 25 | 26 | int size; 27 | cout<<"How many values you wanna enter:"; 28 | cin>>size; 29 | 30 | int *A = new int[size]; 31 | 32 | cout<<"Enter "<>A[i]; 35 | 36 | HeapSort(A,size); 37 | 38 | cout<<"Sorted Array is: "; 39 | for(int i=0; i=0; i--){ 52 | heapify(A,n,i); //Building of heap 53 | } 54 | 55 | //now picking each element one by one from last node and deletion 56 | for(int i=n-1; i>=0; i--){ 57 | swap(&A[0],&A[i]); //it swap root node with last node. 58 | 59 | heapify(A,i,0);//here we pass 0 because deletion is always from root node. 60 | } 61 | } 62 | 63 | 64 | //function to swap two array values 65 | void swap(int *a, int *b){ 66 | int temp; 67 | temp=*a; 68 | *a=*b; 69 | *b=temp; 70 | } 71 | 72 | void heapify(int A[],int n, int i){ 73 | //setting the largest value = root node 74 | int largest=i; 75 | //finding the left child of root node 76 | int l= (2 * i) + 1; 77 | //finding the right child of root node 78 | int r= (2 * i) + 2; 79 | //if left child is < size and left child is greater than 80 | //largest then largest = left child. 81 | if(lA[largest]){ 82 | largest=l; 83 | } 84 | //if right child is < size and right child is greater than 85 | //largest then largest = right child 86 | if(rA[largest]){ 87 | largest=r; 88 | } 89 | //now as we have updated the largest 90 | //so we check if largest != i then we will swap 91 | if(largest!=i){ 92 | swap(&A[i],&A[largest]); 93 | 94 | //recursive call 95 | heapify(A,n,largest); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShehrozIrfan/learn-dsa/bcd65a9ee2c6fb4dcfc769d97b2eddd56c05db0a/C++/12. Labs & Tasks/.DS_Store -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/Lab1/DSA lab1 task1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | DSA Lab 3 | Date: 12-04-19 4 | Task 1: 5 | Write a program implementing inheritance in which there is a base class shape.Base class should have methods to set 6 | width and height of shape.A derived class should have methods to get area.Area is obtained by multiplying 7 | Height*Width. 8 | note: 9 | Base class should have data members declared in protected access specifiers. 10 | */ 11 | #include 12 | using namespace std; 13 | 14 | class Base{ 15 | protected: 16 | float height; 17 | float width; 18 | public: 19 | void set_height(int h){ 20 | height=h; 21 | } 22 | void set_width(int w){ 23 | width=w; 24 | } 25 | }; 26 | class Derived:public Base{ 27 | public: 28 | int get_area(){ 29 | return (width*height); 30 | } 31 | }; 32 | int main(){ 33 | 34 | Derived d; 35 | d.set_height(10); 36 | d.set_width(50); 37 | cout<<"Area="; 38 | cout< 8 | using namespace std; 9 | int main(){ 10 | int size; 11 | cout<<"Enter size of array:"; 12 | cin>>size; 13 | int arr[size]; 14 | cout<<"Enter values in array:"<>arr[i]; 18 | } 19 | 20 | int max,min; 21 | max=min=arr[0]; 22 | 23 | for(int i=0;imax){ 25 | max=arr[i]; 26 | } 27 | if(arr[i]>arr[i]; 15 | } 16 | 17 | cout<<"Values in actual order:"<=0;i--){ 23 | cout< 15 | using namespace std; 16 | int main(){ 17 | int size,delNum,counter=0; 18 | 19 | // Input size of array 20 | cout<<"\n\t"<<"Enter the size of Array:"; 21 | cin>>size; 22 | // array of size 'size' entered by the user. 23 | int arr[size]; 24 | // Input values in array. 25 | for(int count=0; count < size ; count++){ 26 | cout<<"\t"<<"Enter value "<>arr[count]; 28 | } 29 | 30 | cout<<"\n\t"<<"Enter the number that you wanna Delete:"; 31 | cin>>delNum; 32 | 33 | //Searching the occurance of deleted number in array 34 | for(int count=0; count < size; count++){ 35 | if(arr[count]==delNum){ 36 | counter++; 37 | } 38 | } 39 | 40 | if(counter==0){ 41 | cout<<"\n\n\t"<<"Number not found in array."< 6 | using namespace std; 7 | 8 | void sortArray(int arr[]); 9 | void printArray(int arr[]); 10 | int main(){ 11 | int arr[10]; 12 | cout<<"Enter values:"<>arr[i]; 15 | 16 | } 17 | cout<<"Array before sorting:"<arr[j+1]){ 32 | 33 | 34 | temp=arr[j]; 35 | arr[j]=arr[j+1]; 36 | arr[j+1]=temp; 37 | } 38 | } 39 | } 40 | } 41 | void printArray(int arr[]){ 42 | cout<<"Array after sorting:"< 6 | using namespace std; 7 | int main() { 8 | int arr[10] = { 10,20,30,40,50,60,70,80,90,100 }; 9 | cout << "Printing values using Array Notation:" << endl; 10 | 11 | for (int i = 0; i < 10; i++) { 12 | cout << arr[i] << endl; 13 | } 14 | 15 | int *ptr; 16 | ptr = arr; 17 | cout << "Printing values using Pointer Notation:" << endl; 18 | for (int i = 0; i < 10; i++) { 19 | cout << *ptr << endl; 20 | ptr++; 21 | } 22 | 23 | cout << "Printing address using Pointer Notation:" << endl; 24 | for (int i = 0; i < 10; i++) { 25 | cout << ptr << endl; 26 | ptr++; 27 | } 28 | 29 | 30 | 31 | system("pause"); 32 | return 0; 33 | } -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/Task (13-06-19)/Task (13-06-19).cpp: -------------------------------------------------------------------------------- 1 | //sum of first 100 natural numbers using recursion. 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | int sum(int n){ 8 | if(n!=0){ 9 | return n+sum(n-1); 10 | } 11 | } 12 | 13 | 14 | int main(){ 15 | 16 | int n=100; 17 | 18 | cout<<"Sum of first 100 Natural Numbers is: "< 2 | using namespace std; 3 | 4 | #define SIZE 10 //Constant size 5 | 6 | /*class MyStack { 7 | private: 8 | int top; //holds currently top of stack 9 | int st[SIZE]; 10 | public: 11 | MyStack() { 12 | top = -1; 13 | } 14 | 15 | //as we know that the array starts from 0 index and goes on and if index=-1 means array is empty 16 | //because array didn't have index in negative. 17 | bool isEmpty() { 18 | if (top == -1) 19 | return true; 20 | else 21 | return false; 22 | } 23 | 24 | void push(int x) { 25 | //if top =9 means 0-9 which means we have entered all the 10 values and no more values 26 | //entered in stack so it will be overflow 27 | if (top == SIZE - 1) { 28 | cout << "Stack Overflow" << endl; 29 | } 30 | else { 31 | top = top + 1; 32 | st[top] = x; 33 | } 34 | } 35 | 36 | int pop() { 37 | if (top == -1) 38 | cout << "Empty Stack" << endl; 39 | else 40 | return st[top--]; 41 | } 42 | 43 | void display() { 44 | cout << "Values in Stack are:" << endl; 45 | for (int c = 0; c <= top; c++) { 46 | cout << st[c] << " "; 47 | } 48 | cout << endl; 49 | } 50 | }; 51 | 52 | int main() { 53 | 54 | MyStack s; 55 | s.isEmpty(); 56 | s.push(90); 57 | s.push(20); 58 | s.push(11); 59 | s.push(7); 60 | s.push(0); 61 | s.push(00); 62 | s.push(88); 63 | s.push(44); 64 | s.push(33); 65 | s.push(22); 66 | s.push(11); 67 | s.pop(); 68 | s.display(); 69 | system("pause"); 70 | return 0; 71 | } 72 | */ 73 | 74 | class MyStack { 75 | private: 76 | int top; //holds currently top of stack 77 | char st[SIZE]; 78 | public: 79 | MyStack() { 80 | top = -1; 81 | } 82 | 83 | //as we know that the array starts from 0 index and goes on and if index=-1 means array is empty 84 | //because array didn't have index in negative. 85 | bool isEmpty() { 86 | if (top == -1) 87 | return true; 88 | else 89 | return false; 90 | } 91 | 92 | void push(char x) { 93 | //if top =9 means 0-9 which means we have entered all the 10 values and no more values 94 | //entered in stack so it will be overflow 95 | if (top == SIZE - 1) { 96 | cout << "Stack Overflow" << endl; 97 | } 98 | else { 99 | top = top + 1; 100 | st[top] = x; 101 | } 102 | } 103 | 104 | char pop() { 105 | if (top == -1) 106 | cout << "Empty Stack" << endl; 107 | else 108 | return st[top--]; 109 | } 110 | 111 | void display() { 112 | cout << "Values in Stack are:" << endl; 113 | for (int c = 0; c <= top; c++) { 114 | cout << st[c] << " "; 115 | } 116 | cout << endl; 117 | } 118 | }; 119 | int main() { 120 | MyStack s; 121 | s.push('A'); 122 | s.push('E'); 123 | s.push('I'); 124 | s.push('O'); 125 | s.push('U'); 126 | s.display(); 127 | s.pop(); 128 | s.display(); 129 | 130 | system("pause"); 131 | return 0; 132 | } 133 | 134 | 135 | -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/Task(10-05-19)/Task DSA(10-05-19)(important).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem: 3 | let we have a stack: 4 | * * 5 | ********* 6 | * 12 * 7 | ********* 8 | * 5 * 9 | ********* 10 | * 2 * 11 | ********* 12 | 13 | and we wanted to get to out of it. and removing 2 from the above stack the stack will be like this: 14 | 15 | * * 16 | ********* 17 | * 12 * 18 | ********* 19 | * 5 * 20 | ********* 21 | 22 | so to do this we make two stacks one for storing values and in second stack we push the values of first stack. 23 | 24 | */ 25 | 26 | #include 27 | using namespace std; 28 | 29 | //maximum size of array 30 | #define SIZE 100 31 | 32 | class MyStack { 33 | private: 34 | int top; 35 | int st[SIZE]; 36 | public: 37 | //constructor 38 | MyStack() { 39 | top = -1; 40 | } 41 | 42 | //check stack is empty or not 43 | bool isEmpty() { 44 | if (top == -1) 45 | return true; 46 | else 47 | return false; 48 | } 49 | 50 | //inserting an element on the top of stack 51 | void push(int x) { 52 | if (top == SIZE - 1) { 53 | cout << "Error: Queue Overflow" << endl; 54 | } 55 | else { 56 | top = top + 1; 57 | st[top] = x; 58 | } 59 | } 60 | 61 | //removing an element from the top of stack 62 | int pop() { 63 | if (top == -1) { 64 | cout << "Error: No element to pop" << endl; 65 | } 66 | return st[top--]; 67 | } 68 | 69 | //returns the current top of stack 70 | int topOfStack() { 71 | return st[top]; 72 | } 73 | 74 | //checks whether the stack is full or not 75 | bool isFull() 76 | { 77 | return top == SIZE - 1; 78 | } 79 | 80 | //display stack 81 | void display() { 82 | for (int c = 0; c <= top; c++) { 83 | cout << st[c] << " "; 84 | } 85 | cout << endl; 86 | } 87 | }; 88 | 89 | class Queue { 90 | private: 91 | //we made two stacks 92 | MyStack s1, s2; 93 | public: 94 | 95 | //inserting a value in queue 96 | void enQueue(int val) 97 | { 98 | if (s1.isFull()) { 99 | cout << "Queue is Full. Can't be insrted" << endl; 100 | } 101 | else { 102 | //we use the push method of MyStack class. 103 | s1.push(val); 104 | } 105 | } 106 | 107 | //removing a value from one stack and placing it in other stack and then we get out our desired value and again push the values in first stack 108 | int deQueue() { 109 | if (s1.isEmpty()) { 110 | cout << "Queue is Empty. Can`t be Dequed" << endl; 111 | } 112 | else { 113 | //while s1 is not empty pop the values from s1 and push in s2. 114 | while (!s1.isEmpty()) { 115 | s2.push(s1.pop()); 116 | } 117 | 118 | //we get our desired value that is not on the top of s2. 119 | int val = s2.pop(); 120 | 121 | //pushing the values back to s1 122 | //while s2 is not empty pop values from s2 and push in s1 123 | while (!s2.isEmpty()) { 124 | s1.push(s2.pop()); 125 | } 126 | 127 | //returns are desired value 128 | return val; 129 | 130 | } 131 | } 132 | 133 | //to check s1 is empty or not 134 | bool isEmpty() { 135 | return s1.isEmpty(); 136 | } 137 | 138 | //display queue 139 | void displayQueue() { 140 | cout << "Displaying Queue values:" << endl; 141 | s1.display(); 142 | } 143 | }; 144 | int main() { 145 | 146 | Queue myQueue; 147 | myQueue.enQueue(2); 148 | myQueue.enQueue(5); 149 | myQueue.enQueue(12); 150 | myQueue.displayQueue(); 151 | 152 | myQueue.deQueue(); 153 | myQueue.displayQueue(); 154 | 155 | system("pause"); 156 | return 0; 157 | } 158 | -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/Task(18-05-19)/DSA Task (18-05-19).cpp: -------------------------------------------------------------------------------- 1 | //DSA Task (18-05-19) 2 | //display first 100 natural numbers using recursion. 3 | 4 | #include 5 | using namespace std; 6 | 7 | void display(int n) { 8 | if (n <= 100) { 9 | cout << n << endl; 10 | display(n+1); 11 | } 12 | } 13 | 14 | int main() { 15 | display(1); 16 | 17 | 18 | 19 | system("pause"); 20 | return 0; 21 | } -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/Task(27-06-19)/BST(LinkedList Implementation).cpp: -------------------------------------------------------------------------------- 1 | //Binary Search Tree (Linked List Implementation) 2 | 3 | #include 4 | using namespace std; 5 | 6 | //when a node is created it will have three things: 7 | // 1. data(when a new node is created it has its value as data) 8 | // 2. left child(when a new node is created it is NULL) 9 | // 3. right child(when a new node is created it is NULL) 10 | class Node { 11 | public: 12 | //data will have the value that the node has 13 | int data; 14 | //left child stores the address of left child 15 | Node *leftChild; 16 | //right child stores the address of right child 17 | Node *rightChild; 18 | 19 | //Paremeterized constructor which initialize all the data members of class Node to 0 and NULL. 20 | Node(int d = 0, Node *left = NULL, Node *right = NULL) { 21 | data = d; 22 | leftChild = left; 23 | rightChild = right; 24 | } 25 | }; 26 | 27 | //This is a Global Pointer. we declare it gloabal because when we do pre , post or in order traversal we have to pass root as a argument from main when 28 | // we call these functions. that's why we declare it global. 29 | Node *root=NULL; 30 | 31 | class BST { 32 | public: 33 | 34 | //the definitions of all these functions is outside the class. 35 | int insert(int d); 36 | void preOrderTraversal(Node *root); 37 | void inOrderTraversal(Node *root); 38 | void postOrderTraversal(Node *root); 39 | }; 40 | 41 | //insert function is used to insert a new node in a tree. 42 | int BST::insert(int d) { 43 | //tempNode is a pointer which always has address of new node that is created. 44 | Node *tempNode = new Node(d); 45 | Node *parent = NULL; 46 | Node *current = NULL; 47 | 48 | if (root == NULL) { 49 | root = tempNode; 50 | } 51 | else { 52 | current = root; 53 | parent = NULL; 54 | 55 | while (1) { 56 | parent = current; 57 | //in BST value of all the nodes in left subtree is lesser or equal 58 | if (tempNode->data <= parent->data) { 59 | current = current->leftChild; 60 | if (current == NULL) { 61 | parent->leftChild = tempNode; 62 | return 0; 63 | } 64 | } 65 | //in BST value of all the nodes in right subtree is greater. 66 | else { 67 | current = current->rightChild; 68 | if (current == NULL) { 69 | parent->rightChild = tempNode; 70 | return 0; 71 | } 72 | } 73 | } 74 | } 75 | } 76 | 77 | //in pre order traversal first root node is printed then left subtree and then right subtree is printed and it is true for all the nodes. 78 | void BST::preOrderTraversal(Node *root) { 79 | 80 | if (root != NULL) { 81 | cout << root->data<<" "; 82 | //here we use recursion 83 | preOrderTraversal(root->leftChild); 84 | preOrderTraversal(root->rightChild); 85 | } 86 | 87 | } 88 | 89 | //in "in order" traversal first left subtree is printed then the root node is printed and then right subtree is printed and is true for all the nodes. 90 | void BST::inOrderTraversal(Node *root) { 91 | 92 | if (root != NULL) { 93 | //here we use recursion 94 | inOrderTraversal(root->leftChild); 95 | cout << root->data << " "; 96 | inOrderTraversal(root->rightChild); 97 | } 98 | 99 | } 100 | 101 | //in post order traversal first left subtree is printed and then right subtree is printed and then root node is printed and is true for all the nodes. 102 | void BST::postOrderTraversal(Node *root) { 103 | 104 | if (root != NULL) { 105 | //here we use recursion 106 | postOrderTraversal(root->leftChild); 107 | postOrderTraversal(root->rightChild); 108 | cout << root->data << " "; 109 | } 110 | 111 | } 112 | 113 | int main() { 114 | BST t; 115 | t.insert(5); 116 | t.insert(4); 117 | t.insert(7); 118 | t.insert(6); 119 | t.insert(0); 120 | 121 | cout << "Pre Order Traversal is :" << " "; 122 | t.preOrderTraversal(root); 123 | cout << "\n\n"; 124 | 125 | cout << "In Order Traversal is :" << " "; 126 | t.inOrderTraversal(root); 127 | cout << "\n\n"; 128 | 129 | cout << "Post Order Traversal is :" << " "; 130 | t.postOrderTraversal(root); 131 | cout << "\n\n"; 132 | 133 | system("pause"); 134 | return 0; 135 | } -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/Tasks(03-05-19)/DSA lab 03-05-19.cpp: -------------------------------------------------------------------------------- 1 | //DSA lab 2 | //03-05-19 3 | 4 | #include 5 | using namespace std; 6 | 7 | class Node { 8 | public: 9 | int info; 10 | Node *next, *prev; 11 | 12 | //Constructor 13 | Node(int i, Node *p = 0) { 14 | info = i; 15 | next = p; 16 | prev = p; 17 | } 18 | 19 | }; 20 | 21 | class DLinkedList { 22 | private: 23 | Node *head; 24 | Node *tail; 25 | 26 | public: 27 | //Constructor 28 | DLinkedList() { 29 | head = tail = 0; 30 | } 31 | //Task 1: add to head, add to tail , display list 32 | //add to head 33 | void addToHead(int i) { 34 | if (head == 0) { 35 | head = tail = new Node(i); 36 | } 37 | else { 38 | head->prev = new Node(i); 39 | head->prev->next = head; 40 | head = head->prev; 41 | } 42 | } 43 | 44 | //add to tail 45 | void addToTail(int i){ 46 | if(head==0){ 47 | head=tail=new Node(i); 48 | } 49 | else{ 50 | tail->next=new Node(i); 51 | tail->next->prev=tail; 52 | tail=tail->next; 53 | } 54 | } 55 | 56 | //display list 57 | void displayList() { 58 | if (head == 0) { 59 | cout << "Empty List" << endl; 60 | cout << "Nothing to display" << endl; 61 | } 62 | else if (head == tail != 0) { 63 | cout<<"List is:"<info << endl; 65 | } 66 | else { 67 | Node *temp; 68 | temp = head; 69 | cout<<"List is:"<info << " "; 72 | temp = temp->next; 73 | } 74 | cout<next; 93 | delete temp; 94 | head->prev=NULL; 95 | cout<<" Head Deleted"<prev; 112 | delete temp; 113 | tail->next=NULL; 114 | cout<<" Tail Deleted"< 7 | using namespace std; 8 | 9 | //size of queue 10 | #define SIZE 10 11 | 12 | class MyQueue { 13 | private: 14 | int que[SIZE]; 15 | int front; 16 | int rear; 17 | 18 | public: 19 | //constructor 20 | MyQueue() { 21 | front = -1; 22 | rear = -1; 23 | } 24 | 25 | int enQueue(int x); 26 | void deQueue(); 27 | bool isEmpty(); 28 | int frontOfQueue(); 29 | void display(); 30 | int searchKey(int key); 31 | }; 32 | 33 | bool MyQueue::isEmpty() { 34 | if (front == -1 && rear == -1) 35 | return true; 36 | else 37 | return false; 38 | } 39 | 40 | int MyQueue::enQueue(int x) { 41 | //when queue is empty 42 | if (front == -1 && rear == -1) { 43 | front = rear = 0; 44 | } 45 | //when queue is full 46 | else if ((rear + 1) % SIZE == front) { 47 | cout << "Error: Queue is full" << endl; 48 | return 0; 49 | } 50 | //when queue contains one or more than one element 51 | else { 52 | rear = (rear + 1) % SIZE; 53 | } 54 | que[rear] = x; //place value at rear index 55 | } 56 | 57 | void MyQueue::deQueue() { 58 | //when queue is empty 59 | if (front == -1 && rear == -1) 60 | cout << "Error: Queue is Empty" << endl; 61 | //when there is only one element in queue 62 | else if (front == rear) 63 | front = rear = -1; 64 | //when there are more than one element in queue 65 | else { 66 | front = (front + 1) % SIZE; 67 | } 68 | } 69 | 70 | int MyQueue::frontOfQueue() { 71 | //when queue is empty 72 | if (isEmpty()) 73 | return 0; 74 | //when queue is not empty 75 | else 76 | return que[front]; 77 | } 78 | void MyQueue::display() { 79 | //when queue is empty 80 | if (front == -1 && rear == -1) { 81 | cout << "Error: Empty Queue" << endl; 82 | cout << "Nothing to display" << endl; 83 | } 84 | else { 85 | //when queue contains one or more than one element 86 | cout << "Queue is:" << endl; 87 | for (int c = front; c <= rear; c++) { 88 | cout << que[c] << " "; 89 | } 90 | cout << endl; 91 | } 92 | } 93 | 94 | //searching in queue. 95 | int MyQueue::searchKey(int key) { 96 | //when queue is empty 97 | if (front == -1 && rear == -1) { 98 | cout << "Error: Empty Queue" << endl; 99 | cout << "Nothing to Search" << endl; 100 | } 101 | else { 102 | //when queue contains one or more than one element 103 | for (int c = front; c <= rear; c++) { 104 | if (que[c] == key) { 105 | cout << key << " Founded in Queue" << endl; 106 | return 0; 107 | } 108 | } 109 | cout << key << " not founded in Queue" << endl; 110 | 111 | } 112 | } 113 | 114 | int main() { 115 | 116 | MyQueue q; 117 | q.enQueue(5); 118 | q.enQueue(10); 119 | q.enQueue(3); 120 | q.display(); 121 | q.searchKey(3); 122 | q.searchKey(0); 123 | q.searchKey(10); 124 | q.searchKey(5); 125 | q.searchKey(4); 126 | system("pause"); 127 | return 0; 128 | } -------------------------------------------------------------------------------- /C++/12. Labs & Tasks/Tasks(17-05-19)/DSA task 17-05-19.cpp: -------------------------------------------------------------------------------- 1 | //Task 17-05-19 2 | //Finding factorial of a number 3 | // 1-> using loop 4 | // 2-> using recursion 5 | 6 | //using loop 7 | //#include 8 | //using namespace std; 9 | //int main(){ 10 | // int no; 11 | // cout<<"Enter Number:"; 12 | // cin>>no; 13 | // int fact=1; 14 | // for(int i=no;i>0;i--){ 15 | // fact=fact*i; 16 | // } 17 | // cout< 24 | using namespace std; 25 | 26 | int fact(int n){ 27 | //base condition 28 | if(n<=1) 29 | return 1; 30 | else 31 | return n*fact(n-1); 32 | } 33 | 34 | int main(){ 35 | 36 | int n; 37 | cout<<"enter no:"; 38 | cin>>n; 39 | fact(n); 40 | cout<<"Factorial:"< 47 | //using namespace std; 48 | // 49 | //int count(int n){ 50 | // if(n==1) 51 | // return 1; 52 | // else 53 | // return n+count(n-1); 54 | //} 55 | // 56 | //int main(){ 57 | //cout<<"Sum="< 2 | using namespace std; 3 | /* 4 | Question: 5 | Write a function that takes an unsigned integer and return the number of '1' bits it has. 6 | */ 7 | int main() 8 | { 9 | int t; 10 | cin>>t; 11 | while(t--) 12 | { 13 | int n; 14 | cin>>n; 15 | int count=0; 16 | while(n>0) 17 | { 18 | count++; 19 | n=n&(n-1); 20 | } 21 | cout<<"Number of Set bits: "< 2 | using namespace std; 3 | #define w(x) int x; cin>>x; while(x--); 4 | /* 5 | Question: 6 | Suzie came over to Monk's place today with a box of Monk's favorite cookies! But Monk has to play a game with her in order to win the cookies. 7 | Suzie takes out N balls from her bag, each ball having an integer on it. All the integers are 32-bit. She places all these balls in a box and closes it. The game starts by Monk choosing an integer from 0 to 31, representing a bit position. It is called as Monk's chosen bit. Post this, Suzie draws 1 balls from the box randomly and notes the integers on them. The rule is simple, Monk wins if Monk's chosen bit is set in the binary representation of the drawn ball. Help Monk choose a bit that maximizes his probability of winning the game! If there are multiple bit positions having the same probability, choose the smallest one. 8 | Input: 9 | The first line consists of an integer T. T testcases follow. The first line of each testcase consists of an integer N. 10 | In next N lines, each line will contain 1 integer denoting the integers on the ball. 11 | Output: 12 | For each testcase, print the answer in a single line. 13 | Constraints: 14 | SAMPLE INPUT 15 | 1 16 | 4 17 | 2 18 | 4 19 | 2 20 | 8 21 | SAMPLE OUTPUT 22 | 1 23 | Explanation 24 | He chooses the bit at position 1. 25 | */ 26 | int main() 27 | { 28 | int T; 29 | cin>>T; 30 | int arr[32]; 31 | while(T--) 32 | { 33 | int n; 34 | cin>>n; 35 | for(int i=0;i<32;i++) 36 | { 37 | arr[i]=0; 38 | } 39 | int x; 40 | for(int i=1;i<=n;i++) 41 | { 42 | cin>>x; 43 | for(int j=0;j<32;j++) 44 | { 45 | if(x & (1< 2 | using namespace std; 3 | /*Question: check if an integer is power of two or not*/ 4 | bool isPowerOf2(int n){ 5 | if(n==0) 6 | return false; 7 | if((n&(n-1))==0) 8 | return true; 9 | return false; 10 | } 11 | int main() 12 | { 13 | int T; 14 | cin>>T; 15 | while(T--) 16 | { 17 | int n; 18 | cin>>n; 19 | cout< 2 | using namespace std; 3 | #define REP(i,n) for (int i=1;i<=n;i++) 4 | #define w(x) int x; cin>>x; while(x--) 5 | /*Question: 6 | Suzie came over to Monk's place today with a box of Monk's favorite cookies! But Monk has to play a game with her in order to win the cookies. 7 | Suzie takes out N balls from her bag, each ball having an integer on it. All the integers are 32-bit. She places all these balls in a box and closes it. The game starts by Monk choosing an integer from 0 to 31, representing a bit position. It is called as Monk's chosen bit. Post this, Suzie draws 1 balls from the box randomly and notes the integers on them. The rule is simple, Monk wins if Monk's chosen bit is set in the binary representation of the drawn ball. Help Monk choose a bit that maximizes his probability of winning the game! If there are multiple bit positions having the same probability, choose the smallest one. 8 | Input: 9 | The first line consists of an integer T. T testcases follow. The first line of each testcase consists of an integer N. 10 | In next N lines, each line will contain 1 integer denoting the integers on the ball. 11 | Output: 12 | For each testcase, print the answer in a single line. 13 | Constraints: 14 | SAMPLE INPUT 15 | 1 16 | 4 17 | 2 18 | 4 19 | 2 20 | 8 21 | SAMPLE OUTPUT 22 | 1 23 | Explanation 24 | He chooses the bit at position 1. 25 | */ 26 | int main() 27 | { 28 | w(t) 29 | { 30 | int n; 31 | cin>>n; 32 | int arr[n]; 33 | REP(i,n) cin>>arr[i]; 34 | int cnt; 35 | int res=0; 36 | for(int i=1;i<=n;i++) 37 | { 38 | cnt=(i) * (n-i+1); 39 | if(cnt%2) res^=arr[i]; 40 | } 41 | cout< 2 | using namespace std; 3 | #define w(x) int x; cin>>x; while(x--); 4 | /* 5 | Question: 6 | Given an array arr[] of N integers, the task is to find the sum of all the pairs possible from the given array. Note that, 7 | (arr[i], arr[i]) is also considered as a valid pair. 8 | (arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs. 9 | Examples: 10 | Input: arr[] = {1, 2} 11 | Output: 12 12 | All valid pairs are (1, 1), (1, 2), (2, 1) and (2, 2). 13 | 1 + 1 + 1 + 2 + 2 + 1 + 2 + 2 = 12 14 | Input: arr[] = {1, 2, 3, 1, 4} 15 | Output: 110 16 | */ 17 | int main() 18 | { 19 | int n,m,res; 20 | w(t) 21 | { 22 | cin>>n; 23 | vectorvect; 24 | for(int i=1;i<=n;i++) 25 | { 26 | cin>>vect[i]; 27 | } 28 | for(int i=0;i<31;i++) 29 | { 30 | int cntZ=0, cnt1=0; 31 | 32 | for(int j=1;j<=n;j++) 33 | { 34 | if(vect[j] & (1<< i)) 35 | cnt1++; 36 | else 37 | cntZ++; 38 | } 39 | int p=cntZ*cnt1; 40 | 41 | res+=(1< 2 | using namespace std; 3 | int main() 4 | { 5 | int T; 6 | cin>>T; 7 | while(T--) 8 | { 9 | int N; 10 | cin>>N; 11 | int arr[N]; 12 | for(int i=0;i>arr[i]; 15 | } 16 | int x=arr[0]; 17 | for(int i=1;i 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | int n,i; 10 | cin>>n>>i; 11 | //F=00000001 left shift F by i times and perform AND operation with N, if the result is 0 the the ith bit is not set else the ith bit is set 12 | int f=1; 13 | f=f< 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | int n,i; 10 | cin>>n>>i; 11 | //Left shift n by i bits i.e mutiplying n by 2^i 12 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int t; 6 | cin>>t; 7 | while(t--) 8 | { 9 | int n,i; 10 | cin>>n>>i; 11 | //Right shift n by i bits i.e n=n/(2^i) 12 | cout<>"<>i)< 2 | using namespace std; 3 | #define pb push_back 4 | #define vi vector 5 | #define setbits(x) __builtin_popcountll(x) 6 | #define w(x) int x; cin>>x; while(x--) 7 | vi vect; 8 | int main() 9 | { 10 | w(t) 11 | { 12 | int n; 13 | cin>>n; 14 | for(int i=0;i<=n;i++) 15 | { 16 | vect.pb(setbits(i)); 17 | } 18 | for(auto i:vect) 19 | { 20 | cout< 2 | using namespace std; 3 | /*Question: given an integer.check if it's power of two or not*/ 4 | int main() 5 | { 6 | int t; 7 | cin>>t; 8 | while(t--) 9 | { 10 | int n; 11 | cin>>n; 12 | if(n<=0) 13 | cout< 2 | using namespace std; 3 | #define w(x) int x; cin>>x; while(x--) 4 | /*Question: Given an array of n integers, find the sum of xor of all pairs of numbers in the array. 5 | Examples : 6 | Input : arr[] = {7, 3, 5} 7 | Output : 12 8 | 7 ^ 3 = 4 9 | 3 ^ 5 = 6 10 | 7 ^ 5 = 2 11 | Sum = 4 + 6 + 2 12 | = 12 13 | Input : arr[] = {5, 9, 7, 6} 14 | Output : 47 15 | 5 ^ 9 = 12 16 | 9 ^ 7 = 14 17 | 7 ^ 6 = 1 18 | 5 ^ 7 = 2 19 | 5 ^ 6 = 3 20 | 9 ^ 6 = 15 21 | Sum = 12 + 14 + 1 + 2 + 3 + 15 22 | = 47 23 | */ 24 | int main() 25 | { 26 | w(t) 27 | { 28 | int n; 29 | cin>>n; 30 | int res=0; 31 | for(int i=0;i>m; 35 | res^=2*m; 36 | } 37 | cout< 2 | using namespace std; 3 | /* 4 | Question: Given integers n and k check if kth bit in n is set or not? 5 | */ 6 | bool Kthset(int n,int k){ 7 | if(n&(1<<(k-1))!=0) 8 | return true; 9 | return false; 10 | } 11 | int main() 12 | { 13 | int T; 14 | cin>>T; 15 | while(T--) 16 | { 17 | long long int n,k; 18 | cin>>n>>k; 19 | cout< 2 | using namespace std; 3 | #define w(x) int x; cin>>x; while(x--) 4 | /* 5 | Question: minimum number of flips required to make A OR B equal C 6 | */ 7 | int minFlips(int a,int b,int c) 8 | { 9 | //check if ith bit is set or not 10 | int res=0,count=0; 11 | for(int i=0;i<=31;i++) 12 | { 13 | bool x=false, y=false, z=false; 14 | //check if ith bit is set or not 15 | if(a & (1<>a>>b>>c; 42 | cout< 19 | using namespace std; 20 | 21 | class Node { 22 | public: 23 | int info; 24 | Node *next; 25 | 26 | //Constructor 27 | Node(int i, Node *p = 0) { 28 | info = i; 29 | next = p; 30 | } 31 | }; 32 | 33 | class SLinkedList { 34 | private: 35 | Node *head, *tail; 36 | public: 37 | //Constructor 38 | SLinkedList() { 39 | head = tail = 0; 40 | } 41 | 42 | //add to tail 43 | void addToTail(int i) { 44 | if (tail == 0) { 45 | head = tail = new Node(i); 46 | } 47 | else { 48 | tail->next = new Node(i); 49 | tail = tail->next; 50 | } 51 | } 52 | 53 | //Add to head 54 | 55 | void addToHead(int i) { 56 | if (head == 0) { 57 | head = tail = new Node(i); 58 | } 59 | else { 60 | Node *temp; 61 | temp = new Node(i); 62 | temp->next = head; 63 | head = temp; 64 | } 65 | } 66 | 67 | //Reversing a singly linked list 68 | 69 | void reverseList() { 70 | //No Node 71 | if (head == 0) { 72 | cout << "Empty list" << endl; 73 | cout << "No node to reverse" << endl; 74 | } 75 | //One Node or more than one Node 76 | else { 77 | Node *current; 78 | Node *prev; 79 | Node *next; //local pointer don't confuse it with next pointer that is declared as public in Node class. 80 | 81 | current = head; 82 | prev = NULL; 83 | next = NULL; 84 | 85 | //traverse the list 86 | while (current != NULL) { 87 | //store next 88 | next = current->next; 89 | 90 | //Reverse current's node pointer 91 | current->next = prev; 92 | 93 | //move pointers one position ahead 94 | prev = current; 95 | current = next; 96 | } 97 | 98 | head = prev; 99 | } 100 | } 101 | 102 | //display list 103 | 104 | void print() { 105 | Node *temp; 106 | temp = head; 107 | while (temp!= NULL) { 108 | cout << temp->info << " "; 109 | temp = temp->next; 110 | } 111 | cout << endl << endl; 112 | } 113 | 114 | }; 115 | 116 | int main() { 117 | 118 | SLinkedList list; 119 | 120 | //when there is no node 121 | 122 | cout << "When there is no node in List:" << endl; 123 | list.reverseList(); 124 | list.print(); 125 | 126 | //when there is only one node 127 | 128 | cout << "When there is only one node in List:" << endl; 129 | list.addToHead(5); 130 | cout << "List in Actual Order:" << endl; 131 | list.print(); 132 | cout << "List in Reverse Order:" << endl; 133 | list.reverseList(); 134 | list.print(); 135 | 136 | //when there are more than one nodes in list. 137 | 138 | cout << "When there are more than one nodes in List:" << endl; 139 | list.addToTail(10); 140 | list.addToTail(15); 141 | list.addToTail(20); 142 | list.addToTail(25); 143 | list.addToHead(10); 144 | list.addToHead(20); 145 | list.addToHead(30); 146 | list.addToTail(40); 147 | cout << "\n\n"<<"List in Actual Order:" << endl; 148 | list.print(); 149 | cout << "\n\n" << "List in Reverse Order:" << endl; 150 | list.reverseList(); 151 | list.print(); 152 | system("pause"); 153 | return 0; 154 | } 155 | -------------------------------------------------------------------------------- /C++/2-Singly Linked List/6-Removing Duplicates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode() : val(0), next(nullptr) {} 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplicates(ListNode* head) { 14 | // base case 15 | if(!head || !head->next){ 16 | return head; 17 | } 18 | ListNode *dummy = new ListNode(0); 19 | dummy->next = head; 20 | ListNode *current = head; 21 | ListNode *prev = dummy; 22 | 23 | while(current!=nullptr && current->next!=nullptr){ 24 | if(current->val == current->next->val){ 25 | int match = current->val; 26 | while(current!=nullptr && current->val == match){ 27 | current = current->next; 28 | } 29 | prev->next = current; 30 | 31 | } 32 | else{ 33 | prev = current; 34 | current = current->next; 35 | } 36 | } 37 | ListNode *newHead = dummy->next; 38 | delete dummy; 39 | return newHead; 40 | } 41 | }; 42 | 43 | 44 | 45 | int main() { 46 | // Create a sample linked list with duplicates 47 | ListNode* head = new ListNode(1); 48 | head->next = new ListNode(1); 49 | head->next->next = new ListNode(2); 50 | head->next->next->next = new ListNode(3); 51 | head->next->next->next->next = new ListNode(3); 52 | 53 | // Print the original linked list 54 | std::cout << "Original Linked List: "; 55 | ListNode* current = head; 56 | while (current != nullptr) { 57 | std::cout << current->val << " "; 58 | current = current->next; 59 | } 60 | std::cout << std::endl; 61 | 62 | // Call the deleteDuplicates function to remove duplicates 63 | Solution solution; 64 | ListNode* newHead = solution.deleteDuplicates(head); 65 | 66 | // Print the modified linked list without duplicates 67 | std::cout << "Modified Linked List: "; 68 | current = newHead; 69 | while (current != nullptr) { 70 | std::cout << current->val << " "; 71 | current = current->next; 72 | } 73 | std::cout << std::endl; 74 | 75 | current = newHead; 76 | while (current != nullptr) { 77 | ListNode* temp = current; 78 | current = current->next; 79 | delete temp; 80 | } 81 | 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /C++/5-Stack/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShehrozIrfan/learn-dsa/bcd65a9ee2c6fb4dcfc769d97b2eddd56c05db0a/C++/5-Stack/.DS_Store -------------------------------------------------------------------------------- /C++/5-Stack/1-Stack(Array Implementation)/1-Stack(Array Implementation).cpp: -------------------------------------------------------------------------------- 1 | //Array implementation of stack 2 | 3 | #include 4 | using namespace std; 5 | 6 | //maximum size of array 7 | #define SIZE 100 8 | 9 | class MyStack{ 10 | private: 11 | int top; 12 | int st[SIZE]; 13 | public: 14 | //constructor 15 | MyStack() { 16 | top = -1; 17 | } 18 | 19 | //check stack is empty or not 20 | bool isEmpty() { 21 | if (top == -1) 22 | return true; 23 | else 24 | return false; 25 | } 26 | 27 | //inserting an element on the top of stack 28 | void push(int x) { 29 | if (top == SIZE - 1) { 30 | cout << "Error: Stack Overflow" << endl; 31 | } 32 | else { 33 | top = top + 1; 34 | st[top] = x; 35 | } 36 | } 37 | 38 | //removing an element from the top of stack 39 | int pop() { 40 | if (top == -1) { 41 | cout << "Error: No element to pop" << endl; 42 | } 43 | return st[top--]; 44 | } 45 | 46 | //returns the current top of stack 47 | int topOfStack() { 48 | return st[top]; 49 | } 50 | //display stack 51 | void display() { 52 | cout << "StacK: "; 53 | for (int c = 0; c <= top; c++) { 54 | cout << st[c] << " "; 55 | } 56 | cout << endl; 57 | } 58 | }; 59 | 60 | 61 | int main() { 62 | 63 | MyStack s; 64 | if (s.isEmpty()) 65 | cout << "Stack is empty" << endl; 66 | else 67 | cout << "Stack is not empty" << endl; 68 | s.push(2); 69 | s.display(); 70 | s.push(8); 71 | s.display(); 72 | s.push(1); 73 | s.display(); 74 | s.push(66); 75 | s.display(); 76 | s.push(77); 77 | s.display(); 78 | s.push(22); 79 | s.display(); 80 | s.push(55); 81 | s.display(); 82 | s.pop(); 83 | s.display(); 84 | cout << "Top of stack is:"; 85 | cout << s.topOfStack()< 5 | using namespace std; 6 | 7 | class Node { 8 | public: 9 | int info; 10 | Node *next; 11 | //constructor 12 | Node(int i, Node *p = 0) { 13 | info = i; 14 | next = p; 15 | } 16 | }; 17 | 18 | class MyStack { 19 | private: 20 | Node *top; 21 | public: 22 | //constructor 23 | MyStack() { 24 | top = 0; 25 | } 26 | 27 | bool isEmpty(); 28 | void push(int i); 29 | void pop(); 30 | void display(); 31 | int topOfStack(); 32 | }; 33 | 34 | //check stack is empty or not 35 | bool MyStack::isEmpty() { 36 | if (top == 0) 37 | return true; 38 | else 39 | return false; 40 | } 41 | 42 | //push element in a stack 43 | void MyStack::push(int i) { 44 | //if stack is empty 45 | if (top == 0) { 46 | top = new Node(i); 47 | } 48 | //if stack is not empty 49 | else { 50 | Node *temp; 51 | temp = new Node(i); 52 | temp->next = top; 53 | top = temp; 54 | } 55 | } 56 | 57 | //pop element from a stack 58 | void MyStack::pop() { 59 | //if stack is empty 60 | if (top == 0) { 61 | cout << "Error: empty Stack nothing to delete" << endl; 62 | } 63 | //if stack contains only one element 64 | else if(top->next==0) { 65 | delete top; 66 | top = NULL; 67 | } 68 | //if stack contains more than one element 69 | else { 70 | Node *temp; 71 | temp = top; 72 | top = top->next; 73 | delete temp; 74 | } 75 | } 76 | 77 | //display stack 78 | void MyStack::display() { 79 | //when stack is empty 80 | if (top == 0) { 81 | cout << "Empty Stack" << endl; 82 | } 83 | //when stack contains only one element 84 | else if (top->next== 0) { 85 | cout << "Stack is:"; 86 | cout << top->info << endl; 87 | } 88 | //when stack contains more than one element 89 | else { 90 | Node *temp; 91 | temp = top; 92 | cout << "Stack is:"; 93 | while (temp!= 0) { 94 | cout << temp->info << " "; 95 | temp = temp->next; 96 | } 97 | cout << endl; 98 | } 99 | } 100 | 101 | //returns the current top of stack 102 | int MyStack::topOfStack(){ 103 | 104 | return top->info; 105 | } 106 | 107 | 108 | int main() { 109 | MyStack s; 110 | if (s.isEmpty()) 111 | cout << "Stack is empty" << endl; 112 | else 113 | cout << "Stack is not empty" << endl; 114 | s.push(10); 115 | s.push(30); 116 | s.push(20); 117 | s.push(40); 118 | s.display(); 119 | s.pop(); 120 | s.display(); 121 | cout << "Current top of stack is:"; 122 | cout< 27 | using namespace std; 28 | 29 | //maximum size of array 30 | #define SIZE 100 31 | 32 | class MyStack { 33 | private: 34 | int top; 35 | int st[SIZE]; 36 | public: 37 | //constructor 38 | MyStack() { 39 | top = -1; 40 | } 41 | 42 | //check stack is empty or not 43 | bool isEmpty() { 44 | if (top == -1) 45 | return true; 46 | else 47 | return false; 48 | } 49 | 50 | //inserting an element on the top of stack 51 | void push(int x) { 52 | if (top == SIZE - 1) { 53 | cout << "Error: Queue Overflow" << endl; 54 | } 55 | else { 56 | top = top + 1; 57 | st[top] = x; 58 | } 59 | } 60 | 61 | //removing an element from the top of stack 62 | int pop() { 63 | if (top == -1) { 64 | cout << "Error: No element to pop" << endl; 65 | } 66 | return st[top--]; 67 | } 68 | 69 | //returns the current top of stack 70 | int topOfStack() { 71 | return st[top]; 72 | } 73 | 74 | //checks whether the stack is full or not 75 | bool isFull() 76 | { 77 | return top == SIZE - 1; 78 | } 79 | 80 | //display stack 81 | void display() { 82 | for (int c = 0; c <= top; c++) { 83 | cout << st[c] << " "; 84 | } 85 | cout << endl; 86 | } 87 | }; 88 | 89 | class Queue { 90 | private: 91 | //we made two stacks 92 | MyStack s1, s2; 93 | public: 94 | 95 | //inserting a value in queue 96 | void enQueue(int val) 97 | { 98 | if (s1.isFull()) { 99 | cout << "Queue is Full. Can't be insrted" << endl; 100 | } 101 | else { 102 | //we use the push method of MyStack class. 103 | s1.push(val); 104 | } 105 | } 106 | 107 | //removing a value from one stack and placing it in other stack and then we get out our desired value and again push the values in first stack 108 | int deQueue() { 109 | if (s1.isEmpty()) { 110 | cout << "Queue is Empty. Can`t be Dequed" << endl; 111 | } 112 | else { 113 | //while s1 is not empty pop the values from s1 and push in s2. 114 | while (!s1.isEmpty()) { 115 | s2.push(s1.pop()); 116 | } 117 | 118 | //we get our desired value that is not on the top of s2. 119 | int val = s2.pop(); 120 | 121 | //pushing the values back to s1 122 | //while s2 is not empty pop values from s2 and push in s1 123 | while (!s2.isEmpty()) { 124 | s1.push(s2.pop()); 125 | } 126 | 127 | //returns our desired value 128 | return val; 129 | 130 | } 131 | } 132 | 133 | //to check s1 is empty or not 134 | bool isEmpty() { 135 | return s1.isEmpty(); 136 | } 137 | 138 | //display queue 139 | void displayQueue() { 140 | cout << "Displaying Queue values:" << endl; 141 | s1.display(); 142 | } 143 | }; 144 | int main() { 145 | 146 | Queue myQueue; 147 | myQueue.enQueue(2); 148 | myQueue.enQueue(5); 149 | myQueue.enQueue(12); 150 | myQueue.displayQueue(); 151 | 152 | myQueue.deQueue(); 153 | myQueue.displayQueue(); 154 | 155 | system("pause"); 156 | return 0; 157 | } 158 | -------------------------------------------------------------------------------- /C++/5-Stack/3-Imp Problem(Interview)/parenthesesCheck.cpp: -------------------------------------------------------------------------------- 1 | /*************************************************************************** 2 | * 3 | * In this problem, we are required to check for balanced parantheses check 4 | * When we say parentheses, we mean pairs of (), {} and [] 5 | * For balancing of parentheses, the last opened one should be closed first 6 | * For example, (), {}, [], {() ()}, [{()}()] are balanced 7 | * However, [(]), {[()} are not balanced 8 | * 9 | ****************************************************************************/ 10 | 11 | #include 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | stack S; 17 | 18 | bool pairsWithTop(char x) 19 | { 20 | if (S.top() == '(' && x == ')') 21 | return true; 22 | else if (S.top() == '[' && x == ']') 23 | return true; 24 | else if (S.top() == '{' && x == '}') 25 | return true; 26 | else 27 | return false; 28 | } 29 | 30 | bool balancedParantheses(char exp[]) 31 | { 32 | int n = strlen(exp); 33 | for (int i = 0; i < n; i++) 34 | { 35 | if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') 36 | { 37 | S.push(exp[i]); 38 | } 39 | else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']') 40 | { 41 | if (S.empty() || !pairsWithTop(exp[i])) 42 | { 43 | return false; 44 | } 45 | else 46 | { 47 | S.pop(); 48 | } 49 | } 50 | } 51 | return (S.empty()) ? true : false; 52 | } 53 | 54 | int main() 55 | { 56 | char exp[101]; 57 | cin >> exp; 58 | if (balancedParantheses(exp)) 59 | cout << "Balanced\n"; 60 | else 61 | cout << "Imbalanced\n"; 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /C++/6-Recursion/1-sum of first n positive numbers.cpp: -------------------------------------------------------------------------------- 1 | //write a recursion function that will return sum of first n positive integers. 2 | #include 3 | using namespace std; 4 | 5 | int sum(int n) { 6 | if (n == 1) 7 | return 1; 8 | else 9 | return n + sum(n - 1); 10 | } 11 | 12 | int main() { 13 | int num; 14 | cout << "Enter a positive number:"; 15 | cin >> num; 16 | if (num > 0) 17 | cout << "Sum of first " << num << " numbers is : " << sum(num) << endl; 18 | else 19 | cout << "Invalid input!!" << endl; 20 | system("pause"); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /C++/6-Recursion/2-sum of squares of n numbers.cpp: -------------------------------------------------------------------------------- 1 | //Write a recursive function that returns the sum of the squares of the first n positive integers. 2 | 3 | #include 4 | using namespace std; 5 | 6 | int sumOfSquares(int n) { 7 | if (n == 1) 8 | return 1; 9 | else 10 | return (n*n) + sumOfSquares(n - 1); 11 | } 12 | 13 | int main() { 14 | int num; 15 | cout << "Enter a positive number: "; 16 | cin >> num; 17 | if (num > 0) 18 | cout << "Sum of the squares of the first " << num << " integers is: " << sumOfSquares(num) << endl; 19 | else 20 | cout << "Invalid Input!!" << endl; 21 | 22 | system("pause"); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /C++/6-Recursion/3-recursion that returns power.cpp: -------------------------------------------------------------------------------- 1 | //Write a recursive function that returns the power a^n. 2 | #include 3 | using namespace std; 4 | 5 | int findPower(int b,int p) { 6 | if (p == 0) 7 | return 1; 8 | else 9 | return (b * findPower(b, p - 1)); 10 | } 11 | 12 | int main() { 13 | int base, power; 14 | cout << "Enter base:"; 15 | cin >> base; 16 | cout << "Enter power:"; 17 | cin >> power; 18 | cout << base << "^" << power << " is : " << findPower(base, power) << endl; 19 | 20 | system("pause"); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /C++/6-Recursion/4-Factorial of a number.cpp: -------------------------------------------------------------------------------- 1 | //Write a recursive function to calculate the factorial of a number a! 2 | 3 | #include 4 | using namespace std; 5 | 6 | int factorial(int n) { 7 | if (n == 1) 8 | return 1; 9 | else 10 | return n * factorial(n - 1); 11 | } 12 | int main() { 13 | int n; 14 | cout << "Enter a number: "; 15 | cin >> n; 16 | if (n > 0) 17 | cout << "Factorial of " << n << " is: " << factorial(n) << endl; 18 | else 19 | cout << "Invalid Input!!" << endl; 20 | system("pause"); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /C++/6-Recursion/5-Maximum in array using recursion.cpp: -------------------------------------------------------------------------------- 1 | //recursive function that returns the maximum among the n elements of an integer array. 2 | 3 | #include 4 | using namespace std; 5 | 6 | //function that returns maximum of two numbers. 7 | int max(int x, int y) { 8 | return (x > y) ? x : y; 9 | } 10 | //function to find maximum in an array using recursion 11 | int maxRec(int A[], int n) { 12 | if (n == 1) 13 | return A[0]; 14 | else 15 | return max(A[n - 1], maxRec(A, n - 1)); 16 | } 17 | int main() { 18 | int size; 19 | cout << "How many values you wanna enter:"; 20 | cin >> size; 21 | int *A = new int[size]; 22 | cout << "Enter " << size << " values in array: " << endl; 23 | for (int i = 0; i < size; i++) 24 | cin >> A[i]; 25 | 26 | cout << "Maximum value in Array is: " << maxRec(A, size) << endl; 27 | 28 | delete[] A; 29 | 30 | system("pause"); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /C++/6-Recursion/Recursion Practice Exercises.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShehrozIrfan/learn-dsa/bcd65a9ee2c6fb4dcfc769d97b2eddd56c05db0a/C++/6-Recursion/Recursion Practice Exercises.pdf -------------------------------------------------------------------------------- /C++/6-Recursion/Recursion Practice exercise.txt: -------------------------------------------------------------------------------- 1 | Trace the following recursive functions using paper and pencil and also determine their output(s). 2 | 3 | Trace it with print(6); 4 | void print(int n) 5 | { 6 | if (n > 1) 7 | { 8 | cout << n << " "; 9 | print(n - 1); 10 | cout << n << " "; 11 | } 12 | } 13 | 14 | Answer: 6 5 4 3 2 2 3 4 5 6 15 | 16 | 17 | Trace it with foo(99); 18 | int foo(int n) 19 | { 20 | if (n > 100) 21 | return n - 10; 22 | return foo( foo(n + 11) ); 23 | } 24 | 25 | Answer: 91 26 | 27 | Trace it with int x = 15; bar(5, &x); 28 | int bar( int n, int *p ) 29 | { 30 | int t, f; 31 | if ( n <= 1 ) 32 | { 33 | *p = 1; 34 | return 1; 35 | } 36 | t = bar ( n - 1, p ); 37 | f = t + *p; 38 | *p = t; 39 | return f; 40 | } 41 | 42 | Answer: 8 -------------------------------------------------------------------------------- /C++/7-Queue/1-Circular Queue(Array Implementation).cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShehrozIrfan/learn-dsa/bcd65a9ee2c6fb4dcfc769d97b2eddd56c05db0a/C++/7-Queue/1-Circular Queue(Array Implementation).cpp -------------------------------------------------------------------------------- /C++/7-Queue/2-Queue(LinkedList Implementation).cpp: -------------------------------------------------------------------------------- 1 | //Linked List implementation of Queue 2 | //Here we enQueue at tail(rear) means we insert a new node at tail(rear) 3 | //Here we deQueue from head(front) means we delete a node from head(front) 4 | 5 | #include 6 | using namespace std; 7 | 8 | class Node { 9 | public: 10 | int info; 11 | Node *next; 12 | //constructor 13 | Node(int i, Node *p = NULL) { 14 | info = i; 15 | next = p; 16 | } 17 | }; 18 | 19 | class MyQueue { 20 | private: 21 | Node *front, *rear; 22 | public: 23 | //constructor 24 | MyQueue() { 25 | front = rear = NULL; 26 | } 27 | 28 | bool isEmpty(); 29 | void enQueue(int i); 30 | int deQueue(); 31 | int frontOfQueue(); 32 | int rearOfQueue(); 33 | void displayQueue(); 34 | }; 35 | 36 | //check queue is empty or not 37 | bool MyQueue::isEmpty() { 38 | if (front == NULL) 39 | return true; 40 | else 41 | return false; 42 | } 43 | 44 | //inserting a node at rear of queue 45 | void MyQueue::enQueue(int i) { 46 | //when the queue is empty 47 | if (isEmpty()) 48 | front = rear = new Node(i); 49 | //when queue is not empty 50 | else { 51 | Node *temp; 52 | temp = new Node(i); 53 | rear->next = temp; 54 | rear = temp; 55 | } 56 | } 57 | 58 | //deleting a node from fornt of queue 59 | int MyQueue::deQueue() { 60 | //when queue is empty 61 | if (isEmpty()) { 62 | cout << "Error: Empty Queue. Can't delete" << endl; 63 | return 0; 64 | } 65 | //when queue contains only one node 66 | else if (front == rear) 67 | front = rear = NULL; 68 | //when queue contains more than one nodes 69 | else { 70 | Node *temp; 71 | temp = front; 72 | front = temp->next; 73 | delete temp; 74 | } 75 | } 76 | 77 | //it returns current front of queue 78 | int MyQueue::frontOfQueue() { 79 | if (isEmpty()) 80 | return 0; 81 | else 82 | return front->info; 83 | } 84 | 85 | //it returns rear of queue 86 | int MyQueue::rearOfQueue() { 87 | if(isEmpty()) 88 | return 0; 89 | else 90 | return rear->info; 91 | } 92 | 93 | //display queue 94 | void MyQueue::displayQueue() { 95 | //when queue is empty 96 | if (isEmpty()) 97 | cout << "Empty Queue.Nothing to display" << endl; 98 | //when queue contains only one node 99 | else if (front == rear) { 100 | cout << "Queue is:"; 101 | cout << front->info << endl; 102 | } 103 | //when queue contains more than one nodes 104 | else { 105 | Node *temp = front; 106 | cout << "Queue is:"; 107 | while (temp != NULL) { 108 | cout << temp->info << " "; 109 | temp = temp->next; 110 | } 111 | cout << endl; 112 | delete temp; 113 | } 114 | cout< 4 | using namespace std; 5 | 6 | //when a node is created it will have three things: 7 | // 1. data(when a new node is created it has its value as data) 8 | // 2. left child(when a new node is created it is NULL) 9 | // 3. right child(when a new node is created it is NULL) 10 | class Node { 11 | public: 12 | //data will have the value that the node has 13 | int data; 14 | //left child stores the address of left child 15 | Node *leftChild; 16 | //right child stores the address of right child 17 | Node *rightChild; 18 | 19 | //Paremeterized constructor which initialize all the data members of class Node to 0 and NULL. 20 | Node(int d = 0, Node *left = NULL, Node *right = NULL) { 21 | data = d; 22 | leftChild = left; 23 | rightChild = right; 24 | } 25 | }; 26 | 27 | //This is a Global Pointer. we declare it gloabal because when we do pre , post or in order traversal we have to pass root as a argument from main when 28 | // we call these functions. that's why we declare it global. 29 | Node *root=NULL; 30 | 31 | class BST { 32 | public: 33 | 34 | //the definitions of all these functions is outside the class. 35 | int insert(int d); 36 | void preOrderTraversal(Node *root); 37 | void inOrderTraversal(Node *root); 38 | void postOrderTraversal(Node *root); 39 | }; 40 | 41 | //insert function is used to insert a new node in a tree. 42 | int BST::insert(int d) { 43 | //tempNode is a pointer which always has address of new node that is created. 44 | Node *tempNode = new Node(d); 45 | Node *parent = NULL; 46 | Node *current = NULL; 47 | 48 | if (root == NULL) { 49 | root = tempNode; 50 | } 51 | else { 52 | current = root; 53 | parent = NULL; 54 | 55 | while (1) { 56 | parent = current; 57 | //in BST value of all the nodes in left subtree is lesser or equal 58 | if (tempNode->data <= parent->data) { 59 | current = current->leftChild; 60 | if (current == NULL) { 61 | parent->leftChild = tempNode; 62 | return 0; 63 | } 64 | } 65 | //in BST value of all the nodes in right subtree is greater. 66 | else { 67 | current = current->rightChild; 68 | if (current == NULL) { 69 | parent->rightChild = tempNode; 70 | return 0; 71 | } 72 | } 73 | } 74 | } 75 | } 76 | 77 | //in pre order traversal first root node is printed then left subtree and then right subtree is printed and it is true for all the nodes. 78 | void BST::preOrderTraversal(Node *root) { 79 | 80 | if (root != NULL) { 81 | cout << root->data<<" "; 82 | //here we use recursion 83 | preOrderTraversal(root->leftChild); 84 | preOrderTraversal(root->rightChild); 85 | } 86 | 87 | } 88 | 89 | //in "in order" traversal first left subtree is printed then the root node is printed and then right subtree is printed and is true for all the nodes. 90 | void BST::inOrderTraversal(Node *root) { 91 | 92 | if (root != NULL) { 93 | //here we use recursion 94 | inOrderTraversal(root->leftChild); 95 | cout << root->data << " "; 96 | inOrderTraversal(root->rightChild); 97 | } 98 | 99 | } 100 | 101 | //in post order traversal first left subtree is printed and then right subtree is printed and then root node is printed and is true for all the nodes. 102 | void BST::postOrderTraversal(Node *root) { 103 | 104 | if (root != NULL) { 105 | //here we use recursion 106 | postOrderTraversal(root->leftChild); 107 | postOrderTraversal(root->rightChild); 108 | cout << root->data << " "; 109 | } 110 | 111 | } 112 | 113 | int main() { 114 | BST t; 115 | t.insert(5); 116 | t.insert(4); 117 | t.insert(7); 118 | t.insert(6); 119 | t.insert(0); 120 | 121 | cout << "Pre Order Traversal is :" << " "; 122 | t.preOrderTraversal(root); 123 | cout << "\n\n"; 124 | 125 | cout << "In Order Traversal is :" << " "; 126 | t.inOrderTraversal(root); 127 | cout << "\n\n"; 128 | 129 | cout << "Post Order Traversal is :" << " "; 130 | t.postOrderTraversal(root); 131 | cout << "\n\n"; 132 | 133 | system("pause"); 134 | return 0; 135 | } -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/14-FullBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int key; 6 | struct Node *left, *right; 7 | }; 8 | 9 | struct Node *newNode(char k) { 10 | struct Node *node = (struct Node *)malloc(sizeof(struct Node)); 11 | node->key = k; 12 | node->right = node->left = NULL; 13 | return node; 14 | } 15 | 16 | bool isFullBinaryTree(struct Node *root) { 17 | 18 | if (root == NULL) 19 | return true; 20 | 21 | if (root->left == NULL && root->right == NULL) 22 | return true; 23 | 24 | if ((root->left) && (root->right)) 25 | return (isFullBinaryTree(root->left) && isFullBinaryTree(root->right)); 26 | 27 | return false; 28 | } 29 | 30 | int main() { 31 | struct Node *root = NULL; 32 | root = newNode(1); 33 | root->left = newNode(2); 34 | root->right = newNode(3); 35 | root->left->left = newNode(4); 36 | root->left->right = newNode(5); 37 | root->left->right->left = newNode(6); 38 | root->left->right->right = newNode(7); 39 | 40 | if (isFullBinaryTree(root)) 41 | cout << "The tree is a full binary tree\n"; 42 | else 43 | cout << "The tree is not a full binary tree\n"; 44 | } -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/2-BST(searching)/2-BST(searching).cpp: -------------------------------------------------------------------------------- 1 | //Binary Search Tree (Linked List Implementation) 2 | 3 | #include 4 | using namespace std; 5 | 6 | //when a node is created it will have three things: 7 | // 1. data(when a new node is created it has its value as data) 8 | // 2. left child(when a new node is created it is NULL) 9 | // 3. right child(when a new node is created it is NULL) 10 | class Node { 11 | public: 12 | //data will have the value that the node has 13 | int data; 14 | //left child stores the address of left child 15 | Node *leftChild; 16 | //right child stores the address of right child 17 | Node *rightChild; 18 | 19 | //Paremeterized constructor which initialize all the data members of class Node to 0 and NULL. 20 | Node(int d = 0, Node *left = NULL, Node *right = NULL) { 21 | data = d; 22 | leftChild = left; 23 | rightChild = right; 24 | } 25 | }; 26 | 27 | //This is a Global Pointer. we declare it gloabal because when we do pre , post or in order traversal we have to pass root as a argument from main when 28 | // we call these functions. that's why we declare it global. 29 | Node *root = NULL; 30 | 31 | class BST { 32 | public: 33 | 34 | //the definitions of all these functions is outside the class. 35 | int insert(int d); 36 | bool search(Node *root, int d); 37 | }; 38 | 39 | //searchin in BST 40 | bool BST::search(Node *root, int d) { 41 | //when tree is empty 42 | if (root == NULL) 43 | return false; 44 | //when the searched number is at root 45 | else if (root->data == d) 46 | return true; 47 | //when searched number is less than root->data then we go(search) to left side of tree 48 | else if (d <= root->data) { 49 | return search(root->leftChild, d); 50 | } 51 | //if searched number is greater than root->data then we go(search) to right side of tree 52 | else { 53 | return search(root->rightChild, d); 54 | } 55 | } 56 | 57 | 58 | //insert function is used to insert a new node in a tree. 59 | int BST::insert(int d) { 60 | //tempNode is a pointer which always has address of new node that is created. 61 | Node *tempNode = new Node(d); 62 | Node *parent = NULL; 63 | Node *current = NULL; 64 | 65 | if (root == NULL) { 66 | root = tempNode; 67 | } 68 | else { 69 | current = root; 70 | parent = NULL; 71 | 72 | while (1) { 73 | parent = current; 74 | //in BST value of all the nodes in left subtree is lesser or equal 75 | if (tempNode->data <= parent->data) { 76 | current = current->leftChild; 77 | if (current == NULL) { 78 | parent->leftChild = tempNode; 79 | return 0; 80 | } 81 | } 82 | //in BST value of all the nodes in right subtree is greater. 83 | else { 84 | current = current->rightChild; 85 | if (current == NULL) { 86 | parent->rightChild = tempNode; 87 | return 0; 88 | } 89 | } 90 | } 91 | } 92 | } 93 | 94 | int main() { 95 | BST t; 96 | t.insert(4); 97 | t.insert(6); 98 | t.insert(0); 99 | int num; 100 | cout << "Enter number to be searched:"; 101 | cin >> num; 102 | if (t.search(root, num)) 103 | cout < 5 | using namespace std; 6 | 7 | class Node { 8 | public: 9 | int data; 10 | Node *leftChild; 11 | Node *rightChild; 12 | //Constructor 13 | Node(int d = 0, Node *left = NULL, Node *right = NULL) { 14 | data = d; 15 | leftChild = left; 16 | rightChild = right; 17 | } 18 | }; 19 | 20 | Node *root = NULL; 21 | 22 | class BST { 23 | public: 24 | int findMin(Node *root); 25 | int findMax(Node *root); 26 | int insert(int d); 27 | }; 28 | 29 | //so to find the minimum value we go as left as possible. 30 | int BST::findMin(Node *root) { 31 | //when tree is empty 32 | if (root == NULL) { 33 | cout << "\n" << "Error: Tree is Empty" << endl; 34 | return -1; 35 | } 36 | //when tree is not empty 37 | else { 38 | while (root->leftChild != NULL) { 39 | root = root->leftChild; 40 | } 41 | return root->data; 42 | } 43 | } 44 | 45 | //to find maximum value we go as right as possible. 46 | int BST::findMax(Node *root) { 47 | //when tree is empty 48 | if (root == NULL) { 49 | cout << "\n" << "Error: Tree is Empty" << endl; 50 | return -1; 51 | } 52 | //when tree is not empty 53 | else { 54 | while (root->rightChild != NULL) { 55 | root = root->rightChild; 56 | } 57 | return root->data; 58 | } 59 | } 60 | 61 | //insert function is used to insert a new node in a tree. 62 | int BST::insert(int d) { 63 | //tempNode is a pointer which always has address of new node that is created. 64 | Node *tempNode = new Node(d); 65 | Node *parent = NULL; 66 | Node *current = NULL; 67 | 68 | if (root == NULL) { 69 | root = tempNode; 70 | } 71 | else { 72 | current = root; 73 | parent = NULL; 74 | 75 | while (1) { 76 | parent = current; 77 | //in BST value of all the nodes in left subtree is lesser or equal 78 | if (tempNode->data <= parent->data) { 79 | current = current->leftChild; 80 | if (current == NULL) { 81 | parent->leftChild = tempNode; 82 | return 0; 83 | } 84 | } 85 | //in BST value of all the nodes in right subtree is greater. 86 | else { 87 | current = current->rightChild; 88 | if (current == NULL) { 89 | parent->rightChild = tempNode; 90 | return 0; 91 | } 92 | } 93 | } 94 | } 95 | } 96 | 97 | int main() { 98 | BST t; 99 | t.insert(5); 100 | t.insert(3); 101 | t.insert(9); 102 | t.insert(2); 103 | t.insert(0); 104 | t.insert(10); 105 | t.insert(8); 106 | t.insert(7); 107 | t.insert(1); 108 | cout << "Maximum Node is:" << t.findMax(root) << endl; 109 | cout << "Minimum Node is:" << t.findMin(root) << endl; 110 | 111 | 112 | 113 | system("pause"); 114 | return 0; 115 | } -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/3-BST(Find max & min)/2-BST(Find min and max) recursively.cpp: -------------------------------------------------------------------------------- 1 | //This is a recursive method of finding min and max in BST 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Node { 7 | public: 8 | int data; 9 | Node *leftChild; 10 | Node *rightChild; 11 | //Constructor 12 | Node(int d = 0, Node *left = NULL, Node *right = NULL) { 13 | data = d; 14 | leftChild = left; 15 | rightChild = right; 16 | } 17 | }; 18 | 19 | Node *root = NULL; 20 | 21 | class BST { 22 | public: 23 | int findMin(Node *root); 24 | int findMax(Node *root); 25 | int insert(int d); 26 | }; 27 | 28 | //so to find the minimum value we go as left as possible. 29 | int BST::findMin(Node *root) { 30 | //when tree is empty 31 | if (root == NULL) { 32 | cout << "\n" << "Error: Tree is Empty" << endl; 33 | return -1; 34 | } 35 | //when tree is not empty 36 | else { 37 | //base condition for recursion 38 | if (root->leftChild == NULL) { 39 | return root->data; 40 | } 41 | //search in left subtree 42 | findMin(root->leftChild); 43 | } 44 | } 45 | 46 | //to find maximum value we go as right as possible. 47 | int BST::findMax(Node *root) { 48 | //when tree is empty 49 | if (root == NULL) { 50 | cout << "\n" << "Error: Tree is Empty" << endl; 51 | return -1; 52 | } 53 | //when tree is not empty 54 | else { 55 | //base condition for recursion 56 | if (root->rightChild == NULL) { 57 | return root->data; 58 | } 59 | //search in right subtree 60 | findMax(root->rightChild); 61 | } 62 | } 63 | 64 | //insert function is used to insert a new node in a tree. 65 | int BST::insert(int d) { 66 | //tempNode is a pointer which always has address of new node that is created. 67 | Node *tempNode = new Node(d); 68 | Node *parent = NULL; 69 | Node *current = NULL; 70 | 71 | if (root == NULL) { 72 | root = tempNode; 73 | } 74 | else { 75 | current = root; 76 | parent = NULL; 77 | 78 | while (1) { 79 | parent = current; 80 | //in BST value of all the nodes in left subtree is lesser or equal 81 | if (tempNode->data <= parent->data) { 82 | current = current->leftChild; 83 | if (current == NULL) { 84 | parent->leftChild = tempNode; 85 | return 0; 86 | } 87 | } 88 | //in BST value of all the nodes in right subtree is greater. 89 | else { 90 | current = current->rightChild; 91 | if (current == NULL) { 92 | parent->rightChild = tempNode; 93 | return 0; 94 | } 95 | } 96 | } 97 | } 98 | } 99 | 100 | int main() { 101 | BST t; 102 | t.insert(5); 103 | t.insert(3); 104 | t.insert(9); 105 | t.insert(2); 106 | t.insert(0); 107 | t.insert(10); 108 | t.insert(8); 109 | t.insert(7); 110 | t.insert(1); 111 | cout << "Maximum Node is:" << t.findMax(root) << endl; 112 | cout << "Minimum Node is:" << t.findMin(root) << endl; 113 | 114 | 115 | 116 | system("pause"); 117 | return 0; 118 | } -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/4-BST(find height)/4-BST(find height).cpp: -------------------------------------------------------------------------------- 1 | //This is code of finding Height of a binary tree. 2 | // Height of Binary tree = max of height of left subtree and right subtree +1 3 | // e.g; if height of left subtree= 2 4 | // and height of right subtree= 1 5 | // then height of tree = 2+1 (because of 2 and 1 max is 2 so 2+1=3) 6 | // e.g; if height of left subtree= 4 7 | // and height of right subtree= 5 8 | // then height of tree = 5+1 (because of 4 and 5 max is 5 so 5+1=6) 9 | 10 | #include 11 | using namespace std; 12 | 13 | class Node { 14 | public: 15 | int data; 16 | Node *leftChild; 17 | Node *rightChild; 18 | //constructor 19 | Node(int d = 0, Node *left = NULL, Node *right = NULL) { 20 | data = d; 21 | leftChild = left; 22 | rightChild = right; 23 | } 24 | }; 25 | 26 | Node *root = NULL; 27 | 28 | class BST { 29 | public: 30 | int findHeight(Node *root); 31 | int max(int x, int y); 32 | int insert(int d); 33 | }; 34 | 35 | //this is function to find maximum of two integers 36 | int BST::max(int x,int y) { 37 | return (x > y) ? x : y; 38 | } 39 | 40 | //function to find height of a tree 41 | int BST::findHeight(Node *root) { 42 | //if tree is empty then we return -1 some people return 0 also. 43 | if (root == NULL) 44 | return -1; 45 | else { 46 | //leftHeight find the height of left subtree 47 | int leftHeight = findHeight(root->leftChild); 48 | //rightHeight find the height of right subtree 49 | int rightHeight = findHeight(root->rightChild); 50 | //function call which first finds the maximum of height of left subtree and right subtree and after finding maximum value it add 1 to it and 51 | //returns 52 | return max(leftHeight, rightHeight) + 1; 53 | } 54 | } 55 | 56 | //insert function is used to insert a new node in a tree. 57 | int BST::insert(int d) { 58 | //tempNode is a pointer which always has address of new node that is created. 59 | Node *tempNode = new Node(d); 60 | Node *parent = NULL; 61 | Node *current = NULL; 62 | 63 | if (root == NULL) { 64 | root = tempNode; 65 | } 66 | else { 67 | current = root; 68 | parent = NULL; 69 | 70 | while (1) { 71 | parent = current; 72 | //in BST value of all the nodes in left subtree is lesser or equal 73 | if (tempNode->data <= parent->data) { 74 | current = current->leftChild; 75 | if (current == NULL) { 76 | parent->leftChild = tempNode; 77 | return 0; 78 | } 79 | } 80 | //in BST value of all the nodes in right subtree is greater. 81 | else { 82 | current = current->rightChild; 83 | if (current == NULL) { 84 | parent->rightChild = tempNode; 85 | return 0; 86 | } 87 | } 88 | } 89 | } 90 | } 91 | 92 | int main() { 93 | BST t; 94 | /* 95 | the following tree will be constructed with height=4 96 | 15 97 | / \ 98 | 12 17 99 | / \ / \ 100 | 10 13 16 18 101 | / \ \ 102 | 8 14 20 103 | \ 104 | 22 105 | if there is only one node in tree then height=0 106 | e.g; 107 | 15 ->height=0 108 | / \ 109 | null null 110 | */ 111 | t.insert(15); 112 | t.insert(12); 113 | t.insert(17); 114 | t.insert(10); 115 | t.insert(13); 116 | t.insert(16); 117 | t.insert(18); 118 | t.insert(8); 119 | t.insert(14); 120 | t.insert(20); 121 | t.insert(22); 122 | cout << "\n\n\t" << "Height of the tree is:"<< t.findHeight(root)<<"\n\n\t"; 123 | system("pause"); 124 | return 0; 125 | } -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/5-Level Order(BFS) using QUEUE/5-Level Order Traversal(using QUEUE).cpp: -------------------------------------------------------------------------------- 1 | // Level Order Traversal (BFS) 2 | // Time- Complexity= O(n) 3 | // Space-Complexity=O(1)-best 4 | // =O(n)-worst/average 5 | 6 | #include 7 | 8 | //instead of writing our own queue implementation we can use Queue in standard template library #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | //node class to create a new node 14 | class Node{ 15 | public: 16 | char data; 17 | Node *leftChild ; 18 | Node *rightChild; 19 | 20 | Node(char d,Node *l=NULL, Node *r=NULL){ 21 | data=d; 22 | leftChild=l; 23 | rightChild=r; 24 | } 25 | }; 26 | 27 | 28 | Node *root=NULL; 29 | 30 | 31 | class BST{ 32 | public: 33 | char insert(char d); 34 | int levelOrder(Node *root); 35 | }; 36 | 37 | //function to insert a node in BST 38 | char BST::insert(char d){ 39 | //tempNode is a pointer which always has address of new node that is created. 40 | Node *tempNode = new Node(d); 41 | Node *parent = NULL; 42 | Node *current = NULL; 43 | 44 | if (root == NULL) { 45 | root = tempNode; 46 | } 47 | else { 48 | current = root; 49 | parent = NULL; 50 | 51 | while (1) { 52 | parent = current; 53 | //in BST value of all the nodes in left subtree is lesser or equal 54 | if (tempNode->data <= parent->data) { 55 | current = current->leftChild; 56 | if (current == NULL) { 57 | parent->leftChild = tempNode; 58 | return 0; 59 | } 60 | } 61 | //in BST value of all the nodes in right subtree is greater. 62 | else { 63 | current = current->rightChild; 64 | if (current == NULL) { 65 | parent->rightChild = tempNode; 66 | return 0; 67 | } 68 | } 69 | } 70 | } 71 | } 72 | 73 | 74 | //function for level order traversal 75 | int BST::levelOrder(Node *root){ 76 | if(root==NULL) 77 | return 0; 78 | 79 | //now to create a queue we use the following syntax 80 | queueQ; 81 | 82 | //first we push root in queue 83 | Q.push(root); 84 | 85 | //while there is at least one discovered node 86 | while(!Q.empty()){ 87 | Node *current=Q.front(); 88 | Q.pop(); // removing the element at front 89 | cout<data<<" "; 90 | 91 | if(current->leftChild!=NULL) 92 | Q.push(current->leftChild); 93 | 94 | if(current->rightChild!=NULL) 95 | Q.push(current->rightChild); 96 | } 97 | } 98 | int main(){ 99 | /* 100 | Creating an example tree 101 | M 102 | / \ 103 | B Q 104 | / \ \ 105 | A C Z 106 | */ 107 | 108 | BST t; 109 | t.insert('M'); 110 | t.insert('B'); 111 | t.insert('Q'); 112 | t.insert('A'); 113 | t.insert('C'); 114 | t.insert('Z'); 115 | 116 | cout<<"Level Order Traversal(BFS) is:"<<"\n\n"; 117 | t.levelOrder(root); 118 | cout<<"\n\n"; 119 | 120 | return 0; 121 | } 122 | -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/6-Delete Node from BST/6-delete a node from bst.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | To delete a node from BST there are three scenarios: 4 | 1- root has no child 5 | 2- root has one child 6 | 3- root has two children 7 | 8 | */ 9 | #include 10 | using namespace std; 11 | 12 | class Node { 13 | public: 14 | int data; 15 | Node *left; 16 | Node *right; 17 | 18 | Node(int d,Node *l=NULL, Node *r=NULL) { 19 | data = d; 20 | left = l; 21 | right = r; 22 | } 23 | }; 24 | class BST { 25 | public: 26 | Node* FindMin(Node *root); 27 | Node* Delete(Node *root, int data); 28 | void inOrderTraversal(Node *root); 29 | Node* insert(Node *root, int d); 30 | }; 31 | 32 | //function to find node value 33 | Node* BST::FindMin(Node *root) { 34 | while (root->left != NULL) { 35 | root = root->left; 36 | return root; 37 | } 38 | } 39 | 40 | //function to search a node to be deleted and then delete it. 41 | Node* BST::Delete(Node *root, int data) { 42 | if (root == NULL) 43 | return root; 44 | else if (data < root->data) 45 | root->left = Delete(root->left, data); 46 | else if (data > root->data) 47 | root->right = Delete(root->right, data); 48 | //now we have found the node to be deleted let's delete it... 49 | else { 50 | //Case 1: No Child 51 | if (root->left == NULL && root->right == NULL) { 52 | delete root; 53 | root = NULL; 54 | } 55 | //Case 2: One Child 56 | else if (root->left == NULL) { 57 | Node *temp; 58 | temp = root; 59 | root = root->right; 60 | delete temp; 61 | } 62 | else if (root->right == NULL) { 63 | Node *temp; 64 | temp = root; 65 | root = root->left; 66 | delete temp; 67 | } 68 | //Case 3: Two Children 69 | else { 70 | Node *temp; 71 | //find minimum in right sub-tree 72 | temp = FindMin(root->right); 73 | //copy the minimum value at the place of node to be deleted 74 | root->data = temp->data; 75 | //delete duplicate value 76 | root->right = Delete(root->right, temp->data); 77 | } 78 | } 79 | return root; 80 | } 81 | 82 | //function for inOrder Traversal 83 | void BST::inOrderTraversal(Node *root){ 84 | if (root != NULL) { 85 | inOrderTraversal(root->left); 86 | cout << root->data<<" "; 87 | inOrderTraversal(root->right); 88 | } 89 | } 90 | 91 | //function to insert a new node in BST 92 | Node* BST::insert(Node *root, int d) { 93 | if (root == NULL) 94 | root = new Node(d); 95 | else if(d<=root->data) 96 | root->left = insert(root->left, d); 97 | else 98 | root->right = insert(root->right, d); 99 | return root; 100 | } 101 | 102 | int main() { 103 | 104 | /*Code To Test the logic 105 | Creating an example tree 106 | 5 107 | / \ 108 | 3 10 109 | / \ \ 110 | 1 4 11 111 | 112 | to check this code properly use 11, 3, 10 , 5 to be deleted values. 113 | */ 114 | Node *root = NULL; 115 | 116 | BST t; 117 | 118 | root = t.insert(root, 5); root = t.insert(root, 10); 119 | root = t.insert(root, 3); root = t.insert(root, 4); 120 | root = t.insert(root, 1); root = t.insert(root, 11); 121 | 122 | t.Delete(root, 3); 123 | cout << "InOrder Traversal is: "; 124 | t.inOrderTraversal(root); 125 | 126 | 127 | system("pause"); 128 | return 0; 129 | } -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/7-Check tree is BST or Not/7-Check Tree is BST or Not.cpp: -------------------------------------------------------------------------------- 1 | //Check whether a tree is BST or not. 2 | //Time Complexity is O(N) 3 | #include 4 | using namespace std; 5 | 6 | class Node { 7 | public: 8 | int data; 9 | Node *left; 10 | Node *right; 11 | 12 | Node(int d, Node *l = NULL, Node *r = NULL) { 13 | data = d; 14 | left = l; 15 | right = r; 16 | } 17 | }; 18 | 19 | class BST { 20 | public: 21 | //BST Utility Function. 22 | bool isBSTUtil(Node *root, int minValue, int maxValue) { 23 | if (root == NULL) 24 | return true; 25 | if (root->datadata>maxValue ) 26 | return false; 27 | return isBSTUtil(root->left, minValue, root->data) && isBSTUtil(root->right, root->data, maxValue); 28 | } 29 | //function that returns true if tree is BST or false otherwise. 30 | bool isBinarySearchTree(Node *root) { 31 | return isBSTUtil(root, INT_MIN, INT_MAX); 32 | } 33 | }; 34 | 35 | int main() { 36 | 37 | BST t; 38 | 39 | Node *root = NULL; 40 | 41 | root = new Node(4); 42 | root->left = new Node(2); 43 | root->right = new Node(5); 44 | root->left->left = new Node(1); 45 | root->left->right = new Node(3); 46 | root->right->right = new Node(0); 47 | 48 | if (t.isBinarySearchTree(root)) 49 | cout << "Is BST"<<"\n"; 50 | else 51 | cout << "Not a BST"<<"\n"; 52 | 53 | system("pause"); 54 | return 0; 55 | } -------------------------------------------------------------------------------- /C++/8-BST(Binary Search tree)/8-InOrder successor of a Node in BST/8-InOrder Successor in BST.cpp: -------------------------------------------------------------------------------- 1 | //InOrder successor is the node that would come immediately after the given node in inOrder traversal of the BST. 2 | //Time Complexity of this algorithm is O(h)=log base 2 n 3 | 4 | #include 5 | using namespace std; 6 | 7 | class Node { 8 | public: 9 | int data; 10 | Node *left; 11 | Node *right; 12 | 13 | Node(int d, Node *l = NULL, Node *r = NULL) { 14 | data = d; 15 | left = l; 16 | right = r; 17 | } 18 | }; 19 | 20 | class BST { 21 | public: 22 | Node* insert(Node *root,int d); 23 | void inOrder(Node *root); 24 | 25 | Node* find(Node *root, int d); 26 | Node* findMin(Node *root); 27 | Node* findSuccessor(Node *root, int d); 28 | }; 29 | 30 | //function to find the node whose successor we have to find 31 | Node* BST::find(Node *root, int d) { 32 | if (root == NULL) 33 | return root; 34 | else if (root->data == d) 35 | return root; 36 | else if (root->data < d) 37 | return find(root->right, d); 38 | else 39 | return find(root->left, d); 40 | } 41 | 42 | //function to find minimum in a BST 43 | Node* BST::findMin(Node *root) { 44 | if (root == NULL) 45 | return NULL; 46 | while (root->left != NULL) 47 | root = root->left; 48 | 49 | return root; 50 | } 51 | 52 | //function to find successor of a Node 53 | Node* BST::findSuccessor(Node *root, int d) { 54 | //the node whose successor we have to find is stored in current 55 | Node *current = find(root, d); 56 | 57 | if (current == NULL) 58 | return NULL; 59 | //case 1: Node has right SubTree 60 | else if (current->right != NULL) { 61 | //if there is a right subtree then we know that the successor will be minimum value at the left of current->right 62 | return findMin(current->right); 63 | } 64 | //case 2: No right SubTree 65 | else { 66 | //to understand this see diagram illustration on register 67 | Node *successor = NULL; 68 | Node *ancestor = root; 69 | while (ancestor != current) { 70 | if (current->data < ancestor->data){ 71 | successor = ancestor; 72 | ancestor = ancestor->left; 73 | } 74 | else { 75 | ancestor = ancestor->right; 76 | } 77 | } 78 | return successor; 79 | } 80 | } 81 | 82 | Node* BST::insert(Node *root,int d) { 83 | if (root == NULL) 84 | root = new Node(d); 85 | else if (d <= root->data) 86 | root->left = insert(root->left, d); 87 | else 88 | root->right = insert(root->right, d); 89 | 90 | return root; 91 | } 92 | 93 | void BST::inOrder(Node *root) { 94 | if (root != NULL) { 95 | inOrder(root->left); 96 | cout << root->data << " "; 97 | inOrder(root->right); 98 | } 99 | } 100 | 101 | int main() { 102 | /*Code To Test the logic 103 | Creating an example tree 104 | 5 105 | / \ 106 | 3 10 107 | / \ \ 108 | 1 4 11 109 | */ 110 | 111 | BST t; 112 | Node *root = NULL; 113 | root = t.insert(root, 5); root = t.insert(root, 10); 114 | root = t.insert(root, 3); root = t.insert(root, 4); 115 | root = t.insert(root, 1); root = t.insert(root, 11); 116 | 117 | cout << "InOrder Traversal is: "; 118 | t.inOrder(root); 119 | Node *successor = t.findSuccessor(root, 3); 120 | 121 | if (successor == NULL) 122 | cout <<" \n" <<"No successor found" << endl; 123 | else 124 | cout <<"\n"<< "Successor is: " << successor->data << endl; 125 | 126 | 127 | system("pause"); 128 | return 0; 129 | } -------------------------------------------------------------------------------- /C++/9-Heaps/Array is Min heap or not.cpp: -------------------------------------------------------------------------------- 1 | //To check whether an array is a min heap or not 2 | 3 | #include 4 | using namespace std; 5 | 6 | bool isMinHeap(int A[], int size); 7 | 8 | int main() { 9 | int size; 10 | cout << "How many Values you wanna enter:"; 11 | cin >> size; 12 | 13 | int A[size]; 14 | 15 | cout << "Enter " << size << " values : " << endl; 16 | for (int i = 1; i <= size; i++) 17 | cin >> A[i]; 18 | 19 | if (isMinHeap(A, size) == true) 20 | cout << "Array is a Min Heap" << endl; 21 | else 22 | cout << "Array is not a Min Heap" << endl; 23 | 24 | 25 | system("pause"); 26 | return 0; 27 | } 28 | bool isMinHeap(int A[], int size) { 29 | //as we know that in min heap each parent node is lesser than or equal to its child nodes. 30 | //so we start checking from root and goes on checking until we reach the last node. 31 | 32 | int i=1; 33 | 34 | while(i<=size){ 35 | 36 | if( A[i] <= A[2*i] && A[i] <= A[(2*i) + 1] ){ 37 | 38 | i++; 39 | 40 | return true; 41 | 42 | } 43 | 44 | else{ 45 | 46 | return false; 47 | 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /C++/9-Heaps/DSA PP-12 Q-4 Max heap or not.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | DSA Past Papar 2012 3 | Q#4: Write C++ function bool isMaxHeap() (int A[], int size) to determine whether the array A is a Max heap or not . This function should return 4 | true if the array A is a max heap and it should return false otherwise. You can assume that the indices of the array start at 1 (instead of 0) 5 | */ 6 | #include 7 | using namespace std; 8 | 9 | bool isMaxHeap(int A[], int size); 10 | 11 | int main() { 12 | int size; 13 | cout << "How many Values you wanna enter:"; 14 | cin >> size; 15 | 16 | int A[size]; 17 | 18 | cout << "Enter " << size << " values : " << endl; 19 | for (int i = 1; i <= size; i++) 20 | cin >> A[i]; 21 | 22 | if (isMaxHeap(A, size) == true) 23 | cout << "Array is a Max Heap" << endl; 24 | else 25 | cout << "Array is not a Max Heap" << endl; 26 | 27 | 28 | system("pause"); 29 | return 0; 30 | } 31 | bool isMaxHeap(int A[], int size) { 32 | //as we know that in max heap each parent node is greater than or equal to its child nodes. 33 | //so we check from root node and goes on until we reach the last node. 34 | 35 | int i=1; 36 | 37 | while(i<=size){ 38 | 39 | if( A[i] >= A[2*i] && A[i] >= A[(2*i) + 1] ){ 40 | 41 | i++; 42 | 43 | return true; 44 | 45 | } 46 | 47 | else{ 48 | 49 | return false; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /C++/9-Heaps/Max Heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Maximum size of Heap. 5 | #define MAX 100 6 | 7 | void insertHeap(int A[], int n, int key); 8 | void insertHeapify(int A[], int n, int i); 9 | 10 | void deleteRoot(int A[], int n); 11 | void deleteHeapify(int A[], int n, int i); 12 | 13 | void swap(int *a,int *b); 14 | int main() { 15 | 16 | int arr[MAX]={10, 5, 3, 2, 4, 0}; 17 | 18 | //key is the value that we wanna insert in heap. 19 | int key=25; 20 | 21 | //Total no. of elements in an array 22 | int n=6; 23 | 24 | //insertion 25 | insertHeap(arr, n, key); 26 | 27 | //to display 28 | cout<<"Max Heap is(After insertion) is: "; 29 | for(int i=0; i0){ 75 | 76 | if(A[i]>A[parent]){ 77 | 78 | swap(&A[i],&A[parent]); 79 | 80 | //recursive call 81 | insertHeapify(A,n,parent); 82 | } 83 | } 84 | } 85 | 86 | //Function to delete the root node 87 | void deleteRoot(int A[],int n){ 88 | //As we know for deletion in max heap 89 | //first we place the last node 90 | //at the place of root node and then build the max heap 91 | int lastElement=A[n-1]; 92 | //placing the last element at root 93 | A[0]=lastElement; 94 | //decrementing the size becuase last element is placed 95 | //at the root node and root node is deleted 96 | n=n-1; 97 | 98 | deleteHeapify(A,n,0); 99 | } 100 | 101 | void deleteHeapify(int A[],int n, int i){ 102 | //setting the largest value = root node 103 | int largest=i; 104 | //finding the left child of root node 105 | int l= (2 * i) + 1; 106 | //finding the right child of root node 107 | int r= (2 * i) + 2; 108 | //if left child is < size and left child is greater than 109 | //largest then largest = left child. 110 | if(lA[largest]){ 111 | largest=l; 112 | } 113 | //if right child is < size and right child is greater than 114 | //largest then largest = right child 115 | if(rA[largest]){ 116 | largest=r; 117 | } 118 | //now as we have updated the largest 119 | //so we check if largest != i then we will swap 120 | if(largest!=i){ 121 | swap(&A[i],&A[largest]); 122 | 123 | //recursive call 124 | deleteHeapify(A,n,largest); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /C++/9-Heaps/Min Heap(Array Representation).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int *a, int *b); 5 | 6 | class MinHeap { 7 | private: 8 | int *harr; //pointer to array of elements in heap 9 | int capacity; //maximum size of min heap 10 | int heap_size;//current number of elements in min heap 11 | public: 12 | //constructor 13 | MinHeap(int cap); 14 | 15 | //returns the parent node 16 | int parent(int i) { 17 | return (i - 1) / 2; 18 | } 19 | //returns the left child of parent node 20 | int left(int i) { 21 | return (2 * i) + 1; 22 | } 23 | //returns the right child of parent node 24 | int right(int i) { 25 | return (2 * i) + 2; 26 | } 27 | //returns the minimum value 28 | int getMin() { 29 | return harr[0]; 30 | } 31 | void minHeapify(int i); 32 | 33 | void insertKey(int k); 34 | void display(); 35 | }; 36 | 37 | //Constructor 38 | MinHeap::MinHeap(int cap) { 39 | harr = new int[cap]; 40 | capacity = cap; 41 | heap_size = 0; 42 | } 43 | 44 | void MinHeap::minHeapify(int i) { 45 | int l = left(i); 46 | int r = right(i); 47 | int smallest = i; 48 | if (l < heap_size && harr[l] < harr[i]) 49 | smallest = l; 50 | if (r < heap_size && harr[r] < harr[smallest]) 51 | smallest = r; 52 | if (smallest != i) 53 | { 54 | swap(&harr[i], &harr[smallest]); 55 | minHeapify(smallest); 56 | } 57 | } 58 | //Function to insert a node in min heap 59 | void MinHeap::insertKey(int k) { 60 | if (heap_size == capacity) { 61 | cout << "Overflow: couldn't insert" << endl; 62 | return; 63 | } 64 | heap_size++; 65 | int i = heap_size - 1; 66 | harr[i] = k; 67 | while (i != 0 && harr[parent(i)] > harr[i]) 68 | { 69 | swap(&harr[i], &harr[parent(i)]); 70 | i = parent(i); 71 | } 72 | 73 | } 74 | 75 | 76 | //display values 77 | void MinHeap::display() { 78 | cout << "Min Heap is : "; 79 | for (int i = 0; i < capacity; i++) { 80 | cout << harr[i] << " "; 81 | } 82 | cout << endl; 83 | } 84 | 85 | int main() { 86 | 87 | MinHeap m(5); 88 | m.insertKey(5); 89 | m.insertKey(13); 90 | m.insertKey(2); 91 | m.insertKey(0); 92 | m.insertKey(55); 93 | m.display(); 94 | cout << m.parent(0) << endl; 95 | cout << m.left(0) << endl; 96 | cout << m.right(0) << endl; 97 | cout << m.getMin() << endl; 98 | 99 | 100 | system("pause"); 101 | return 0; 102 | } 103 | 104 | void swap(int *a, int *b) { 105 | int temp; 106 | temp = *a; 107 | *a = *b; 108 | *b = temp; 109 | } -------------------------------------------------------------------------------- /C++/Binary Tree/Children Sum property.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | void InOrder(Node *head, vector &a) 19 | { 20 | if (head == NULL) 21 | return; 22 | InOrder(head->left, a); 23 | a.push_back(head->data); 24 | InOrder(head->right, a); 25 | return; 26 | } 27 | 28 | void ChildrenSumProperty(Node *head) 29 | { 30 | if (head == NULL) 31 | return; 32 | if (head->left && head->right && head->left->data + head->right->data <= head->data) 33 | { 34 | head->left->data = head->data; 35 | head->right->data = head->data; 36 | ChildrenSumProperty(head->left); 37 | ChildrenSumProperty(head->right); 38 | head->data = head->left->data + head->right->data; 39 | return; 40 | } 41 | else if (head->right && !head->left && head->right->data <= head->data) 42 | { 43 | head->right->data = head->data; 44 | ChildrenSumProperty(head->right); 45 | head->data = head->right->data; 46 | } 47 | else if (head->right && !head->left && head->right->data > head->data) 48 | { 49 | ChildrenSumProperty(head->right); 50 | head->data = head->right->data; 51 | } 52 | else if (head->left && !head->right && head->left->data <= head->data) 53 | { 54 | head->left->data = head->data; 55 | ChildrenSumProperty(head->left); 56 | head->data = head->left->data; 57 | } 58 | else if (head->left && !head->right && head->left->data > head->data) 59 | { 60 | ChildrenSumProperty(head->left); 61 | head->data = head->left->data; 62 | } 63 | else if (head->left && head->right) 64 | { 65 | head->data = head->left->data + head->right->data; 66 | ChildrenSumProperty(head->left); 67 | ChildrenSumProperty(head->right); 68 | head->data = head->left->data + head->right->data; 69 | } 70 | return; 71 | } 72 | 73 | int main() 74 | { 75 | Node *head = new Node(1); 76 | head->left = new Node(2); 77 | head->right = new Node(3); 78 | head->left->left = new Node(4); 79 | head->left->right = new Node(5); 80 | head->right->left = new Node(6); 81 | head->right->right = new Node(7); 82 | head->left->left->right = new Node(8); 83 | head->left->right->left = new Node(9); 84 | head->right->left->left = new Node(10); 85 | head->right->right->right = new Node(11); 86 | head->right->right->right->right = new Node(12); 87 | 88 | vector prein, newin; 89 | 90 | cout << "Previous Inorder: "; 91 | InOrder(head, prein); 92 | for (int i = 0; i < prein.size(); i++) 93 | { 94 | cout << prein[i] << ' '; 95 | } 96 | cout << '\n'; 97 | 98 | cout << "\nChildren Sum Property: Applied\n"; 99 | ChildrenSumProperty(head); 100 | 101 | cout << "\nLater InOrder: "; 102 | InOrder(head, newin); 103 | for (int i = 0; i < newin.size(); i++) 104 | { 105 | cout << newin[i] << ' '; 106 | } 107 | cout << '\n'; 108 | 109 | return 0; 110 | } -------------------------------------------------------------------------------- /C++/Binary Tree/DiameterBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | int height(Node *head) 19 | { 20 | if (head == NULL) 21 | return 0; 22 | int lh = height(head->left); 23 | int rh = height(head->right); 24 | return max(lh, rh) + 1; 25 | } 26 | 27 | int Diameter(Node *head) 28 | { 29 | if (head == NULL) 30 | return 0; 31 | return max(height(head->left) + height(head->right) + 1, max(Diameter(head->left), Diameter(head->right))); 32 | } 33 | 34 | int main() 35 | { 36 | Node *head = new Node(1); 37 | head->left = new Node(2); 38 | head->right = new Node(3); 39 | head->left->left = new Node(4); 40 | head->left->right = new Node(5); 41 | head->right->left = new Node(6); 42 | head->right->right = new Node(7); 43 | head->left->left->right = new Node(8); 44 | head->left->right->left = new Node(9); 45 | head->right->left->left = new Node(10); 46 | head->right->right->right = new Node(11); 47 | head->right->right->right->right = new Node(12); 48 | 49 | cout << "Diameter: "; 50 | int d = Diameter(head); 51 | cout << d; 52 | return 0; 53 | } -------------------------------------------------------------------------------- /C++/Binary Tree/Height of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | int height(Node *head) 19 | { 20 | if (head == NULL) 21 | return 0; 22 | int lh = height(head->left); 23 | int rh = height(head->right); 24 | return max(lh, rh) + 1; 25 | } 26 | 27 | int main() 28 | { 29 | Node *head = new Node(1); 30 | head->left = new Node(2); 31 | head->right = new Node(3); 32 | head->left->left = new Node(4); 33 | head->left->right = new Node(5); 34 | head->right->left = new Node(6); 35 | head->right->right = new Node(7); 36 | head->left->left->right = new Node(8); 37 | head->left->right->left = new Node(9); 38 | head->right->left->left = new Node(10); 39 | head->right->right->right = new Node(11); 40 | head->right->right->right->right = new Node(12); 41 | 42 | cout << "\nHeight: "; 43 | int h = height(head); 44 | cout << h << '\n'; 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /C++/Binary Tree/Inorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | void InOrder(Node *head, vector &a) 19 | { 20 | if (head == NULL) 21 | return; 22 | InOrder(head->left, a); 23 | a.push_back(head->data); 24 | InOrder(head->right, a); 25 | return; 26 | } 27 | 28 | int main() 29 | { 30 | Node *head = new Node(1); 31 | head->left = new Node(2); 32 | head->right = new Node(3); 33 | head->left->left = new Node(4); 34 | head->left->right = new Node(5); 35 | head->right->left = new Node(6); 36 | head->right->right = new Node(7); 37 | head->left->left->right = new Node(8); 38 | head->left->right->left = new Node(9); 39 | head->right->left->left = new Node(10); 40 | head->right->right->right = new Node(11); 41 | head->right->right->right->right = new Node(12); 42 | 43 | vector in; 44 | InOrder(head, in); 45 | cout << "\nInOrder: "; 46 | for (int i = 0; i < in.size(); i++) 47 | { 48 | cout << in[i] << ' '; 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /C++/Binary Tree/LeftView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | void LeftView(Node *head, vector &a) 19 | { 20 | if (head == NULL) 21 | return; 22 | queue q; 23 | q.push(head); 24 | q.push(NULL); 25 | a.push_back(head->data); 26 | int level = 1; 27 | while (!q.empty()) 28 | { 29 | if (q.front() == NULL) 30 | { 31 | q.pop(); 32 | if (!q.empty()) 33 | q.push(NULL); 34 | level++; 35 | if (!q.empty() && a.size() < level) 36 | a.push_back(q.front()->data); 37 | } 38 | else 39 | { 40 | if (q.front()->left != NULL) 41 | q.push(q.front()->left); 42 | if (q.front()->right != NULL) 43 | q.push(q.front()->right); 44 | q.pop(); 45 | } 46 | } 47 | } 48 | 49 | int main() 50 | { 51 | Node *head = new Node(1); 52 | head->left = new Node(2); 53 | head->right = new Node(3); 54 | head->left->left = new Node(4); 55 | head->left->right = new Node(5); 56 | head->right->left = new Node(6); 57 | head->right->right = new Node(7); 58 | head->left->left->right = new Node(8); 59 | head->left->right->left = new Node(9); 60 | head->right->left->left = new Node(10); 61 | head->right->right->right = new Node(11); 62 | head->right->right->right->right = new Node(12); 63 | 64 | cout << "Left View: "; 65 | vector leftv; 66 | LeftView(head, leftv); 67 | for (int i = 0; i < leftv.size(); i++) 68 | cout << leftv[i] << " "; 69 | cout << endl; 70 | 71 | return 0; 72 | } -------------------------------------------------------------------------------- /C++/Binary Tree/Lowest Common Ancestor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i,x,y) for(ll i=x;idata==a || head->data==b) return true; 23 | else return Find(head->left,a,b)||Find(head->right,a,b); 24 | } 25 | 26 | int LowestCommonAncestor(Node* head,int a,int b) 27 | { 28 | if(head==NULL) return -1; 29 | if(head->data==a || head->data==b) return head->data; 30 | else if(Find(head->left,a,b) && Find(head->right,a,b)) return head->data; 31 | else if(Find(head->left,a,b)) return LowestCommonAncestor(head->left,a,b); 32 | else if(Find(head->right,a,b)) return LowestCommonAncestor(head->right,a,b); 33 | return -1; 34 | } 35 | 36 | int main() 37 | { 38 | Node* head=new Node(1); 39 | head->left=new Node(2); 40 | head->right=new Node(3); 41 | head->left->left=new Node(4); 42 | head->left->right=new Node(5); 43 | head->right->left=new Node(6); 44 | head->right->right=new Node(7); 45 | head->left->left->right=new Node(8); 46 | head->left->right->left=new Node(9); 47 | head->right->left->left=new Node(10); 48 | head->right->right->right=new Node(11); 49 | head->right->right->right->right=new Node(12); 50 | 51 | int a = 6, b = 12; 52 | cout< 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | void PostOrder(Node *head, vector &a) 19 | { 20 | if (head == NULL) 21 | return; 22 | PostOrder(head->left, a); 23 | PostOrder(head->right, a); 24 | a.push_back(head->data); 25 | return; 26 | } 27 | 28 | int main() 29 | { 30 | Node *head = new Node(1); 31 | head->left = new Node(2); 32 | head->right = new Node(3); 33 | head->left->left = new Node(4); 34 | head->left->right = new Node(5); 35 | head->right->left = new Node(6); 36 | head->right->right = new Node(7); 37 | head->left->left->right = new Node(8); 38 | head->left->right->left = new Node(9); 39 | head->right->left->left = new Node(10); 40 | head->right->right->right = new Node(11); 41 | head->right->right->right->right = new Node(12); 42 | 43 | vector post; 44 | PostOrder(head, post); 45 | cout << "\nPostOrder: "; 46 | for (int i = 0; i < post.size(); i++) 47 | { 48 | cout << post[i] << ' '; 49 | } 50 | return 0; 51 | } -------------------------------------------------------------------------------- /C++/Binary Tree/Preorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | void PreOrder(Node *head, vector &a) 19 | { 20 | if (head == NULL) 21 | return; 22 | a.push_back(head->data); 23 | PreOrder(head->left, a); 24 | PreOrder(head->right, a); 25 | return; 26 | } 27 | 28 | int main() 29 | { 30 | Node *head = new Node(1); 31 | head->left = new Node(2); 32 | head->right = new Node(3); 33 | head->left->left = new Node(4); 34 | head->left->right = new Node(5); 35 | head->right->left = new Node(6); 36 | head->right->right = new Node(7); 37 | head->left->left->right = new Node(8); 38 | head->left->right->left = new Node(9); 39 | head->right->left->left = new Node(10); 40 | head->right->right->right = new Node(11); 41 | head->right->right->right->right = new Node(12); 42 | 43 | vector pre; 44 | PreOrder(head, pre); 45 | cout << "\nPreOrder: "; 46 | for (int i = 0; i < pre.size(); i++) 47 | { 48 | cout << pre[i] << ' '; 49 | } 50 | return 0; 51 | } -------------------------------------------------------------------------------- /C++/Binary Tree/RightView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define f(i, x, y) for (ll i = x; i < y; i++) 5 | 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node *left = NULL; 11 | Node *right = NULL; 12 | Node(int x) 13 | { 14 | data = x; 15 | } 16 | }; 17 | 18 | void RightView(Node *head, vector &a) 19 | { 20 | if (head == NULL) 21 | return; 22 | queue q; 23 | q.push(head); 24 | q.push(NULL); 25 | int level = 1; 26 | a.push_back(head->data); 27 | while (!q.empty()) 28 | { 29 | if (q.front() == NULL) 30 | { 31 | q.pop(); 32 | if (!q.empty()) 33 | q.push(NULL); 34 | level++; 35 | if (!q.empty() && a.size() < level) 36 | a.push_back(q.front()->data); 37 | } 38 | 39 | else 40 | { 41 | if (q.front()->right != NULL) 42 | q.push(q.front()->right); 43 | if (q.front()->left != NULL) 44 | q.push(q.front()->left); 45 | q.pop(); 46 | } 47 | } 48 | } 49 | 50 | int main() 51 | { 52 | Node *head = new Node(1); 53 | head->left = new Node(2); 54 | head->right = new Node(3); 55 | head->left->left = new Node(4); 56 | head->left->right = new Node(5); 57 | head->right->left = new Node(6); 58 | head->right->right = new Node(7); 59 | head->left->left->right = new Node(8); 60 | head->left->right->left = new Node(9); 61 | head->right->left->left = new Node(10); 62 | head->right->right->right = new Node(11); 63 | head->right->right->right->right = new Node(12); 64 | 65 | cout << "Right View: "; 66 | vector rightv; 67 | RightView(head, rightv); 68 | for (int i = 0; i < rightv.size(); i++) 69 | cout << rightv[i] << " "; 70 | cout << endl; 71 | 72 | return 0; 73 | } -------------------------------------------------------------------------------- /C++/Graphs/Adjencency_List_Implementation/BFS/Itteration.cpp: -------------------------------------------------------------------------------- 1 | //Incase of BFS we will make use of queue and will implement following idea 2 | //Take a start vertex 3 | //Check all neighbours and push them onto queue 4 | //now take the first neighbour and push all neighbours onto queue and so on 5 | 6 | void BFS() 7 | { 8 | bool *visited = new bool[V]; 9 | for (int i = 0; i < V; i++) 10 | visited[i] = false; 11 | list queue; // Create a queue for BFS 12 | 13 | //The outer loop will keep track of all disconnected nodes 14 | for(int i=0; i::iterator ite; 21 | while (!queue.empty()){ 22 | i = queue.front(); // Dequeue a vertex from queue & print it 23 | cout << i << " "; 24 | queue.pop_front(); 25 | 26 | // Get all adjacent vertices of the dequeued vertex i. If an adjacent vertex is not visited,then mark it visited and enqueue it 27 | for (ite = adj[i].begin(); ite != adj[i].end(); ++ite){ 28 | if (!visited[*ite]){ 29 | visited[*ite] = true;//mark the neighbours and push them onto queue 30 | queue.push_back(*ite); 31 | } 32 | 33 | } 34 | } 35 | } 36 | delete [] visited; 37 | } 38 | -------------------------------------------------------------------------------- /C++/Graphs/Adjencency_List_Implementation/BasicStructure.cpp: -------------------------------------------------------------------------------- 1 | //Following is the basic structure of graph implemented using adjencency list 2 | class Graph() 3 | { 4 | private: 5 | int V; //Total number of vertices 6 | list* adj; //List to keep track of edges between vertices and to recurse through them 7 | public: 8 | Graph(int n) //Constructor that intializes the total number of vertices and the list adj 9 | { 10 | V = n; 11 | adj = new list[V]; 12 | } 13 | void TakeInput(int n, int w) //Add edge between n and w that are the given vertices 14 | { 15 | adj[n].push_back(w); //Incase of directed graph only add an edge from n to w 16 | adj[w].push_back(n); 17 | } 18 | //We will do itterations seperately as they are of different types mainly DFS and BFS 19 | } 20 | -------------------------------------------------------------------------------- /C++/Graphs/Adjencency_List_Implementation/DFS/Itteration.cpp: -------------------------------------------------------------------------------- 1 | //Following code is used to Itterate through graphs implemented using adjencency list using DFS recursively 2 | 3 | void DFS(int V)//Total vertices V 4 | { 5 | bool* visited = new bool[V]; // create a boolean array on heap to keep track of vertices 6 | for(int i=0 ;i::iterator ite; 32 | for(ite = adj[v].begin(); ite!= adj[v].end();i++) 33 | { 34 | if(!visited[*i]) 35 | { 36 | DFSHelp(*i,visited); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /C++/Red-Black-Tree/Theoretical-Background.md: -------------------------------------------------------------------------------- 1 | **Introduction:** 2 | When it comes to searching and sorting data, one of the most fundamental data structures is the binary search tree. However, the performance of a binary search tree is highly dependent on its shape, and in the worst case, it can degenerate into a linear structure with a time complexity of O(n). This is where Red Black Trees come in, they are a type of balanced binary search tree that use a specific set of rules to ensure that the tree is always balanced. This balance guarantees that the time complexity for operations such as insertion, deletion, and searching is always O(log n), regardless of the initial shape of the tree. 3 | 4 | Red Black Trees are self-balancing, meaning that the tree adjusts itself automatically after each insertion or deletion operation. It uses a simple but powerful mechanism to maintain balance, by coloring each node in the tree either red or black. 5 | 6 | 7 | *Properties of Red Black Tree:* 8 | The Red-Black tree satisfies all the properties of binary search tree in addition to that it satisfies following additional properties – 9 | 10 | 1. *Root property*: The root is black. 11 | 12 | 2. *External property*: Every leaf (Leaf is a NULL child of a node) is black in Red-Black tree. 13 | 14 | 3. *Internal property*: The children of a red node are black. Hence possible parent of red node is a black node. 15 | 16 | 4. *Depth property*: All the leaves have the same black depth. 17 | 18 | 5. *Path property*: Every simple path from root to descendant leaf node contains same number of black nodes. 19 | 20 | *Why Red-Black Trees?*
21 | Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height of the BST. The cost of these operations may become O(n) for a skewed Binary tree. If we make sure that the height of the tree remains O(log n) after every insertion and deletion, then we can guarantee an upper bound of O(log n) for all these operations. The height of a Red-Black tree is always O(log n) where n is the number of nodes in the tree. 22 | -------------------------------------------------------------------------------- /C++/SlidingWindow/239. Sliding Window Maximum: -------------------------------------------------------------------------------- 1 | //problem name: Sliding Window Maximum 2 | //problem link: https://leetcode.com/problems/sliding-window-maximum/description/ 3 | //code: 4 | class Solution { 5 | public: 6 | vector maxSlidingWindow(vector& nums, int k) { 7 | vector ans; 8 | // deque ll; 9 | list ll; 10 | int i=0,j=0; 11 | int n = nums.size(); 12 | while(j0 && ll.back()data > b->data; 16 | } 17 | }; 18 | class Solution { 19 | public: 20 | vector smallestRange(vector>& nums) { 21 | int start,end; 22 | int mini=INT_MAX,maxi=INT_MIN; 23 | node* tmp; 24 | int len=nums.size(); 25 | priority_queue,compare> mp; 26 | for(int i=0;idata; 36 | if(maxi-mini < end-start){ 37 | start=mini; 38 | end=maxi; 39 | } 40 | if(tmp->col+1row].size()){ 41 | maxi=max(maxi,nums[tmp->row][tmp->col+1]); 42 | mp.push(new node(nums[tmp->row][tmp->col+1],tmp->row,tmp->col+1)); 43 | } 44 | else{ 45 | break; 46 | } 47 | } 48 | return {start,end}; 49 | } 50 | }; -------------------------------------------------------------------------------- /C++/SlidingWindow/Nice_subarrays.cpp: -------------------------------------------------------------------------------- 1 | // LEETCODE SLIDING WINDOW PROBLEM 1 - https://leetcode.com/problems/count-number-of-nice-subarrays/description/ 2 | 3 | class Solution { 4 | public: 5 | int numberOfSubarrays(vector& nums, int k) { 6 | int j = 0; 7 | int odd = 0; 8 | int count = 0; 9 | int total = 0; 10 | 11 | for(int i = 0; i < nums.size(); i++){ 12 | if(nums[i] % 2 != 0){ 13 | odd++; 14 | if(odd >= k){ 15 | count = 1; //set count as 1 16 | while (!(nums[j++] & 1)) count++; 17 | // while (j < i && nums[j] % 2 == 0){ 18 | // count++; 19 | // j++; 20 | // } 21 | total += count; 22 | } 23 | } else if (odd >= k) total += count; 24 | } 25 | return total; 26 | } 27 | }; -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | # Learn Data Structures and Algorithms 3 | 4 | ## How to contribute 5 | 1. You can contribute in terms of Code: 6 | - By adding a new `topic` and `code` related to that topic 7 | - By adding data structures and algorithms concepts in other languages like `java`, `python`, `ruby`, `javascript` etc 8 | - Visit [issues](https://github.com/ShehrozIrfan/learn-dsa/issues) 9 | 2. You can contribute in terms of documentation: 10 | - By adding the documentation for any `data structure and algorithm` concept 11 | 12 | ## Following the procedure you can make your contribution with ease. 13 | 14 | ### Step 0 15 | Star and Fork this repository 16 | 17 | ### Step 1 18 | Look in the issues section, if the change you are doing is available in the issues section and whether it is assigned to someone or not. 19 | If you can't find any issue then open one. I will assign you the issue then you can start contributing! 20 | 21 | ### step 2 Fork this repository 22 | You can fork this repository by clicking on fork button on top right corner. Once you fork this will create a copy of repo on your account 23 | 24 | ### step 3 Clone the repository 25 | To clone the repository go to your account open this repo and either click on clone button or run the command below to get this repository on your local machine 26 | 27 | > git clone <_URL you just copied_> 28 | e.g. git clone https://github.com/yourgithubusername/learn-dsa.git 29 | 30 | ### step 4 Get into the App 31 | On your local machine go the project folder that you cloned 32 | 33 | ### step 4 Create a branch 34 | Use following git command inside that folder 35 | 36 | create a new branch using below command. 37 | 38 | > git checkout -b \ 39 | e.g. `git checkout -b mybranch` 40 | 41 | ### step 4 Lets make some contributions 42 | Make changes to files on your local machine work on the issue you're assigned. 43 | 44 | ### step 5 Add Changes and Commit Changes 45 | Now we have to add changes that we made to the branch so for that we will run following command. 46 | 47 | > git add . 48 | Now we have to commit changes, commit message should always be clear, to commit use command below. 49 | 50 | > git commit -m "resolved the \" 51 | ### step 6 Push changes to GitHub 52 | Now we have to push the changes that we made to remote repository on specified branch to do so use command below. 53 | 54 | > git push origin \ 55 | name of branch is same as you created in step 3 56 | 57 | e.g `git push origin mybranch` 58 | 59 | ### step 7 Submit your changes for review 60 | Once you have pushed your code to GitHub, it's now time to create pull request, you will go to the repository click on compare and pull request and submit the pull request. 61 | 62 | Soon, I will be merging all your pull requests to the main branch of project and you will also get notification once your pull request is merged with existing code base. 63 | -------------------------------------------------------------------------------- /Java/Binary Search Tree/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | // This code defines a TreeNode class to represent the nodes of the binary search tree 2 | // and a BinarySearchTree class to manage the tree. It includes methods for insertion (insert), 3 | // searching (search), and in-order traversal (inOrderTraversal). The main method demonstrates 4 | // how to create a BST, insert elements, perform in-order traversal, and search for specific 5 | // values in the tree. 6 | 7 | 8 | class TreeNode { 9 | int data; 10 | TreeNode left; 11 | TreeNode right; 12 | 13 | public TreeNode(int data) { 14 | this.data = data; 15 | this.left = null; 16 | this.right = null; 17 | } 18 | } 19 | 20 | public class BinarySearchTree { 21 | private TreeNode root; 22 | 23 | public BinarySearchTree() { 24 | root = null; 25 | } 26 | 27 | public void insert(int value) { 28 | root = insertRec(root, value); 29 | } 30 | 31 | private TreeNode insertRec(TreeNode root, int value) { 32 | if (root == null) { 33 | root = new TreeNode(value); 34 | return root; 35 | } 36 | 37 | if (value < root.data) { 38 | root.left = insertRec(root.left, value); 39 | } else if (value > root.data) { 40 | root.right = insertRec(root.right, value); 41 | } 42 | 43 | return root; 44 | } 45 | 46 | public boolean search(int value) { 47 | return searchRec(root, value); 48 | } 49 | 50 | private boolean searchRec(TreeNode root, int value) { 51 | if (root == null) { 52 | return false; 53 | } 54 | 55 | if (root.data == value) { 56 | return true; 57 | } 58 | 59 | if (value < root.data) { 60 | return searchRec(root.left, value); 61 | } 62 | 63 | return searchRec(root.right, value); 64 | } 65 | 66 | public void inOrderTraversal() { 67 | inOrderTraversal(root); 68 | } 69 | 70 | private void inOrderTraversal(TreeNode root) { 71 | if (root != null) { 72 | inOrderTraversal(root.left); 73 | System.out.print(root.data + " "); 74 | inOrderTraversal(root.right); 75 | } 76 | } 77 | 78 | public static void main(String[] args) { 79 | BinarySearchTree bst = new BinarySearchTree(); 80 | 81 | bst.insert(50); 82 | bst.insert(30); 83 | bst.insert(70); 84 | bst.insert(20); 85 | bst.insert(40); 86 | bst.insert(60); 87 | bst.insert(80); 88 | 89 | System.out.println("In-order traversal of the BST:"); 90 | bst.inOrderTraversal(); 91 | 92 | int searchValue = 40; 93 | System.out.println("\nSearch for " + searchValue + ": " + bst.search(searchValue)); 94 | 95 | searchValue = 90; 96 | System.out.println("Search for " + searchValue + ": " + bst.search(searchValue)); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Java/Circular Linked List/CircularLinkedList.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | int data; 3 | Node next; 4 | 5 | public Node(int data) { 6 | this.data = data; 7 | this.next = null; 8 | } 9 | } 10 | 11 | public class CircularLinkedList { 12 | private Node head; 13 | private Node tail; 14 | 15 | public CircularLinkedList() { 16 | head = null; 17 | tail = null; 18 | } 19 | 20 | public void addToEnd(int data) { 21 | Node newNode = new Node(data); 22 | if (head == null) { 23 | head = newNode; 24 | tail = newNode; 25 | newNode.next = head; // Point the tail back to the head to form a loop 26 | } else { 27 | tail.next = newNode; 28 | tail = newNode; 29 | newNode.next = head; // Update the new tail to point back to the head 30 | } 31 | } 32 | 33 | public void display() { 34 | if (head == null) { 35 | System.out.println("Circular Linked List is empty."); 36 | return; 37 | } 38 | 39 | Node current = head; 40 | do { 41 | System.out.print(current.data + " "); 42 | current = current.next; 43 | } while (current != head); 44 | System.out.println(); 45 | } 46 | 47 | public static void main(String[] args) { 48 | CircularLinkedList cll = new CircularLinkedList(); 49 | 50 | cll.addToEnd(1); 51 | cll.addToEnd(2); 52 | cll.addToEnd(3); 53 | cll.addToEnd(4); 54 | 55 | System.out.println("Circular Linked List:"); 56 | cll.display(); 57 | } 58 | } 59 | 60 | //The Node class represents a node in the circular linked list. 61 | // It contains an integer data field and a reference to the next node. 62 | 63 | // The CircularLinkedList class manages the circular linked list. 64 | // It provides methods to add elements to the end of the list and to display the list. 65 | 66 | // The addToEnd method adds a new node to the end of the circular linked list. 67 | // If the list is empty, it creates the first node and sets both the head and tail to it. 68 | // For subsequent additions, it updates the tail and the new node's next reference to maintain the circular structure. 69 | 70 | // The display method traverses and prints the circular linked list starting from the head, 71 | // looping until it reaches the head again. 72 | 73 | // The main method demonstrates how to create a circular linked list, add elements, and display the list. -------------------------------------------------------------------------------- /Java/Doubly Linked List/DoublyLinkedList.java: -------------------------------------------------------------------------------- 1 | //Doubly Linked List in Java 2 | 3 | class Node { 4 | 5 | int data; 6 | Node prev; 7 | Node next; 8 | 9 | Node(int value) 10 | { 11 | prev = null; 12 | data = value; 13 | next = null; 14 | } 15 | } 16 | 17 | class DoublyLinkedList 18 | { 19 | //creating empty doubly linked list 20 | static Node head = null; 21 | 22 | //inserting element at the head 23 | static void insert_at_head(int value) 24 | { 25 | Node n = new Node(value); 26 | n.next = head; 27 | 28 | if (head != null) 29 | { 30 | head.prev = n; 31 | } 32 | head = n; 33 | } 34 | 35 | //inserting element at the tail 36 | static void insert_at_tail(int value) 37 | { 38 | if (head == null) 39 | { 40 | insert_at_head(value); 41 | return; 42 | } 43 | Node n = new Node(value); 44 | Node temp = head; 45 | while (temp.next != null) 46 | { 47 | temp = temp.next; 48 | } 49 | temp.next = n; 50 | n.prev = temp; 51 | } 52 | 53 | //displaying the doubly linked list 54 | static void display(Node head) 55 | { 56 | Node temp = head; 57 | while (temp != null) 58 | { 59 | System.out.print(temp.data + " --> "); 60 | temp = temp.next; 61 | } 62 | System.out.println("NULL"); 63 | } 64 | 65 | public static void main(String[] args) 66 | { 67 | insert_at_tail(1); 68 | insert_at_tail(2); 69 | insert_at_tail(3); 70 | insert_at_tail(4); 71 | insert_at_tail(5); 72 | System.out.print("After insertion at tail: "); 73 | display(head); 74 | System.out.print("After insertion at head: "); 75 | insert_at_head(0); 76 | display(head); 77 | } 78 | } -------------------------------------------------------------------------------- /Java/Programs and Task/PyramidPattern.java: -------------------------------------------------------------------------------- 1 | package ProblemSolvingBasic; 2 | 3 | /*Right Pyramid*/ 4 | 5 | public class PyramidPattern { 6 | public static void main(String[] args) { 7 | System.out.println("Pyramid Pattern!"); 8 | 9 | int n = 5; 10 | 11 | for (int i = n; i > 0; i--) { 12 | int space = i - 1; 13 | for (int j = 0; j < n; j++) { 14 | if (j < space) { 15 | System.out.print(" "); 16 | } else { 17 | System.out.print("#"); 18 | } 19 | } 20 | System.out.println(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Java/Programs and Task/UnexpectedDemand.java: -------------------------------------------------------------------------------- 1 | package ProblemSolvingBasic; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | /*A widget manufacturer is facing unexpectedly high demand for its new product. 8 | They would like to satisfy as many customers as possible. Given a number of widgets 9 | available and a list of customer orders, what is the maximum number of orders the 10 | manufacturer can fulfill in full?*/ 11 | 12 | public class UnexpectedDemand { 13 | public static void main(String[] args) { 14 | System.out.println("Unexpected Demand!"); 15 | 16 | List orders = Arrays.asList(5, 2, 4); 17 | 18 | Collections.sort(orders); 19 | 20 | int widgets = 3; 21 | int counter = 0; 22 | 23 | for (Integer order : orders) { 24 | if (order <= widgets) { 25 | widgets -= order; 26 | counter++; 27 | } else { 28 | break; 29 | } 30 | } 31 | 32 | System.out.println("Successful Filled Orders ---> " + counter); 33 | } 34 | } -------------------------------------------------------------------------------- /Java/Queue/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShehrozIrfan/learn-dsa/bcd65a9ee2c6fb4dcfc769d97b2eddd56c05db0a/Java/Queue/.DS_Store -------------------------------------------------------------------------------- /Java/Queue/Queue.java: -------------------------------------------------------------------------------- 1 | //program to implement Queue in Java 2 | public class Queue { 3 | static final int SIZE = 100; 4 | int items[] = new int[SIZE]; 5 | int front, rear; 6 | 7 | Queue() 8 | { 9 | front = -1; 10 | rear = -1; 11 | } 12 | 13 | //checking if Queue is empty 14 | boolean isEmpty() 15 | { 16 | if (front == -1) 17 | { 18 | return true; 19 | } 20 | else 21 | { 22 | return false; 23 | } 24 | } 25 | 26 | //checking if Queue is full 27 | boolean isFull() 28 | { 29 | if (front == 0 && rear == SIZE) 30 | { 31 | return true; 32 | } 33 | else 34 | { 35 | return false; 36 | } 37 | } 38 | 39 | //inserting elements to Queue 40 | void enQueue(int x) 41 | { 42 | //checking if queue is full 43 | if (isFull()) 44 | { 45 | System.out.println("Queue is full"); 46 | } 47 | //inserting element from rear of Queue 48 | else 49 | { 50 | if (front == -1) 51 | { 52 | front = 0; 53 | } 54 | } 55 | rear ++; 56 | items[rear] = x; 57 | } 58 | 59 | //removing element from Queue 60 | int deQueue() 61 | { 62 | int x; 63 | 64 | //checking if queue if empty 65 | if (isEmpty()) 66 | { 67 | System.out.println("Queue is Empty"); 68 | return (-1); 69 | } 70 | 71 | //removing the element from front of Queue 72 | else 73 | { 74 | x = items[front]; 75 | if (front >= rear) 76 | { 77 | front = -1; 78 | rear = -1; 79 | } 80 | else{ 81 | front++; 82 | } 83 | return(x); 84 | } 85 | } 86 | 87 | //displaying queue 88 | void display() 89 | { 90 | int i; 91 | if (isEmpty()) 92 | { 93 | System.out.println("Queue is empty"); 94 | } 95 | else{ 96 | System.out.println("Queue: "); 97 | for (i = front; i <= rear; i++) 98 | { 99 | System.out.print(items[i] + " "); 100 | } 101 | } 102 | } 103 | } 104 | 105 | class Main{ 106 | public static void main(String args[]) 107 | { 108 | Queue q = new Queue(); 109 | 110 | q.deQueue(); 111 | q.enQueue(1); 112 | q.enQueue(2); 113 | q.enQueue(3); 114 | q.deQueue(); 115 | q.display(); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Java/Recursion/Factorial.java: -------------------------------------------------------------------------------- 1 | //Recursive function to find factorial of a number 2 | 3 | package Recursion; 4 | 5 | public class Factorial { 6 | static int factorial(int n) 7 | { 8 | if (n == 0) 9 | { 10 | return 1; 11 | } 12 | else 13 | { 14 | return (n * factorial(n-1)); 15 | } 16 | } 17 | 18 | public static void main (String args[]) 19 | { 20 | int fact = 1; 21 | int num = 6; 22 | fact = factorial(num); 23 | System.out.println("Factorial of " + num + " is: " + fact); 24 | } 25 | } -------------------------------------------------------------------------------- /Java/Recursion/Power.java: -------------------------------------------------------------------------------- 1 | //Recursive function to find power of a number in Java 2 | package Recursion; 3 | 4 | public class Power { 5 | 6 | //function to calculate power 7 | static int power(int num, int pow) 8 | { 9 | if (pow == 0) 10 | { 11 | return 1; 12 | } 13 | else 14 | { 15 | return num * power(num, pow - 1); 16 | } 17 | } 18 | 19 | public static void main(String args[]) 20 | { 21 | int num = 2; 22 | int pow = 8; 23 | 24 | System.out.println(power(num, pow)); 25 | } 26 | } -------------------------------------------------------------------------------- /Java/Recursion/SumOfPositiveNumber.java: -------------------------------------------------------------------------------- 1 | package Recursion; 2 | 3 | //Recursion program to find Sum of n positive numbers in Java 4 | 5 | public class SumOfPositiveNumber { 6 | public static int sum(int n) { 7 | if (n == 1) { 8 | return 1; 9 | } else { 10 | return n + sum(n-1); 11 | } 12 | } 13 | 14 | public static void main(String[] args) { 15 | int n = 5; 16 | int result = sum(n); 17 | System.out.println("Sum of the first " + n + " positive integers: " + result); 18 | } 19 | } -------------------------------------------------------------------------------- /Java/Recursion/SumOfSquareOfPositiveNumbers.java: -------------------------------------------------------------------------------- 1 | //Recursive function to find Sum of square of first n positive numbers 2 | 3 | package Recursion; 4 | 5 | public class SumOfSquareOfPositiveNumbers { 6 | public static int sumSquares(int n) { 7 | if (n == 1) { 8 | return 1; 9 | } 10 | return (n * n) + sumSquares(n - 1); 11 | } 12 | 13 | public static void main(String args[]) 14 | { 15 | int n = 5; 16 | System.out.println("Sum of square of First " + n + " positive numbers: "); 17 | System.out.println(sumSquares(n)); 18 | } 19 | } -------------------------------------------------------------------------------- /Java/Searching/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Search implementation code in Java 3 | This is used to search an element in sorted array 4 | Time complexity : O(logn) 5 | */ 6 | 7 | 8 | public class BinarySearch { 9 | public static int search(int[] arr,int target){ 10 | int start = 0; 11 | int end = arr.length-1; 12 | while (start <= end) { 13 | int mid = start+(end-start)/2; 14 | if(target == arr[mid]) 15 | return mid; //Return the index of element if found in array 16 | if(arr[mid]= l) { 21 | 22 | // Find the mid1 and mid2 23 | int mid1 = l + (r - l) / 3; 24 | int mid2 = r - (r - l) / 3; 25 | 26 | // Check if key is present at any mid 27 | if (ar[mid1] == key) { 28 | return mid1; 29 | } 30 | if (ar[mid2] == key) { 31 | return mid2; 32 | } 33 | 34 | // Since key is not present at mid, 35 | // check in which region it is present 36 | // then repeat the Search operation 37 | // in that region 38 | 39 | if (key < ar[mid1]) { 40 | 41 | // The key lies in between l and mid1 42 | return ternarySearch(l, mid1 - 1, key, ar); 43 | } 44 | else if (key > ar[mid2]) { 45 | 46 | // The key lies in between mid2 and r 47 | return ternarySearch(mid2 + 1, r, key, ar); 48 | } 49 | else { 50 | 51 | // The key lies in between mid1 and mid2 52 | return ternarySearch(mid1 + 1, mid2 - 1, key, ar); 53 | } 54 | } 55 | 56 | // Key not found 57 | return -1; 58 | } 59 | 60 | // Driver code 61 | public static void main(String args[]) 62 | { 63 | int l, r, p, key; 64 | 65 | // Get the array 66 | // Sort the array if not sorted 67 | int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 68 | 69 | // Starting index 70 | l = 0; 71 | 72 | // end element index 73 | r = 9; 74 | 75 | // Checking for 5 76 | 77 | // Key to be searched in the array 78 | key = 5; 79 | 80 | // Search the key using ternarySearch 81 | p = ternarySearch(l, r, key, ar); 82 | 83 | // Print the result 84 | System.out.println("Index of " + key + " is " + p); 85 | 86 | // Checking for 50 87 | 88 | // Key to be searched in the array 89 | key = 50; 90 | 91 | // Search the key using ternarySearch 92 | p = ternarySearch(l, r, key, ar); 93 | 94 | // Print the result 95 | System.out.println("Index of " + key + " is " + p); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Java/Singly Linked List/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | //Singly Linked List in Java 2 | 3 | public class SinglyLinkedList { 4 | class Node 5 | { 6 | int data; 7 | Node next; 8 | 9 | public Node(int data) 10 | { 11 | this.data = data; 12 | this.next = null; 13 | } 14 | } 15 | 16 | //head and tail of the singly linked list 17 | public Node head = null; 18 | public Node tail = null; 19 | 20 | public void addNode(int data) 21 | { 22 | //creating a new node in the list 23 | Node newNode = new Node(data); 24 | 25 | //checking if list is empty 26 | if (head == null) 27 | { 28 | //when list is empty both head and tail points to new node 29 | head = newNode; 30 | tail = newNode; 31 | } 32 | else 33 | { 34 | tail.next = newNode; 35 | tail = newNode; 36 | } 37 | } 38 | 39 | //displaying the list 40 | void display() 41 | { 42 | //pointing to head 43 | Node current = head; 44 | if (head == null) 45 | { 46 | System.out.println("List is Empty"); 47 | return; 48 | } 49 | while (current != null) 50 | { 51 | System.out.print(current.data + " "); 52 | current = current.next; 53 | } 54 | System.out.println(); 55 | } 56 | 57 | public static void main(String args[]) 58 | { 59 | SinglyLinkedList sll = new SinglyLinkedList(); 60 | sll.addNode(1); 61 | sll.addNode(2); 62 | sll.addNode(3); 63 | sll.addNode(4); 64 | sll.addNode(5); 65 | System.out.println("Nodes of Singly Linked List: "); 66 | sll.display(); 67 | } 68 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/BubbleSort.java: -------------------------------------------------------------------------------- 1 | //Bubble Sort in Java 2 | 3 | public class BubbleSort { 4 | void bubbleSort(int arr[]) 5 | { 6 | //finding length of the array 7 | int len = arr.length; 8 | for (int i = 0; i < len-1; i++) 9 | { 10 | for (int j = 0; j < len-i-1; j++) 11 | { 12 | if (arr[j] > arr[j+1]) 13 | { 14 | //swap arr[j+1] and arr[j] 15 | int temp = arr[j]; 16 | arr[j] = arr[j + 1]; 17 | arr[j + 1] = temp; 18 | } 19 | } 20 | } 21 | } 22 | 23 | //displaying the array 24 | void display(int arr[]) 25 | { 26 | int len = arr.length; 27 | for (int i = 0; i < len; ++i) 28 | { 29 | System.out.print(arr[i] + " "); 30 | } 31 | System.out.println(); 32 | } 33 | 34 | public static void main(String args[]) 35 | { 36 | BubbleSort bs = new BubbleSort(); 37 | int arr[] = {23, 12, 87, 10, 11, 64}; 38 | bs.bubbleSort(arr); 39 | System.out.println("Sorted Array: "); 40 | bs.display(arr); 41 | } 42 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/CountingSort.java: -------------------------------------------------------------------------------- 1 | //Counting Sort in Java 2 | import java.util.Arrays; 3 | 4 | public class CountingSort { 5 | public static void countingSort(int[] array) { 6 | // Find the minimum and maximum values in the array 7 | int max = findMax(array); 8 | int min = findMin(array); 9 | 10 | // Calculate the range of values 11 | int range = max - min + 1; 12 | 13 | // Create an array to store the count of each value 14 | int[] count = new int[range]; 15 | 16 | // Create an output array 17 | int[] output = new int[array.length]; 18 | 19 | // Count the frequency of each element 20 | for (int value : array) { 21 | count[value - min]++; 22 | } 23 | 24 | // Modify the count array to store the final position of each element 25 | for (int i = 1; i < range; i++) { 26 | count[i] += count[i - 1]; 27 | } 28 | 29 | // Build the output array based on the count array 30 | for (int i = array.length - 1; i >= 0; i--) { 31 | output[count[array[i] - min] - 1] = array[i]; 32 | count[array[i] - min]--; 33 | } 34 | 35 | // Copy the sorted elements back to the original array 36 | for (int i = 0; i < array.length; i++) { 37 | array[i] = output[i]; 38 | } 39 | } 40 | 41 | // Function to find the maximum value in an array 42 | public static int findMax(int[] array) { 43 | int max = array[0]; 44 | for (int value : array) { 45 | if (value > max) { 46 | max = value; 47 | } 48 | } 49 | return max; 50 | } 51 | 52 | // Function to find the minimum value in an array 53 | public static int findMin(int[] array) { 54 | int min = array[0]; 55 | for (int value : array) { 56 | if (value < min) { 57 | min = value; 58 | } 59 | } 60 | return min; 61 | } 62 | 63 | public static void main(String[] args) { 64 | int[] arr = {4, 2, 2, 8, 3, 3, 1}; 65 | 66 | System.out.println("Original Array: " + Arrays.toString(arr)); 67 | 68 | countingSort(arr); 69 | 70 | System.out.println("Sorted Array: " + Arrays.toString(arr)); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Java/Sorting Algorithm/HeapSort.java: -------------------------------------------------------------------------------- 1 | //Hear Sort in Java 2 | 3 | public class HeapSort { 4 | public void sort(int arr[]) 5 | { 6 | int len = arr.length; 7 | 8 | //building the heap 9 | for(int i = len / 2 - 1; i >= 0; i--) 10 | { 11 | heapify(arr, len, i); 12 | } 13 | 14 | //extracting element from heap 15 | for (int i = len - 1; i > 0; i--) 16 | { 17 | //moving current root to end 18 | int temp = arr[0]; 19 | arr[0] = arr[i]; 20 | arr[i] = temp; 21 | 22 | //calling maximum heapify on reduced heap 23 | heapify(arr, i, 0); 24 | } 25 | } 26 | 27 | void heapify(int arr[], int len, int i) 28 | { 29 | int largest = i; 30 | int l = 2 * i + 1; 31 | int r = 2 * i + 2; 32 | 33 | //if left child is larger than root 34 | if (l < len && arr[l] > arr[largest]) 35 | { 36 | largest = l; 37 | } 38 | 39 | //if right child is larger than largest 40 | if (r < len && arr[r] > arr[largest]) 41 | { 42 | largest = r; 43 | } 44 | 45 | //if largest is not the root 46 | if (largest != i) 47 | { 48 | int swap = arr[i]; 49 | arr[i] = arr[largest]; 50 | arr[largest] = swap; 51 | 52 | heapify(arr, len, largest); 53 | } 54 | } 55 | 56 | //displaying the array 57 | static void display(int arr[]) 58 | { 59 | int len = arr.length; 60 | for (int i = 0; i < len; ++i) 61 | { 62 | System.out.print(arr[i] + " "); 63 | } 64 | System.out.println(); 65 | } 66 | 67 | public static void main(String args[]) 68 | { 69 | HeapSort hs = new HeapSort(); 70 | int arr[] = {23, 12, 87, 10, 11, 64}; 71 | int len = arr.length; 72 | hs.sort(arr); 73 | System.out.println("Sorted Array: "); 74 | hs.display(arr); 75 | } 76 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/InsertionSort.java: -------------------------------------------------------------------------------- 1 | //Insertion Sort in Java 2 | 3 | public class InsertionSort { 4 | void sort(int arr[]) 5 | { 6 | //finding length of the array 7 | int len = arr.length; 8 | for (int i = 1; i < len; ++i) 9 | { 10 | int key = arr[i]; 11 | int j = i - 1; 12 | 13 | /*moving the elememnts of the array that are greater than 14 | key to a posiiton ahead of their current position */ 15 | while (j >= 0 && arr[j] > key) 16 | { 17 | arr[j + 1] = arr[j]; 18 | j = j - 1; 19 | } 20 | arr[j + 1] = key; 21 | } 22 | } 23 | 24 | //displaying the array 25 | void display(int arr[]) 26 | { 27 | int len = arr.length; 28 | for (int i = 0; i < len; ++i) 29 | { 30 | System.out.print(arr[i] + " "); 31 | } 32 | System.out.println(); 33 | } 34 | 35 | public static void main(String args[]) 36 | { 37 | InsertionSort is = new InsertionSort(); 38 | int arr[] = {23, 12, 87, 10, 11, 64}; 39 | is.sort(arr); 40 | System.out.println("Sorted Array: "); 41 | is.display(arr); 42 | } 43 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/MergeSortAlgo.java: -------------------------------------------------------------------------------- 1 | public class MergeSortAlgo { 2 | public static void main(String[] args) { 3 | int[] arr = { 2, 7, 8, 9, 1, 3, 4, 5 }; 4 | int low = 0; 5 | 6 | int high = arr.length - 1; 7 | mergeSort(arr, low, high); 8 | for (int i = 0; i < arr.length; i++) { 9 | System.out.print(arr[i] + " "); 10 | } 11 | 12 | } 13 | 14 | static void mergeSort(int arr[], int low, int high) { 15 | if (low < high) { 16 | int mid = (low + high) / 2; 17 | mergeSort(arr, low, mid); 18 | mergeSort(arr, mid + 1, high); 19 | mergefunc(arr, low, mid, high); 20 | } 21 | } 22 | 23 | static void mergefunc(int[] arr, int low, int mid, int high) { 24 | int n1 = mid + 1 - low; 25 | int n2 = high - mid; 26 | int[] left = new int[n1]; 27 | int[] right = new int[n2]; 28 | for (int i = 0; i < n1; i++) { 29 | left[i] = arr[low + i]; 30 | } 31 | for (int i = 0; i < n2; i++) { 32 | right[i] = arr[mid + 1 + i]; 33 | } 34 | int i = 0, j = 0, k = low; 35 | while (i < n1 && j < n2) { 36 | if (left[i] <= right[j]) { 37 | arr[k] = left[i]; 38 | i++; 39 | k++; 40 | } else { 41 | arr[k] = right[j]; 42 | j++; 43 | k++; 44 | } 45 | } 46 | 47 | while (i < n1) { 48 | arr[k] = left[i]; 49 | i++; 50 | k++; 51 | } 52 | while (j < n2) { 53 | arr[k] = right[j]; 54 | j++; 55 | k++; 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/QuickSort.java: -------------------------------------------------------------------------------- 1 | //Quick Sort in java 2 | 3 | public class QuickSort { 4 | int partition (int arr[], int start, int end) 5 | { 6 | //end element as the pivot element 7 | int pivot = arr[end]; 8 | int i = (start - 1); 9 | 10 | for (int j = start; j <= end - 1; j++) 11 | { 12 | //if current element is smaller than pivot 13 | if (arr[j] < pivot) 14 | { 15 | //increment index of smaller element 16 | ++i; 17 | //swapping elements at i and j index 18 | int temp = arr[i]; 19 | arr[i] = arr[j]; 20 | arr[j] = temp; 21 | } 22 | } 23 | int temp = arr[i + 1]; 24 | arr[i + 1] = arr[end]; 25 | arr[end] = temp; 26 | return (i + 1); 27 | } 28 | 29 | //to implement quick sort 30 | void sort (int arr[], int start, int end) 31 | { 32 | if(start < end) 33 | { 34 | int p = partition(arr, start, end); 35 | sort(arr, start, p - 1); 36 | sort(arr, p + 1, end); 37 | } 38 | } 39 | 40 | //displaying the error 41 | void display(int arr[], int len) 42 | { 43 | int i; 44 | for (i = 0; i < len; i++) 45 | { 46 | System.out.print(arr[i] + " "); 47 | } 48 | } 49 | 50 | public static void main(String args[]) 51 | { 52 | QuickSort qs = new QuickSort(); 53 | int arr[] = {23, 12, 87, 10, 11, 64}; 54 | int len = arr.length; 55 | qs.sort(arr, 0, len - 1); 56 | System.out.println("Sorted Array: "); 57 | qs.display(arr, len); 58 | } 59 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/SelectionSort.java: -------------------------------------------------------------------------------- 1 | //Selection Sort in Java 2 | 3 | public class SelectionSort { 4 | void sort(int arr[]) 5 | { 6 | //finding length of array 7 | int len = arr.length; 8 | for (int i = 0; i < len; i++) 9 | { 10 | //finding the smallest element in the array 11 | int min = i; 12 | for (int j = i+1; j < len; j++) 13 | { 14 | if(arr[j] < arr[min]) 15 | { 16 | min = j; 17 | } 18 | } 19 | 20 | //swapping the found element with the first element 21 | int temp = arr[min]; 22 | arr[min] = arr[i]; 23 | arr[i] = temp; 24 | } 25 | } 26 | 27 | //displaying the array 28 | void display(int arr[]) 29 | { 30 | int len = arr.length; 31 | for (int i = 0; i < len; ++i) 32 | { 33 | System.out.print(arr[i] + " "); 34 | } 35 | System.out.println(); 36 | } 37 | 38 | public static void main(String args[]) 39 | { 40 | SelectionSort ss = new SelectionSort(); 41 | int arr[] = {23, 12, 87, 10, 11, 64}; 42 | ss.sort(arr); 43 | System.out.println("Sorted Array: "); 44 | ss.display(arr); 45 | } 46 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/TreeSort.java: -------------------------------------------------------------------------------- 1 | //Tree Sort in Java 2 | 3 | public class TreeSort { 4 | class Node 5 | { 6 | int key; 7 | Node left, right; 8 | 9 | public Node(int item) 10 | { 11 | key = item; 12 | left = right = null; 13 | } 14 | } 15 | 16 | //root of BST 17 | Node root; 18 | TreeSort() 19 | { 20 | root = null; 21 | } 22 | void insert(int key) 23 | { 24 | root = insertRec(root, key); 25 | } 26 | 27 | //inserting new key in BST 28 | Node insertRec(Node root, int key) 29 | { 30 | //returns a new node if tree is empty 31 | if (root == null) 32 | { 33 | root = new Node(key); 34 | return root; 35 | } 36 | 37 | if (key < root.key) 38 | { 39 | root.left = insertRec(root.left, key); 40 | } 41 | else if (key > root.key) 42 | { 43 | root.right = insertRec(root.right, key); 44 | } 45 | return root; 46 | } 47 | 48 | //inorder traversal of BST 49 | void inorderRec(Node root) 50 | { 51 | if (root != null) 52 | { 53 | inorderRec(root.left); 54 | System.out.print(root.key + " "); 55 | inorderRec(root.right); 56 | } 57 | } 58 | 59 | //inserting 60 | 61 | void treeins(int arr[]) 62 | { 63 | for (int i = 0; i < arr.length; i++) 64 | { 65 | insert(arr[i]); 66 | } 67 | } 68 | 69 | public static void main(String[] args) 70 | { 71 | TreeSort ts = new TreeSort(); 72 | int arr[] = {23, 12, 87, 10, 11, 64}; 73 | System.out.println("Sorted Array: "); 74 | ts.treeins(arr); 75 | ts.inorderRec(ts.root); 76 | } 77 | } -------------------------------------------------------------------------------- /Java/Sorting Algorithm/shellsort.java: -------------------------------------------------------------------------------- 1 | class ShellSort 2 | { 3 | static void printArray(int arr[]) 4 | { 5 | int n = arr.length; 6 | for (int i=0; i 0; gap /= 2) 14 | { 15 | for (int i = gap; i < n; i += 1) 16 | { 17 | int temp = arr[i]; 18 | int j; 19 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 20 | arr[j] = arr[j - gap]; 21 | 22 | arr[j] = temp; 23 | } 24 | } 25 | return 0; 26 | } 27 | 28 | public static void main(String args[]) 29 | { 30 | int arr[] = {12, 34, 54, 2, 3}; 31 | System.out.println("Array before sorting"); 32 | printArray(arr); 33 | 34 | ShellSort ob = new ShellSort(); 35 | ob.sort(arr); 36 | 37 | System.out.println("Array after sorting"); 38 | printArray(arr); 39 | } 40 | } -------------------------------------------------------------------------------- /Java/Sparse Matrix/SparseMatrix.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | // In this example, the SparseMatrix class uses a Map to store the non-zero elements, 5 | // and it provides methods for setting and getting values at specific positions in 6 | // the matrix. The print method is used to display the matrix. 7 | 8 | public class SparseMatrix { 9 | private int numRows; 10 | private int numCols; 11 | private Map> matrix; 12 | 13 | public SparseMatrix(int numRows, int numCols) { 14 | this.numRows = numRows; 15 | this.numCols = numCols; 16 | this.matrix = new HashMap<>(); 17 | } 18 | 19 | public void set(int row, int col, int value) { 20 | if (row >= 0 && row < numRows && col >= 0 && col < numCols) { 21 | if (value != 0) { 22 | if (!matrix.containsKey(row)) { 23 | matrix.put(row, new HashMap<>()); 24 | } 25 | matrix.get(row).put(col, value); 26 | } else { 27 | // If the value is zero, remove the entry from the map 28 | if (matrix.containsKey(row)) { 29 | matrix.get(row).remove(col); 30 | if (matrix.get(row).isEmpty()) { 31 | matrix.remove(row); 32 | } 33 | } 34 | } 35 | } else { 36 | throw new IllegalArgumentException("Invalid row or column index"); 37 | } 38 | } 39 | 40 | public int get(int row, int col) { 41 | if (row >= 0 && row < numRows && col >= 0 && col < numCols) { 42 | if (matrix.containsKey(row) && matrix.get(row).containsKey(col)) { 43 | return matrix.get(row).get(col); 44 | } 45 | } 46 | return 0; // Default value for zero elements 47 | } 48 | 49 | public void print() { 50 | for (int i = 0; i < numRows; i++) { 51 | for (int j = 0; j < numCols; j++) { 52 | System.out.print(get(i, j) + " "); 53 | } 54 | System.out.println(); 55 | } 56 | } 57 | 58 | public static void main(String[] args) { 59 | int numRows = 5; 60 | int numCols = 5; 61 | SparseMatrix sparseMatrix = new SparseMatrix(numRows, numCols); 62 | 63 | sparseMatrix.set(0, 0, 1); 64 | sparseMatrix.set(1, 1, 2); 65 | sparseMatrix.set(2, 2, 3); 66 | sparseMatrix.set(3, 3, 4); 67 | 68 | sparseMatrix.print(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Java/Stack/Stack.java: -------------------------------------------------------------------------------- 1 | //Program to implement Stack using Java 2 | public class Stack { 3 | static final int SIZE = 100; 4 | int top; 5 | //maximum size of the Stack 6 | int arr[] = new int[SIZE]; 7 | 8 | //checking if stack is empty or not 9 | boolean isEmpty() 10 | { 11 | return (top < 0); 12 | } 13 | Stack() 14 | { 15 | top = -1; 16 | } 17 | 18 | //inserting element in top of stack 19 | boolean push(int x) 20 | { 21 | if (top >= (SIZE - 1)) { 22 | System.out.println("Stack Overflow"); 23 | return false; 24 | } 25 | else { 26 | arr[++top] = x; 27 | return true; 28 | } 29 | } 30 | 31 | //removing an element from top of stack 32 | int pop() 33 | { 34 | if (top < 0){ 35 | System.out.println("Stack Underflow"); 36 | return 0; 37 | } 38 | else{ 39 | int x = arr[top--]; 40 | return x; 41 | } 42 | } 43 | 44 | //returns the current top element of stack 45 | int peek() 46 | { 47 | if (top < 0){ 48 | System.out.println("Stack Underflow"); 49 | return 0; 50 | } 51 | else{ 52 | int x = arr[top]; 53 | return x; 54 | } 55 | } 56 | 57 | //displaying stack 58 | void display() 59 | { 60 | System.out.println("Stack: "); 61 | for (int i=top; i>-1; i--) 62 | { 63 | System.out.print(" " + arr[i]); 64 | } 65 | } 66 | } 67 | 68 | class Main{ 69 | public static void main(String args[]){ 70 | Stack s = new Stack(); 71 | s.push(1); 72 | s.push(2); 73 | s.push(3); 74 | s.pop(); 75 | System.out.println("Top element is: " + s.peek()); 76 | s.display(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /LEARN.md: -------------------------------------------------------------------------------- 1 | # Learn Data Structures and Algorithms 2 | 3 | Irrespective of the programming language you choose to learn, the basic concepts of programming and data structures & algorithms are similar across languages. 4 | Some of `DSA` concepts include: 5 | - Arrays 6 | - Linked List 7 | - Stack 8 | - Queue 9 | - etc 10 | 11 | --- 12 | 13 | This is the repository where you can learn the `data structures and algorithms` practically with code examples, specifically in C++. 14 | Start learning by following the links below: 15 | 16 | --- 17 | 18 | ## C++ 19 | 20 | You can use [github.dev](https://github.dev/github/dev) for coding. Or you can setup your IDE on your local machine. 21 | You can setup `DevC++` or `CodeBlocks` or `VScode` for running c++ programs. 22 | 23 | 24 | - #### [Sparse Matrix](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/1-Sparse%20Matrix) 25 | 26 | - #### [Singly Linked List](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/2-Singly%20Linked%20List) 27 | 28 | - #### [Doubly Linked List](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/3-Doubly%20Linked%20List) 29 | 30 | - #### [Circular Singly Linked List](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/4-Circular%20singly%20linked%20list) 31 | 32 | - #### [Stack](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/5-Stack) 33 | 34 | - #### [Recursion](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/6-Recursion) 35 | 36 | - #### [Queue](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/7-Queue) 37 | 38 | - #### [Binary Search Tree(BST)](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/8-BST(Binary%20Search%20tree)) 39 | 40 | - #### [Heaps](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/9-Heaps) 41 | 42 | - #### [Searching Algorithms](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/10-Searching) 43 | 44 | - #### [Sorting Algorithms](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/11-Sorting%20Algorithms) 45 | 46 | - #### [Labs and Tasks](https://github.com/ShehrozIrfan/learn-dsa/tree/master/C%2B%2B/12.%20Labs%20%26%20Tasks) 47 | 48 | ## Java 49 | - #### [Sparse Matrix](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Sparse%20Matrix) 50 | 51 | - #### [Queue](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Queue) 52 | 53 | - #### [Stack](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Stack) 54 | 55 | - #### [Singly Linked List](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Singly%20Linked%20List) 56 | 57 | - #### [Doubly Linked List](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Doubly%20Linked%20List) 58 | 59 | - #### [Circular Linked List](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Circular%20Linked%20List) 60 | 61 | - #### [Recursion](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Recursion) 62 | 63 | - #### [Searching](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Searching) 64 | 65 | - #### [Binary Search Tree](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Binary%20Search%20Tree) 66 | 67 | - #### [Sorting Algorithm](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Sorting%20Algorithm) 68 | 69 | - #### [Program and Task](https://github.com/ShehrozIrfan/learn-dsa/tree/master/Java/Program%and%Task) 70 | 71 | --- 72 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Shehroz Irfan 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/Heaps/max_heap_usingOOP.py: -------------------------------------------------------------------------------- 1 | class MaxHeap: 2 | def __init__(self): 3 | self.heap = [] 4 | 5 | def push(self, value): 6 | self.heap.append(value) 7 | self._bubble_up(len(self.heap) - 1) 8 | 9 | def pop(self): 10 | if len(self.heap) == 0: 11 | return None 12 | if len(self.heap) == 1: 13 | return self.heap.pop() 14 | root = self.heap[0] 15 | self.heap[0] = self.heap.pop() 16 | self._sink(0) 17 | return root 18 | 19 | def _bubble_up(self, index): 20 | while index > 0: 21 | parent_index = (index - 1) // 2 22 | if self.heap[index] <= self.heap[parent_index]: 23 | break 24 | self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] 25 | index = parent_index 26 | 27 | def _sink(self, index): 28 | left_child_index = 2 * index + 1 29 | right_child_index = 2 * index + 2 30 | largest = index 31 | 32 | if ( 33 | left_child_index < len(self.heap) 34 | and self.heap[left_child_index] > self.heap[largest] 35 | ): 36 | largest = left_child_index 37 | if ( 38 | right_child_index < len(self.heap) 39 | and self.heap[right_child_index] > self.heap[largest] 40 | ): 41 | largest = right_child_index 42 | 43 | if largest != index: 44 | self.heap[index], self.heap[largest] = self.heap[largest], self.heap[index] 45 | self._sink(largest) 46 | 47 | # Example usage of the custom Max Heap: 48 | max_heap = MaxHeap() 49 | max_heap.push(3) 50 | max_heap.push(1) 51 | max_heap.push(4) 52 | max_heap.push(1) 53 | max_heap.push(5) 54 | max_heap.push(9) 55 | max_heap.push(2) 56 | max_heap.push(6) 57 | max_heap.push(5) 58 | max_heap.push(3) 59 | max_heap.push(5) 60 | 61 | max_sorted = [] 62 | while len(max_heap.heap) > 0: 63 | max_sorted.append(max_heap.pop()) 64 | 65 | print("Custom Max Heap Sorted:", max_sorted) 66 | -------------------------------------------------------------------------------- /Python/Heaps/min_heap_usingOOP.py: -------------------------------------------------------------------------------- 1 | class MinHeap: 2 | def __init__(self): 3 | self.heap = [] 4 | 5 | def push(self, value): 6 | self.heap.append(value) 7 | self._bubble_up(len(self.heap) - 1) 8 | 9 | def pop(self): 10 | if len(self.heap) == 0: 11 | return None 12 | if len(self.heap) == 1: 13 | return self.heap.pop() 14 | root = self.heap[0] 15 | self.heap[0] = self.heap.pop() 16 | self._sink(0) 17 | return root 18 | 19 | def _bubble_up(self, index): 20 | while index > 0: 21 | parent_index = (index - 1) // 2 22 | if self.heap[index] >= self.heap[parent_index]: 23 | break 24 | self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] 25 | index = parent_index 26 | 27 | def _sink(self, index): 28 | left_child_index = 2 * index + 1 29 | right_child_index = 2 * index + 2 30 | smallest = index 31 | 32 | if ( 33 | left_child_index < len(self.heap) 34 | and self.heap[left_child_index] < self.heap[smallest] 35 | ): 36 | smallest = left_child_index 37 | if ( 38 | right_child_index < len(self.heap) 39 | and self.heap[right_child_index] < self.heap[smallest] 40 | ): 41 | smallest = right_child_index 42 | 43 | if smallest != index: 44 | self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index] 45 | self._sink(smallest) 46 | 47 | # Example usage of the custom Min-Heap: 48 | min_heap = MinHeap() 49 | min_heap.push(3) 50 | min_heap.push(1) 51 | min_heap.push(4) 52 | min_heap.push(1) 53 | min_heap.push(5) 54 | min_heap.push(9) 55 | min_heap.push(2) 56 | min_heap.push(6) 57 | min_heap.push(5) 58 | min_heap.push(3) 59 | min_heap.push(5) 60 | 61 | min_sorted = [] 62 | while len(min_heap.heap) > 0: 63 | min_sorted.append(min_heap.pop()) 64 | 65 | print("Custom Min-Heap Sorted:", min_sorted) 66 | -------------------------------------------------------------------------------- /Python/LinkedList/LinkedList.py: -------------------------------------------------------------------------------- 1 | # Linked List implementation in Python. I have implemented the following functions: 2 | # 1. deleteNode(key) - deletes the node with the given key 3 | # 2. deleteNodeAtPosition(position) - deletes the node at the given position 4 | # 3. printList() - prints the linked list 5 | 6 | 7 | class Node: 8 | def __init__(self, data): 9 | self.data = data 10 | self.next = None 11 | 12 | class LinkedList: 13 | def __init__ (self): 14 | self.head = None 15 | 16 | def deleteNode(self, key): 17 | temp = self.head 18 | if(temp is not None): 19 | if(temp.data == key): 20 | self.head = temp.next 21 | temp = None 22 | return 23 | 24 | while(temp is not None): 25 | if(temp.data == key): 26 | break 27 | prev = temp 28 | temp = temp.next 29 | 30 | if(temp == None): 31 | return 32 | 33 | prev.next = temp.next 34 | temp = None 35 | 36 | def deleteNodeAtPosition(self, position): 37 | temp = self.head 38 | if(temp == None): 39 | return 40 | 41 | if(position == 0): 42 | self.head = temp.next 43 | temp = None 44 | return 45 | 46 | for i in range(position-1): 47 | temp = temp.next 48 | if(temp == None): 49 | break 50 | 51 | if(temp == None): 52 | return 53 | if(temp.next == None): 54 | return 55 | 56 | next = temp.next.next 57 | temp.next = None 58 | temp.next = next 59 | 60 | 61 | def printList(self): 62 | temp = self.head 63 | while(temp): 64 | print(temp.data) 65 | temp = temp.next 66 | 67 | if __name__ == '__main__': 68 | llist = LinkedList() 69 | llist.head = Node(10) 70 | second = Node(20) 71 | third = Node(30) 72 | fourth = Node(40) 73 | fifth = Node(50) 74 | sixth = Node(60) 75 | 76 | llist.head.next = second 77 | second.next = third 78 | print("Original List") 79 | llist.printList() 80 | print("List after deleting node with key 20") 81 | llist.deleteNode(20) 82 | 83 | llist.printList() 84 | print("List after deleting node at position 1") 85 | llist.deleteNodeAtPosition(1) 86 | 87 | llist.printList() 88 | 89 | -------------------------------------------------------------------------------- /Python/Queue/priority_queue.py: -------------------------------------------------------------------------------- 1 | # A simple implementation of Priority Queue 2 | # using Queue. 3 | class PriorityQueue(object): 4 | def __init__(self): 5 | self.queue = [] 6 | 7 | def __str__(self): 8 | return ' '.join([str(i) for i in self.queue]) 9 | 10 | # for checking if the queue is empty 11 | def isEmpty(self): 12 | return len(self.queue) == 0 13 | 14 | # for inserting an element in the queue 15 | def insert(self, data): 16 | self.queue.append(data) 17 | 18 | # for popping an element based on Priority 19 | def delete(self): 20 | try: 21 | max = 0 22 | for i in range(len(self.queue)): 23 | if self.queue[i] > self.queue[max]: 24 | max = i 25 | item = self.queue[max] 26 | del self.queue[max] 27 | return item 28 | except IndexError: 29 | print() 30 | exit() 31 | 32 | if __name__ == '__main__': 33 | myQueue = PriorityQueue() 34 | myQueue.insert(12) 35 | myQueue.insert(1) 36 | myQueue.insert(14) 37 | myQueue.insert(7) 38 | print(myQueue) 39 | while not myQueue.isEmpty(): 40 | print(myQueue.delete()) 41 | -------------------------------------------------------------------------------- /Python/Queue/queue_using_stack.py: -------------------------------------------------------------------------------- 1 | # Python3 program to implement Queue using 2 | # two stacks with costly enQueue() 3 | 4 | class Queue: 5 | def __init__(self): 6 | self.s1 = [] 7 | self.s2 = [] 8 | 9 | def enQueue(self, x): 10 | 11 | # Move all elements from s1 to s2 12 | while len(self.s1) != 0: 13 | self.s2.append(self.s1[-1]) 14 | self.s1.pop() 15 | 16 | # Push item into self.s1 17 | self.s1.append(x) 18 | 19 | # Push everything back to s1 20 | while len(self.s2) != 0: 21 | self.s1.append(self.s2[-1]) 22 | self.s2.pop() 23 | 24 | # Dequeue an item from the queue 25 | def deQueue(self): 26 | 27 | # if first stack is empty 28 | if len(self.s1) == 0: 29 | return -1; 30 | 31 | # Return top of self.s1 32 | x = self.s1[-1] 33 | self.s1.pop() 34 | return x 35 | 36 | # Driver code 37 | if __name__ == '__main__': 38 | q = Queue() 39 | q.enQueue(1) 40 | q.enQueue(2) 41 | q.enQueue(3) 42 | 43 | print(q.deQueue()) 44 | print(q.deQueue()) 45 | print(q.deQueue()) 46 | 47 | # This code is contributed by PranchalK 48 | -------------------------------------------------------------------------------- /Python/Sorting/BubbleSort.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(array): 2 | n = len(array) 3 | 4 | for i in range(n): 5 | # Create a flag that will allow the function to 6 | # terminate early if there's nothing left to sort 7 | already_sorted = True 8 | 9 | # Start looking at each item of the list one by one, 10 | # comparing it with its adjacent value. With each 11 | # iteration, the portion of the array that you look at 12 | # shrinks because the remaining items have already been 13 | # sorted. 14 | for j in range(n - i - 1): 15 | if array[j] > array[j + 1]: 16 | # If the item you're looking at is greater than its 17 | # adjacent value, then swap them 18 | array[j], array[j + 1] = array[j + 1], array[j] 19 | 20 | # Since you had to swap two elements, 21 | # set the `already_sorted` flag to `False` so the 22 | # algorithm doesn't finish prematurely 23 | already_sorted = False 24 | 25 | # If there were no swaps during the last iteration, 26 | # the array is already sorted, and you can terminate 27 | if already_sorted: 28 | break 29 | 30 | return array 31 | 32 | array = [1, 5, 6, 7, 3, 8, 9, 4] 33 | print(bubble_sort(array)) -------------------------------------------------------------------------------- /Python/Sorting/InsertionSort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(array): 2 | # Loop from the second element of the array until 3 | # the last element 4 | for i in range(1, len(array)): 5 | # This is the element we want to position in its 6 | # correct place 7 | key_item = array[i] 8 | 9 | # Initialize the variable that will be used to 10 | # find the correct position of the element referenced 11 | # by `key_item` 12 | j = i - 1 13 | 14 | # Run through the list of items (the left 15 | # portion of the array) and find the correct position 16 | # of the element referenced by `key_item`. Do this only 17 | # if `key_item` is smaller than its adjacent values. 18 | while j >= 0 and array[j] > key_item: 19 | # Shift the value one position to the left 20 | # and reposition j to point to the next element 21 | # (from right to left) 22 | array[j + 1] = array[j] 23 | j -= 1 24 | 25 | # When you finish shifting the elements, you can position 26 | # `key_item` in its correct location 27 | array[j + 1] = key_item 28 | 29 | return array 30 | 31 | array = [1,2,4,5,7,4,3,8,9,10,3,4,2,7,8] 32 | print(insertion_sort(array)) -------------------------------------------------------------------------------- /Python/Sorting/QuickSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Quicksort Sort 2 | 3 | # This implementation utilizes pivot as the last element in the nums list 4 | # It has a pointer to keep track of the elements smaller than the pivot 5 | # At the very end of partition() function, the pointer is swapped with the pivot 6 | # to come up with a "sorted" nums relative to the pivot 7 | 8 | 9 | # Function to find the partition position 10 | def partition(array, low, high): 11 | 12 | # choose the rightmost element as pivot 13 | pivot = array[high] 14 | 15 | # pointer for greater element 16 | i = low - 1 17 | 18 | # traverse through all elements 19 | # compare each element with pivot 20 | for j in range(low, high): 21 | if array[j] <= pivot: 22 | 23 | # If element smaller than pivot is found 24 | # swap it with the greater element pointed by i 25 | i = i + 1 26 | 27 | # Swapping element at i with element at j 28 | (array[i], array[j]) = (array[j], array[i]) 29 | 30 | # Swap the pivot element with the greater element specified by i 31 | (array[i + 1], array[high]) = (array[high], array[i + 1]) 32 | 33 | # Return the position from where partition is done 34 | return i + 1 35 | 36 | # function to perform quicksort 37 | 38 | 39 | def quickSort(array, low, high): 40 | if low < high: 41 | 42 | # Find pivot element such that 43 | # element smaller than pivot are on the left 44 | # element greater than pivot are on the right 45 | pi = partition(array, low, high) 46 | 47 | # Recursive call on the left of pivot 48 | quickSort(array, low, pi - 1) 49 | 50 | # Recursive call on the right of pivot 51 | quickSort(array, pi + 1, high) 52 | 53 | 54 | data = [1, 7, 4, 1, 10, 9, -2] 55 | print("Unsorted Array") 56 | print(data) 57 | 58 | size = len(data) 59 | 60 | quickSort(data, 0, size - 1) 61 | 62 | print('Sorted Array in Ascending Order:') 63 | print(data) 64 | -------------------------------------------------------------------------------- /Python/Sorting/Selection_sort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(arr): 2 | # Traverse through all array elements 3 | for i in range(len(arr)): 4 | # Find the minimum element in the remaining unsorted array 5 | min_idx = i 6 | for j in range(i+1, len(arr)): 7 | if arr[j] < arr[min_idx]: 8 | min_idx = j 9 | 10 | # Swap the found minimum element with the first element 11 | arr[i], arr[min_idx] = arr[min_idx], arr[i] 12 | 13 | return arr 14 | 15 | # Test 16 | arr = [64, 34, 25, 12, 22, 11, 90] 17 | print("Original array:", arr) 18 | sorted_arr = selection_sort(arr) 19 | print("Sorted array:", sorted_arr) 20 | -------------------------------------------------------------------------------- /Python/Sorting/ShellSort.py: -------------------------------------------------------------------------------- 1 | def shellSort(arr): 2 | n = len(arr) 3 | gap = n // 2 4 | 5 | while gap > 0: 6 | for i in range(gap, n): 7 | temp = arr[i] 8 | j = i 9 | while j >= gap and arr[j - gap] > temp: 10 | arr[j] = arr[j - gap] 11 | j -= gap 12 | arr[j] = temp 13 | gap //= 2 14 | 15 | # Example usage: 16 | arr = [12, 34, 54, 2, 3] 17 | shellSort(arr) 18 | print("Sorted array is:", arr) 19 | -------------------------------------------------------------------------------- /Python/Stack/StackImplementationList.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | 3 | # Constructor to initialize the stack 4 | def __init__(self, size): 5 | self.arr = [None] * size 6 | self.capacity = size 7 | self.top = -1 8 | 9 | # Function to add an element `val` to the stack 10 | def push(self, val): 11 | if self.isFull(): 12 | print('Stack Overflow!! Calling exit()…') 13 | exit(-1) 14 | 15 | print(f'Inserting {val} into the stack…') 16 | self.top = self.top + 1 17 | self.arr[self.top] = val 18 | 19 | # Function to pop a top element from the stack 20 | def pop(self): 21 | # check for stack underflow 22 | if self.isEmpty(): 23 | print('Stack Underflow!! Calling exit()…') 24 | exit(-1) 25 | 26 | print(f'Removing {self.peek()} from the stack') 27 | 28 | # decrease stack size by 1 and (optionally) return the popped element 29 | top = self.arr[self.top] 30 | self.top = self.top - 1 31 | return top 32 | 33 | # Function to return the top element of the stack 34 | def peek(self): 35 | if self.isEmpty(): 36 | exit(-1) 37 | return self.arr[self.top] 38 | 39 | # Function to return the size of the stack 40 | def size(self): 41 | return self.top + 1 42 | 43 | # Function to check if the stack is empty or not 44 | def isEmpty(self): 45 | return self.size() == 0 46 | 47 | # Function to check if the stack is full or not 48 | def isFull(self): 49 | return self.size() == self.capacity 50 | 51 | 52 | if __name__ == '__main__': 53 | 54 | stack = Stack(3) 55 | 56 | stack.push(1) # Inserting 1 in the stack 57 | stack.push(2) # Inserting 2 in the stack 58 | 59 | stack.pop() # removing the top element (2) 60 | stack.pop() # removing the top element (1) 61 | 62 | stack.push(3) # Inserting 3 in the stack 63 | 64 | print('Top element is', stack.peek()) 65 | print('The stack size is', stack.size()) 66 | 67 | stack.pop() # removing the top element (3) 68 | 69 | # check if the stack is empty 70 | if stack.isEmpty(): 71 | print('The stack is empty') 72 | else: 73 | print('The stack is not empty') -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn Data Structures and Algorithms 2 | 3 | This is a repository in which you can learn the data structures and algorithms practically, specifically in C++. The repository is divided into multiple folders like: 4 | - Sparse Matrix 5 | - Singly Linked List 6 | - Doubly Linked List 7 | - Circular Linked List 8 | - Stack 9 | - Recursion 10 | - Queue 11 | - Binary Search Tree 12 | - Heaps 13 | - Searching Algorithms 14 | - Sorting Algorithms 15 | - Labs And Tasks 16 | 17 | You can simply go to any folder, find a program related to that folder topic and learn from that, there are comments added in each program for better understanding. 18 | 19 | 20 | ## How to Learn 21 | 22 | Please visit [LEARN.md](https://github.com/ShehrozIrfan/learn-dsa/blob/master/LEARN.md) for contributions 23 | 24 | ## How to Contribute 25 | 26 | Please visit [CONTRIBUTE.md](https://github.com/ShehrozIrfan/learn-dsa/blob/master/CONTRIBUTING.md) for contributions 27 | 28 | ## Hacktoberfest 2023 29 | Hacktoberfest2022 Banner 30 | 31 |

32 | This year marks the 10th anniversary of Hacktoberfest, and we’re calling on your support! Whether it’s your first time participating—or your tenth—it’s almost time to hack out four pristine pull/merge requests as we continue our month of support for open source. 33 |

34 | 35 | #### What is Hacktoberfest? 36 |

37 | Hacktoberfest is a month-long celebration of open source software run by DigitalOcean in partnership with GitHub and Twilio. Hacktoberfest is open to everyone in our global community! Four quality pull requests must be submitted to public GitHub repositories. You can [sign up](https://hacktoberfest.com/) anytime between October 1 and October 31. 38 |

39 | --------------------------------------------------------------------------------