├── Amazon ├── Non-Tech.txt ├── binary_tree.h ├── binary_tree.cpp └── 1_distance_between_two_nodes_binary_tree.cpp ├── segment_tree └── src │ ├── seg_tree.h │ └── seg_tree.cpp ├── README.md ├── dp ├── CMakeLists.txt └── src │ ├── dp.h │ ├── main.cpp │ └── dp.cpp ├── arrays ├── CMakeLists.txt └── src │ ├── main.cpp │ ├── array.h │ └── array.cpp ├── math ├── CMakeLists.txt └── src │ ├── math.h │ ├── main.cpp │ └── math.cpp ├── misc ├── CMakeLists.txt └── src │ ├── misc.h │ ├── main.cpp │ └── misc.cpp ├── strings ├── CMakeLists.txt └── src │ ├── strings.h │ ├── main.cpp │ └── strings.cpp ├── heap ├── CMakeLists.txt └── src │ ├── main.cpp │ ├── heap.h │ └── heap.cpp ├── binary_tree ├── CMakeLists.txt └── src │ ├── main.cpp │ ├── binary_tree.h │ └── binary_tree.cpp ├── linked_list ├── CMakeLists.txt └── src │ ├── roman.py │ ├── main.cpp │ ├── linked_list.h │ └── linked_list.cpp ├── search_sort ├── CMakeLists.txt └── src │ ├── main.cpp │ ├── search_sort.h │ └── search_sort.cpp ├── bits ├── bits.h └── bits.cpp ├── Searching_and_Sorting ├── 1_binary_search.cpp ├── 3_kth_smallest_largest_number.cpp └── 2_quick_sort.cpp ├── stacks_queue └── src │ ├── stacks_queue.h │ └── stacks_queue.cpp └── To_Do_Microsoft /Amazon/Non-Tech.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Amazon/binary_tree.h: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A Binary Tree Node 5 | struct Node 6 | { 7 | struct Node *left, *right; 8 | int key; 9 | }; 10 | 11 | Node* newNode(int data); -------------------------------------------------------------------------------- /segment_tree/src/seg_tree.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // Segment Tree | Set 1 (Sum of given range) 6 | 7 | int getSumUtil(int *st, int ss, int se, int qs, int qe, int si) ; -------------------------------------------------------------------------------- /Amazon/binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include "binary_tree.h" 2 | 3 | Node* newNode(int data) 4 | { 5 | struct Node* newnode = new Node; 6 | newnode->left = NULL; 7 | newnode->right = NULL; 8 | newnode->key = data; 9 | return newnode; 10 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding-Practice 2 | My personal repository to practice coding questions before interviews 3 | 4 | I Always would go scurrying about Interview questions etc before any interview. 5 | So I thought I would practice regularly and add them up here :) 6 | -------------------------------------------------------------------------------- /dp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(dp) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(dp src/main.cpp src/dp.cpp src/dp.h) 9 | 10 | target_link_libraries(dp) -------------------------------------------------------------------------------- /arrays/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(dp) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(dp src/main.cpp src/dp.cpp src/dp.h) 9 | 10 | target_link_libraries(dp) -------------------------------------------------------------------------------- /math/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(dp) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(dp src/main.cpp src/dp.cpp src/dp.h) 9 | 10 | target_link_libraries(dp) -------------------------------------------------------------------------------- /misc/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(dp) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(dp src/main.cpp src/dp.cpp src/dp.h) 9 | 10 | target_link_libraries(dp) -------------------------------------------------------------------------------- /strings/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(dp) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(dp src/main.cpp src/dp.cpp src/dp.h) 9 | 10 | target_link_libraries(dp) -------------------------------------------------------------------------------- /heap/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(heap) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(heap src/main.cpp src/heap.cpp src/heap.h) 9 | 10 | target_link_libraries(heap) -------------------------------------------------------------------------------- /binary_tree/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(Tree) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(bin_tree src/main.cpp src/binary_tree.cpp src/binary_tree.h) 9 | 10 | target_link_libraries(bin_tree ) -------------------------------------------------------------------------------- /linked_list/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(linked_list) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(linked_list src/main.cpp src/linked_list.cpp src/linked_list.h) 9 | 10 | target_link_libraries(linked_list) -------------------------------------------------------------------------------- /search_sort/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.3) 2 | project(search_sort) 3 | 4 | set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build) 5 | 6 | set (CMAKE_CXX_STANDARD 11) 7 | 8 | add_executable(search_sort src/main.cpp src/search_sort.cpp src/search_sort.h) 9 | 10 | target_link_libraries(search_sort) -------------------------------------------------------------------------------- /bits/bits.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int countSetBits(int n) ; 6 | 7 | // Copy set bits in range [l, r] from y to x. 8 | // Note that x is passed by reference and modified 9 | // by this function. 10 | void copySetBits(unsigned &x, unsigned y, 11 | unsigned l, unsigned r) ; -------------------------------------------------------------------------------- /math/src/math.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int fib_recur(int n) ; 6 | 7 | int fib_dp(int n) ; 8 | 9 | int fib_space_optimized(int n) ; 10 | 11 | void SieveOfEratosthenes(int n) ; 12 | 13 | int gcd(int a, int b) ; 14 | 15 | int generalizedGCD(int num, int* arr) ; // GCD of an array -------------------------------------------------------------------------------- /Searching_and_Sorting/1_binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int binary_search(int arr[], int l, int r, int x) 4 | { 5 | if(l<=r) 6 | { 7 | mid = l + (r-l)/2 ; 8 | 9 | if(arr[mid] == x) 10 | return mid 11 | 12 | else if(arr[mid] > x) 13 | return binary_search(arr,l,mid-1,x); 14 | else 15 | return binary_search(arr,mid+1,r,x); 16 | } 17 | return -1; 18 | } -------------------------------------------------------------------------------- /strings/src/strings.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | bool areParanthesisBalanced(string expr) ; 6 | 7 | void permute(char *a, int l, int r) ; 8 | 9 | void swap(char *a,char *b) ; 10 | 11 | void rev(string& s,int l,int r) ; 12 | 13 | int bsearch (string& s,int l,int r,int key) ; 14 | 15 | // Find next greater number with same set of digits 16 | 17 | void findNext(char number[], int n) ; 18 | 19 | void reverseStr(string& str) ; -------------------------------------------------------------------------------- /misc/src/misc.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // A recursive program to print all possible 6 | // partitions of a given string into dictionary 7 | // words 8 | 9 | void wordBreak(string str) ; 10 | 11 | int getPairsCount(int arr[], int n, int sum) ; 12 | 13 | // Largest Rectangular Area in a Histogram | Set 2 14 | 15 | // The main function to find the maximum rectangular 16 | // area under given histogram with n bars 17 | 18 | int getMaxArea(int hist[], int n) -------------------------------------------------------------------------------- /linked_list/src/roman.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | dict_roman = {} 5 | 6 | dict_roman['I'] = 1 7 | dict_roman['V'] = 5 8 | dict_roman['X'] = 10 9 | 10 | str_roman = 'III' 11 | 12 | count = 0 13 | 14 | 15 | for a in str_roman: 16 | count += dict_roman[a] 17 | 18 | 19 | for i in range(len(str_roman) - 1): 20 | 21 | curr_val = dict_roman[str_roman[i]] 22 | 23 | next_val = dict_roman[str_roman[i+1]] 24 | 25 | if str_roman[i] == str_roman[i+1]: 26 | count += curr_val 27 | 28 | elif (next_val > curr_val): 29 | count = count - curr_val 30 | 31 | else: 32 | count += curr_val 33 | 34 | 35 | 36 | count += dict_roman[len(str_roman) - 1 ] -------------------------------------------------------------------------------- /dp/src/dp.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int lis( int arr[], int n ) ; 6 | 7 | int lcs( char *X, char *Y, int m, int n ); 8 | 9 | int maxSubArraySum(int a[], int size); 10 | 11 | int editDistDP(string str1, string str2, int m, int n); 12 | 13 | int minCost(int cost[R][C], int m, int n) ; 14 | 15 | int count_coin( int S[], int m, int n ); 16 | 17 | int knapSack(int W, int wt[], int val[], int n); 18 | 19 | int longestPalSubstr( char *str ) ; 20 | 21 | // Max Size Square : 22 | 23 | 24 | void printMaxSubSquare(bool M[R][C]) ; 25 | 26 | // Max Size rectangle : 27 | 28 | // Returns area of the largest rectangle with all 1s in A[][] 29 | int maxRectangle(int A[][C]) ; 30 | 31 | int maxSubarrayProduct(int arr[], int n) ; -------------------------------------------------------------------------------- /dp/src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "binary_tree.h" 2 | 3 | int main() 4 | { 5 | // Let us create binary tree given in the 6 | // above example 7 | Node * root = newNode(1); 8 | root->left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<left = newNode(2); 9 | root->right = newNode(3); 10 | root->left->left = newNode(4); 11 | root->left->right = newNode(5); 12 | root->right->left = newNode(6); 13 | root->right->right = newNode(7); 14 | root->right->left->right = newNode(8); 15 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 16 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 17 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 18 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 19 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)<> 1); 12 | } 13 | 14 | void copySetBits(unsigned &x, unsigned y, 15 | unsigned l, unsigned r) 16 | { 17 | // l and r must be between 1 to 32 18 | // (assuming ints are stored using 19 | // 32 bits) 20 | if (l < 1 || r > 32) 21 | return ; 22 | 23 | // Travers in given range 24 | for (int i=l; i<=r; i++) 25 | { 26 | // Find a mask (A number whose 27 | // only set bit is at i'th position) 28 | int mask = 1 << (i-1); 29 | 30 | // If i'th bit is set in y, set i'th 31 | // bit in x also. 32 | if (y & mask) 33 | x = x | mask; 34 | } 35 | } -------------------------------------------------------------------------------- /heap/src/heap.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // A class for Max Heap 6 | class MaxHeap 7 | { 8 | int *harr; // pointer to array of elements in heap 9 | int capacity; // maximum possible size of max heap 10 | int heap_size; // Current number of elements in max heap 11 | public: 12 | MaxHeap(int a[], int size); // Constructor 13 | void maxHeapify(int i); //To maxHeapify subtree rooted with index i 14 | int parent(int i) { return (i-1)/2; } 15 | int left(int i) { return (2*i + 1); } 16 | int right(int i) { return (2*i + 2); } 17 | 18 | int extractMax(); // extracts root (maximum) element 19 | int getMax() { return harr[0]; } // Returns maximum 20 | 21 | // to replace root with new node x and heapify() new root 22 | void replaceMax(int x) { harr[0] = x; maxHeapify(0); } 23 | }; 24 | 25 | 26 | 27 | void heapify(int arr[], int n, int i) ; 28 | 29 | void heapSort(int arr[], int n) ; 30 | 31 | -------------------------------------------------------------------------------- /Searching_and_Sorting/3_kth_smallest_largest_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int partition(int arr[], int l, int r); 6 | 7 | int kthSmallest(int arr[], int l, int r, int k) 8 | { 9 | if(k>0 && k<=r-l+1) 10 | { 11 | int pos = partition(arr,l,r) 12 | 13 | if(pos-l == k-1 ) 14 | return arr[pos]; 15 | if(pos-l > k-1 ) 16 | return kthSmallest(arr,l,pos-1,k); 17 | return kthSmallest(arr,pos+1,r,k); 18 | } 19 | 20 | return INT_MAX; 21 | } 22 | 23 | void swap(int *a, int *b) 24 | { 25 | int temp = *a; 26 | *a = *b; 27 | *b = temp; 28 | } 29 | 30 | int partition(int arr[], int l, int r) 31 | { 32 | int i = l; 33 | int pivot = arr[r]; 34 | 35 | for(int j = l;j 2 | 3 | void swap(int* a, int* b) 4 | { 5 | int t = *a; 6 | *a = *b; 7 | *b = t; 8 | } 9 | 10 | 11 | int partition(int arr[],int low,int high) 12 | { 13 | int pivot = arr[high]; 14 | int i = (low -1); 15 | 16 | for(int j = low;j 2 | #include 3 | using namespace std; 4 | 5 | int binarySearch(int arr[], int l, int r, int x) ; 6 | 7 | void merge(int arr[], int l, int m, int r); 8 | 9 | void mergeSort(int arr[], int l, int r); 10 | 11 | int partition (int arr[], int low, int high); 12 | 13 | void quickSort(int arr[], int low, int high); 14 | 15 | void swap(int* a, int* b); 16 | 17 | int kthSmallest(int arr[], int l, int r, int k); 18 | 19 | int randomPartition(int arr[], int l, int r) ; 20 | 21 | void quickSort(int arr[], int low, int high); 22 | 23 | int kthSmallest(int arr[], int l, int r, int k); 24 | 25 | // Searches an element key in a pivoted sorted array arr[] of size n 26 | 27 | int pivotedBinarySearch(int arr[], int n, int key) ; 28 | 29 | int findPivot(int arr[], int low, int high) ; 30 | 31 | // Median of two sorted arrays with different sizes 32 | double findMedianSortedArrays(int *a, int n, int *b, int m) ; 33 | 34 | void sort012(int a[], int arr_size) ; 35 | 36 | /* This function returns 37 | median of ar1[] and ar2[]. 38 | Assumptions in this function: 39 | Both ar1[] and ar2[] 40 | are sorted arrays 41 | Both have n elements */ 42 | int getMedian(int ar1[], int ar2[], int n) ; 43 | 44 | -------------------------------------------------------------------------------- /arrays/src/array.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void swap(int *a, int *b); 6 | 7 | int partition(int arr[], int l, int r); 8 | 9 | void quickSort(int A[], int si, int ei) ; 10 | 11 | // Largest Sum Contiguous Subarray 12 | // Kadane's Algorithm 13 | 14 | int maxSubArraySum(int a[], int size) ; 15 | 16 | int subArraySum(int arr[], int n, int sum) ; 17 | 18 | // Kth smallest 19 | 20 | int kthSmallest(int arr[], int l, int r, int k); 21 | 22 | void rotateMatrix(int mat[][N]) ; 23 | 24 | // Find Majority Element 25 | 26 | int findCandidate(int a[], int size) ; 27 | 28 | bool isMajority(int a[], int size, int cand) ; 29 | 30 | // Maximum Area Histogram 31 | 32 | int getMaxArea(int hist[], int n) ; 33 | 34 | // Sudoku Back Tracking 35 | 36 | bool SolveSudoku(int grid[N][N]) ; 37 | 38 | bool FindUnassignedLocation(int grid[N][N], int &row, int &col) ; 39 | 40 | bool UsedInRow(int grid[N][N], int row, int num) ; 41 | 42 | bool UsedInCol(int grid[N][N], int col, int num) ; 43 | 44 | bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num) ; 45 | 46 | bool isSafe(int grid[N][N], int row, int col, int num) ; 47 | 48 | // Find the length of largest subarray with 0 sum 49 | 50 | // Returns Length of the required subarray 51 | 52 | int maxLen(int arr[], int n) ; 53 | 54 | // C program to find whether an array 55 | // is subset of another array 56 | // (Use Sorting and Binary Search) 57 | 58 | bool isSubset(int arr1[], int arr2[], int m, int n) ; -------------------------------------------------------------------------------- /math/src/math.cpp: -------------------------------------------------------------------------------- 1 | #include "math.h" 2 | 3 | //Fibonacci Series using Recursion 4 | 5 | int fib_recur(int n) 6 | { 7 | if (n <= 1) 8 | return n; 9 | return fib(n-1) + fib(n-2); 10 | } 11 | 12 | // DP 13 | 14 | int fib_dp(int n) 15 | { 16 | int f[n+2]; // 1 extra to handle case, n = 0 17 | int i; 18 | 19 | f[0] = 0; 20 | f[1] = 1; 21 | 22 | for (i = 2; i <= n; i++) 23 | f[i] = f[i-1] + f[i-2]; 24 | 25 | return f[n]; 26 | } 27 | 28 | 29 | int fib_space_optimized(int n) 30 | { 31 | int a = 0, b = 1, c, i; 32 | 33 | if( n == 0) 34 | return a; 35 | 36 | for (i = 2; i <= n; i++) 37 | { 38 | c = a + b; 39 | a = b; 40 | b = c; 41 | } 42 | 43 | return b; 44 | } 45 | 46 | void SieveOfEratosthenes(int n) 47 | { 48 | // Create a boolean array "prime[0..n]" and initialize 49 | // all entries it as true. A value in prime[i] will 50 | // finally be false if i is Not a prime, else true. 51 | bool prime[n+1]; 52 | memset(prime, true, sizeof(prime)); 53 | 54 | for (int p=2; p*p<=n; p++) 55 | { 56 | // If prime[p] is not changed, then it is a prime 57 | if (prime[p] == true) 58 | { 59 | // Update all multiples of p 60 | for (int i=p*2; i<=n; i += p) 61 | prime[i] = false; 62 | } 63 | } 64 | 65 | // Print all prime numbers 66 | for (int p=2; p<=n; p++) 67 | if (prime[p]) 68 | cout << p << " "; 69 | } 70 | 71 | int gcd(int a, int b) 72 | { 73 | if (a == 0) 74 | return b; 75 | return gcd(b % a, a); 76 | } 77 | 78 | int generalizedGCD(int num, int* arr) // GCD of an array 79 | { 80 | // WRITE YOUR CODE HERE 81 | 82 | int res = arr[0]; 83 | 84 | for(int i = 1;i< num;i++) 85 | { 86 | res = gcd(arr[i],res); 87 | } 88 | 89 | return res; 90 | } 91 | -------------------------------------------------------------------------------- /Amazon/1_distance_between_two_nodes_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | /* Program to find distance between n1 and n2 using 2 | one traversal */ 3 | 4 | #include "binary_tree.h" 5 | 6 | // Returns level of key k if it is present in tree, 7 | // otherwise returns -1 8 | int findLevel(Node *root, int k, int level) 9 | { 10 | if(root == NULL) 11 | return -1 ; 12 | 13 | if(root->key == k) 14 | return level; 15 | 16 | int l = findLevel(root->left,k,level+1); 17 | 18 | if(l != -1) 19 | return l; 20 | else 21 | return findLevel(root->right,k,level+1); 22 | } 23 | 24 | Node *findDistUtil(Node* root, int n1, int n2, int &d1, 25 | int &d2, int &dist, int lvl) 26 | { 27 | if(root == NULL) 28 | return NULL; 29 | 30 | if(root->key == n1) 31 | { 32 | d1 = lvl; 33 | return root; 34 | } 35 | 36 | if(root->key == n2) 37 | { 38 | d2 = lvl; 39 | return root; 40 | } 41 | 42 | 43 | Node* left_lca = findDistUtil(root->left, n1, n2, d1, d2, dist, lvl+1); 44 | Node* right_lca = findDistUtil(root->right, n1, n2, d1, d2, dist, lvl+1); 45 | 46 | if(left_lca && right_lca) 47 | { 48 | dist = d1 + d2 - 2*lvl; 49 | return root; 50 | } 51 | 52 | if(left_lca != NULL) 53 | { 54 | return left_lca; 55 | } 56 | else 57 | { 58 | return right_lca; 59 | } 60 | } 61 | 62 | int findDistance(Node *root, int n1, int n2) 63 | { 64 | int d1 = -1, d2 = -1, dist; 65 | 66 | Node *lca = findDistUtil(root, n1, n2, d1, d2, dist, 1); 67 | 68 | if(d1 != -1 && d2 != -1) 69 | return dist; 70 | 71 | if(d1 != -1) 72 | return findLevel(lca, n2, 0); 73 | 74 | if(d2 != -1) 75 | return findLevel(lca, n1, 0); 76 | 77 | return -1; 78 | } 79 | 80 | int main() 81 | { 82 | // Let us create binary tree given in the 83 | // above example 84 | Node * root = newNode(1); 85 | root->left = newNode(2); 86 | root->right = newNode(3); 87 | root->left->left = newNode(4); 88 | root->left->right = newNode(5); 89 | root->right->left = newNode(6); 90 | root->right->right = newNode(7); 91 | root->right->left->right = newNode(8); 92 | cout << "Dist(4, 5) = " << findDistance(root, 4, 5); 93 | cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); 94 | cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); 95 | cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); 96 | cout << "\nDist(8, 5) = " << findDistance(root, 8, 5)< 2 | #include 3 | using namespace std; 4 | 5 | void printPrevSmaller(int arr[], int n) ; 6 | 7 | /* Program to implement a stack using 8 | two queue */ 9 | 10 | class Stack 11 | { 12 | // Two inbuilt queues 13 | queue q1, q2; 14 | 15 | // To maintain current number of 16 | // elements 17 | int curr_size; 18 | 19 | public: 20 | Stack() 21 | { 22 | curr_size = 0; 23 | } 24 | 25 | void push(int x) ; 26 | 27 | void pop() 28 | { 29 | // if no elements are there in q1 30 | if (q1.empty()) 31 | return ; 32 | q1.pop(); 33 | curr_size--; 34 | } 35 | 36 | int top() 37 | { 38 | if (q1.empty()) 39 | return -1; 40 | return q1.front(); 41 | } 42 | 43 | int size() 44 | { 45 | return curr_size; 46 | } 47 | }; 48 | 49 | 50 | // CPP program to implement Queue using 51 | // two stacks with costly enQueue() 52 | 53 | struct Queue { 54 | stack s1, s2; 55 | 56 | void enQueue(int x) 57 | { 58 | // Move all elements from s1 to s2 59 | while (!s1.empty()) { 60 | s2.push(s1.top()); 61 | s1.pop(); 62 | } 63 | 64 | // Push item into s1 65 | s1.push(x); 66 | 67 | // Push everything back to s1 68 | while (!s2.empty()) { 69 | s1.push(s2.top()); 70 | s2.pop(); 71 | } 72 | } 73 | 74 | // Dequeue an item from the queue 75 | int deQueue() 76 | { 77 | // if first stack is empty 78 | if (s1.empty()) { 79 | cout << "Q is Empty"; 80 | exit(0); 81 | } 82 | 83 | // Return top of s1 84 | int x = s1.top(); 85 | s1.pop(); 86 | return x; 87 | } 88 | }; 89 | 90 | 91 | struct MyStack ; 92 | 93 | // A stack based efficient method to calculate 94 | // stock span values 95 | void calculateSpan(int price[], int n, int S[]) ; 96 | 97 | // Function to find precedence of 98 | // operators. 99 | int precedence(char op) ; 100 | 101 | // Function to perform arithmetic operations. 102 | int applyOp(int a, int b, char op) ; 103 | 104 | // Function that returns value of 105 | // expression after evaluation. 106 | int evaluate(string tokens) ; -------------------------------------------------------------------------------- /heap/src/heap.cpp: -------------------------------------------------------------------------------- 1 | #include "heap.h" 2 | 3 | MaxHeap::MaxHeap(int a[], int size) 4 | { 5 | heap_size = size; 6 | harr = a; // store address of array 7 | int i = (heap_size - 1)/2; 8 | while (i >= 0) 9 | { 10 | maxHeapify(i); 11 | i--; 12 | } 13 | } 14 | 15 | // Method to remove maximum element (or root) from max heap 16 | int MaxHeap::extractMax() 17 | { 18 | if (heap_size == 0) 19 | return INT_MAX; 20 | 21 | // Store the maximum vakue. 22 | int root = harr[0]; 23 | 24 | // If there are more than 1 items, move the last item to root 25 | // and call heapify. 26 | if (heap_size > 1) 27 | { 28 | harr[0] = harr[heap_size-1]; 29 | maxHeapify(0); 30 | } 31 | heap_size--; 32 | 33 | return root; 34 | } 35 | 36 | // A recursive method to heapify a subtree with root at given index 37 | // This method assumes that the subtrees are already heapified 38 | void MaxHeap::maxHeapify(int i) 39 | { 40 | int l = left(i); 41 | int r = right(i); 42 | int largest = i; 43 | if (l < heap_size && harr[l] > harr[i]) 44 | largest = l; 45 | if (r < heap_size && harr[r] > harr[largest]) 46 | largest = r; 47 | if (largest != i) 48 | { 49 | swap(&harr[i], &harr[largest]); 50 | maxHeapify(largest); 51 | } 52 | } 53 | 54 | 55 | void heapify(int arr[], int n, int i) 56 | { 57 | int largest = i; // Initialize largest as root 58 | int l = 2*i + 1; // left = 2*i + 1 59 | int r = 2*i + 2; // right = 2*i + 2 60 | 61 | // If left child is larger than root 62 | if (l < n && arr[l] > arr[largest]) 63 | largest = l; 64 | 65 | // If right child is larger than largest so far 66 | if (r < n && arr[r] > arr[largest]) 67 | largest = r; 68 | 69 | // If largest is not root 70 | if (largest != i) 71 | { 72 | swap(arr[i], arr[largest]); 73 | 74 | // Recursively heapify the affected sub-tree 75 | heapify(arr, n, largest); 76 | } 77 | } 78 | 79 | // main function to do heap sort 80 | 81 | // Heap Sort Algorithm for sorting in increasing order: 82 | // 1. Build a max heap from the input data. 83 | // 2. At this point, the largest item is stored at the root of the heap. 84 | // Replace it with the last item of the heap followed by reducing the size of heap by 1. 85 | // Finally, heapify the root of tree. 86 | // 3. Repeat above steps while size of heap is greater than 1. 87 | 88 | void heapSort(int arr[], int n) 89 | { 90 | // Build heap (rearrange array) 91 | for (int i = n / 2 - 1; i >= 0; i--) 92 | heapify(arr, n, i); 93 | 94 | // One by one extract an element from heap 95 | for (int i=n-1; i>=0; i--) 96 | { 97 | // Move current root to end 98 | swap(arr[0], arr[i]); 99 | 100 | // call max heapify on the reduced heap 101 | heapify(arr, i, 0); 102 | } 103 | } -------------------------------------------------------------------------------- /linked_list/src/linked_list.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // A linked list node 6 | struct Node 7 | { 8 | int data; 9 | struct Node *next; 10 | }; 11 | 12 | void printList(struct Node *n); // Done 13 | 14 | void push(struct Node** head_ref, int new_data); // Done 15 | 16 | void insertAfter(struct Node* prev_node, int new_data); // Done 17 | 18 | void append(struct Node** head_ref, int new_data); // Done 19 | 20 | void deleteNode(struct Node **head_ref, int position); // Done 21 | 22 | Node *deleteKthNode(struct Node *head, int k) ; 23 | 24 | void deleteList(struct Node** head_ref); // Done 25 | 26 | int getCount(struct Node* head); // Done 27 | 28 | int GetNth(struct Node* head, int index); // Done 29 | 30 | void printNthFromLast(struct Node *head, int n); // Done 31 | 32 | void recursiveReverse(struct Node** head_ref); 33 | 34 | void reverse(struct Node** head_ref); // Done 35 | 36 | void printMiddle(struct Node *head); // Done 37 | 38 | void rotate(struct Node **head_ref, int k); // Done 39 | 40 | struct Node* SortedMerge(struct Node* a, struct Node* b) ; // Done 41 | 42 | // Merge two sorted linked lists such that merged list is in reverse order 43 | 44 | struct Node* SortedMergeReverse(Node *a, Node *b) ; 45 | 46 | // Intersection of linkedlist 47 | 48 | int getIntesectionNode(struct Node* head1, struct Node* head2) ; 49 | 50 | // Add two Linked Lists 51 | 52 | struct node* addSameSize(Node* head1, Node* head2, int* carry); 53 | 54 | void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result); 55 | 56 | void addList(Node* head1, Node* head2, Node** result); 57 | 58 | //least significant digit is first node 59 | struct Node* addTwoLists (struct Node* first, struct Node* second); 60 | 61 | // Flatten 62 | // Code : https://www.geeksforgeeks.org/flattening-a-linked-list/ 63 | 64 | struct Node* flatten (Node* root); 65 | 66 | // Returns true if there is a loop in linked list 67 | // else returns false. 68 | 69 | bool detectLoop(struct Node *h) ; // Using Map 70 | 71 | int detectloop_floyd(struct Node *list) ; // Using Two pointers 72 | 73 | struct Node *reverse (struct Node *head, int k) ; // Reverse Nodes in Set of K -- Nodes 74 | 75 | void BinaryTree2DoubleLinkedList(node *root, node **head) ; // Convert Binary tree to DLL 76 | 77 | // Pairwise Swap 78 | 79 | void pairWiseSwap(struct Node *head) ; // Swap Data 80 | 81 | void pairWiseSwap_inplace(struct Node **head) ; 82 | 83 | // Remove Duplicates 84 | 85 | void removeDuplicates(struct Node* head) ; 86 | 87 | // Detect and Remove Loop 88 | 89 | int detectAndRemoveLoop(struct Node *list) ; 90 | 91 | void removeLoop(struct Node *loop_node, struct Node *head) ; 92 | 93 | // Count Loop nodes 94 | 95 | int countNodes(struct Node *n) ; 96 | 97 | int countNodesinLoop(struct Node *list) ; 98 | 99 | // Clone a Linked List 100 | 101 | Node* clone(Node *start) ; -------------------------------------------------------------------------------- /binary_tree/src/binary_tree.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // A Binary Tree Node 6 | struct Node 7 | { 8 | struct Node *left, *right; 9 | int key; 10 | }; 11 | 12 | struct Node* newNode(int data); 13 | 14 | // All Traversals 15 | void printPostorder(struct Node* node); 16 | void printInorder(struct Node* node); 17 | void printPreorder(struct Node* node); 18 | 19 | void inOrder(struct Node *root); // Without recurssion 20 | void iterativePreorder(node *root); 21 | 22 | void NthInorder(struct Node* node, int n); 23 | void NthPostordernode(struct Node* root, int N) 24 | 25 | void insert(struct Node* temp, int key); 26 | 27 | int findLevel(Node *root, int k, int level); 28 | 29 | struct Node *findDistUtil(Node* root, int n1, int n2, 30 | int &d1, int &d2, int &dist, int lvl) ; 31 | 32 | int findDistance(Node *root, int n1, int n2); 33 | 34 | void deletDeepest(struct Node *root,struct Node * d_node); 35 | 36 | void deletion(struct Node* root, int key); 37 | 38 | bool isMirror(struct Node* root1, struct Node* root2); 39 | 40 | bool isSymmetric(struct Node* root); 41 | 42 | int identicalTrees(struct node* a, struct node* b) ; 43 | 44 | int height(struct Node* node); 45 | 46 | void printGivenLevel(struct Node* root, int level); 47 | 48 | void printLevelOrder(struct Node* root); 49 | 50 | void printLevelOrder_queue(struct Node* root); 51 | 52 | void printBoundary (struct node* root) ; // Boundary Traversal 53 | 54 | void printBoundaryLeft(struct node* root) ; 55 | 56 | void printBoundaryRight(struct node* root) ; 57 | 58 | void printLeaves(struct node* root) ; 59 | 60 | // Spiral print level order 61 | void printSpiral(struct Node* root); 62 | 63 | void printGivenLevel(struct Node* root, int level, int ltr); 64 | 65 | // Construction 66 | 67 | struct Node* buildTree(char in[], char pre[], int inStrt, int inEnd) ; 68 | 69 | int search(char arr[], int strt, int end, char value); 70 | 71 | struct Node *findLCA(struct Node* root, int n1, int n2); 72 | 73 | int diameter(struct node * tree); 74 | 75 | int getLevelUtil(struct node *node, int data, int level); 76 | 77 | int getLevel(struct node *node, int data); 78 | 79 | int getLeafCount(struct node* node); 80 | 81 | void leftViewUtil(struct node *root, int level, int *max_level) ; 82 | 83 | void leftView(struct node *root) ; 84 | 85 | void bottomView(Node *root) ; 86 | 87 | void printVerticalOrder(Node* root) ; 88 | 89 | bool isBalanced(struct node *root) ; 90 | 91 | // Binary tree to DLL 92 | 93 | node* bintree2listUtil(node* root) ; 94 | 95 | node* bintree2list(node *root) ; 96 | 97 | // Create a mirror of binary tree 98 | 99 | void mirror(struct Node* node) ; 100 | 101 | // BST 102 | 103 | int isBST(struct node* node) ; 104 | 105 | int isBSTUtil(struct node* node, int min, int max) ; 106 | 107 | // BST : Root to leaf path sum 108 | 109 | int checkThesum(struct Node *root, int path[], int i, int sum) ; 110 | 111 | // Root to leaf path sum : 112 | 113 | // Root to leaf path sum equal to a given number 114 | 115 | // Given a binary tree and a number, return true if the tree has a root-to-leaf path such 116 | // that adding up all the values along the path equals the given number. 117 | // Return false if no such path can be found. 118 | 119 | bool hasPathSum(struct node* node, int sum) ; 120 | 121 | // Sum of all the numbers that are formed from root to leaf paths 122 | 123 | // Returns sum of all root to leaf paths. The first parameter is root 124 | // of current subtree, the second parameter is value of the number formed 125 | // by nodes from root to this node 126 | int treePathsSumUtil(struct node *root, int val) ; 127 | 128 | // A wrapper function over treePathsSumUtil() 129 | int treePathsSum(struct node *root) ; 130 | 131 | // Flatten Linked List 132 | 133 | void flatten(struct Node* root) ; -------------------------------------------------------------------------------- /To_Do_Microsoft: -------------------------------------------------------------------------------- 1 | Arrays : 2 | 3 | Max Sum Contiguous Subarray // Done : Kadane 4 | Spiral Order Matrix I 5 | Spiral Order Matrix II 6 | Next Permutation 7 | Anti Diagonals 8 | 9 | Math : 10 | 11 | Grid Unique Paths 12 | Trailing Zeros in Factorial 13 | 14 | Binary Search : 15 | 16 | Median of Array // To Do 17 | Square Root of Integer 18 | Search for a Range 19 | Rotated Sorted Array Search // Done 20 | 21 | Strings : 22 | 23 | Implement StrStr 24 | Integer To Roman 25 | Roman To Integers // Done 26 | Multiply Strings 27 | Atoi 28 | Longest Palindromic Substring 29 | Pretty Json 30 | Reverse the String // Done 31 | 32 | Bit Manipulation: 33 | 34 | Divide Integers 35 | 36 | Two Pointers : 37 | 38 | Merge Two Sorted Lists II 39 | 3 Sum 40 | Remove Duplicates from Sorted Array 41 | Sort by Color 42 | Array 3 Pointers 43 | Remove Duplicates from Sorted Array II 44 | Minimize the absolute difference 45 | 46 | Tree Data Structure : 47 | 48 | Inorder Traversal // Done 49 | Recover Binary Search Tree 50 | Least Common Ancestor // Done 51 | Construct Binary Tree From Inorder And Preorder 52 | Flatten Binary Tree to Linked List // Done 53 | Preorder Traversal // Done 54 | Max Depth of Binary Tree // Done 55 | Binary Tree From Inorder And Postorder 56 | Sum Root to Leaf Numbers // Done 57 | Postorder Traversal 58 | Populate Next Right Pointers Tree 59 | Path Sum // Done 60 | Next Pointer Binary Tree 61 | Root to Leaf Paths With Sum 62 | 63 | Linked Lists : 64 | 65 | Swap List Nodes in pairs // Done 66 | Remove Duplicates from Sorted List II // Done 67 | Merge Two Sorted Lists // Done 68 | Remove Duplicates from Sorted list // Done 69 | Add Two Numbers as Lists 70 | Partition List 71 | Insertion Sort List 72 | List Cycle // Done 73 | Intersection of Linked Lists // Done 74 | Reverse Link List II 75 | Palindrome List 76 | K reverse linked list 77 | Clone a Linked list // Done 78 | 79 | Stacks And Queues : 80 | 81 | Simplify Directory Path 82 | Nearest Smaller Element // Done 83 | 84 | Backtracking : 85 | 86 | All Unique Permutations 87 | Permutations // Done 88 | Generate all Parentheses II 89 | Combination Sum II 90 | Sudoku // Done 91 | Gray Code 92 | Subsets II 93 | Subset 94 | 95 | Hashing : 96 | 97 | Anagrams // Done 98 | Fraction 99 | Copy List 100 | Largest Continuous Sequence Zero Sum // Done 101 | 102 | Dynamic Programming : 103 | 104 | Max Rectangle in Binary Matrix // Done 105 | Max Product Subarray // Done 106 | Regular Expression Match 107 | Edit Distance // Done 108 | Regular Expression II 109 | Coin Sum Infinite 110 | Longest Arithmetic Progression 111 | Length of Longest Subsequence 112 | 113 | 114 | Greedy Algorithm : 115 | 116 | Majority Element // Done 117 | Distribute Candy 118 | 119 | 120 | Graph Data Structure : 121 | 122 | Word Ladder II 123 | Word Ladder I 124 | Smallest sequence with given Primes 125 | 126 | 127 | Puzzles : 128 | 129 | ..... 130 | 131 | 132 | 133 | 134 | 135 | 136 | Todo Misc : 137 | 138 | Design Patterns -> Tushar Roy Videos 139 | Data Science 140 | 141 | OOPS 142 | 143 | Prepare : Tell me about your self, Why change the Job, Why Microsoft 144 | Ask questions : Make a List of questions to ask 145 | 146 | // Maximum occurence of a num 147 | 148 | 1) What all is expected from me being a part of Microsoft AI & R 149 | 2) What kind of problems do you solve daily. 150 | 151 | // Why microsoft, why do you want to apply : 152 | 153 | Microsoft is a dream company. It has been involved in several Software and AI innovations 154 | and I would like to contribute in it in any small/big ways. 155 | 156 | // Why change the jobs : 157 | 158 | I like to surround myself with bright people and learn and work with senior Leaders. 159 | Unfortunately I dont see that kind of an environment at Jio. It has been a great journey, 160 | I have recieved good projects and support from the management, but if given an opportunity, 161 | I would like to work with microsoft. 162 | 163 | Revise : 164 | Build Tree, Tree construction 165 | Left View 166 | Check The sum 167 | Fatten 168 | 169 | Linked List 170 | 171 | Add LL 172 | Flatten Linked List 173 | BinaryTree2DoubleLinkedList 174 | Clone -------------------------------------------------------------------------------- /misc/src/misc.cpp: -------------------------------------------------------------------------------- 1 | #include "misc.h" 2 | 3 | 4 | int dictionaryContains(string &word) 5 | { 6 | string dictionary[] = {"mobile","samsung","sam","sung", 7 | "man","mango", "icecream","and", 8 | "go","i","love","ice","cream"}; 9 | int n = sizeof(dictionary)/sizeof(dictionary[0]); 10 | for (int i = 0; i < n; i++) 11 | if (dictionary[i].compare(word) == 0) 12 | return true; 13 | return false; 14 | } 15 | 16 | // Prints all possible word breaks of given string 17 | void wordBreak(string str) 18 | { 19 | // last argument is prefix 20 | wordBreakUtil(str, str.size(), ""); 21 | } 22 | 23 | // result store the current prefix with spaces 24 | // between words 25 | void wordBreakUtil(string str, int n, string result) 26 | { 27 | //Process all prefixes one by one 28 | for (int i=1; i<=n; i++) 29 | { 30 | //extract substring from 0 to i in prefix 31 | string prefix = str.substr(0, i); 32 | 33 | // if dictionary conatins this prefix, then 34 | // we check for remaining string. Otherwise 35 | // we ignore this prefix (there is no else for 36 | // this if) and try next 37 | if (dictionaryContains(prefix)) 38 | { 39 | // if no more elements are there, print it 40 | if (i == n) 41 | { 42 | // add this element to previous prefix 43 | result += prefix; 44 | cout << result << endl; //print result 45 | return; 46 | } 47 | wordBreakUtil(str.substr(i, n-i), n-i, result + prefix + " "); 48 | } 49 | } //end for 50 | }//end function 51 | 52 | 53 | 54 | // Returns number of pairs in arr[0..n-1] with sum equal 55 | // to 'sum' 56 | int getPairsCount(int arr[], int n, int sum) 57 | { 58 | unordered_map m; 59 | 60 | // Store counts of all elements in map m 61 | for (int i=0; i s; 94 | 95 | int max_area = 0; // Initalize max area 96 | int tp; // To store top of stack 97 | int area_with_top; // To store area with top bar 98 | // as the smallest bar 99 | 100 | // Run through all bars of given histogram 101 | int i = 0; 102 | while (i < n) 103 | { 104 | // If this bar is higher than the bar on top 105 | // stack, push it to stack 106 | if (s.empty() || hist[s.top()] <= hist[i]) 107 | s.push(i++); 108 | 109 | // If this bar is lower than top of stack, 110 | // then calculate area of rectangle with stack 111 | // top as the smallest (or minimum height) bar. 112 | // 'i' is 'right index' for the top and element 113 | // before top in stack is 'left index' 114 | else 115 | { 116 | tp = s.top(); // store the top index 117 | s.pop(); // pop the top 118 | 119 | // Calculate the area with hist[tp] stack 120 | // as smallest bar 121 | area_with_top = hist[tp] * (s.empty() ? i : 122 | i - s.top() - 1); 123 | 124 | // update max area, if needed 125 | if (max_area < area_with_top) 126 | max_area = area_with_top; 127 | } 128 | } 129 | 130 | // Now pop the remaining bars from stack and calculate 131 | // area with every popped bar as the smallest bar 132 | while (s.empty() == false) 133 | { 134 | tp = s.top(); 135 | s.pop(); 136 | area_with_top = hist[tp] * (s.empty() ? i : 137 | i - s.top() - 1); 138 | 139 | if (max_area < area_with_top) 140 | max_area = area_with_top; 141 | } 142 | 143 | return max_area; 144 | } -------------------------------------------------------------------------------- /strings/src/strings.cpp: -------------------------------------------------------------------------------- 1 | #include "strings.h" 2 | 3 | void swap(char *a,char *b) 4 | { 5 | if( *a == *b ) 6 | return; 7 | *a^=*b; 8 | *b^=*a; 9 | *a^=*b; 10 | } 11 | 12 | void rev(string& s,int l,int r) 13 | { 14 | while(l s; 53 | char x; 54 | 55 | // Traversing the Expression 56 | for (int i=0; i 0; i--) 136 | if (number[i] > number[i-1]) 137 | break; 138 | 139 | // If no such digit is found, then all digits are in descending order 140 | // means there cannot be a greater number with same set of digits 141 | if (i==0) 142 | { 143 | cout << "Next number is not possible"; 144 | return; 145 | } 146 | 147 | // II) Find the smallest digit on right side of (i-1)'th digit that is 148 | // greater than number[i-1] 149 | int x = number[i-1], smallest = i; 150 | for (j = i+1; j < n; j++) 151 | if (number[j] > x && number[j] < number[smallest]) 152 | smallest = j; 153 | 154 | // III) Swap the above found smallest digit with number[i-1] 155 | swap(&number[smallest], &number[i-1]); 156 | 157 | // IV) Sort the digits after (i-1) in ascending order 158 | sort(number + i, number + n); 159 | 160 | cout << "Next number with same set of digits is " << number; 161 | 162 | return; 163 | } 164 | 165 | 166 | 167 | // Function to reverse a string 168 | void reverseStr(string& str) 169 | { 170 | int n = str.length(); 171 | 172 | // Swap character starting from two 173 | // corners 174 | for (int i = 0; i < n / 2; i++) 175 | swap(str[i], str[n - i - 1]); 176 | } -------------------------------------------------------------------------------- /segment_tree/src/seg_tree.cpp: -------------------------------------------------------------------------------- 1 | #include "seg_tree.h" 2 | 3 | // int getSum(node, l, r) 4 | // { 5 | // if the range of the node is within l and r 6 | // return value in the node 7 | // else if the range of the node is completely outside l and r 8 | // return 0 9 | // else 10 | // return getSum(node's left child, l, r) + 11 | // getSum(node's right child, l, r) 12 | // } 13 | 14 | 15 | // A utility function to get the middle index from corner indexes. 16 | int getMid(int s, int e) 17 | { 18 | return s + (e -s)/2; 19 | } 20 | 21 | /* A recursive function to get the sum of values in given range 22 | of the array. The following are parameters for this function. 23 | 24 | st --> Pointer to segment tree 25 | si --> Index of current node in the segment tree. Initially 26 | 0 is passed as root is always at index 0 27 | ss & se --> Starting and ending indexes of the segment represented 28 | by current node, i.e., st[si] 29 | qs & qe --> Starting and ending indexes of query range */ 30 | int getSumUtil(int *st, int ss, int se, int qs, int qe, int si) 31 | { 32 | // If segment of this node is a part of given range, then return 33 | // the sum of the segment 34 | if (qs <= ss && qe >= se) 35 | return st[si]; 36 | 37 | // If segment of this node is outside the given range 38 | if (se < qs || ss > qe) 39 | return 0; 40 | 41 | // If a part of this segment overlaps with the given range 42 | int mid = getMid(ss, se); 43 | return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + 44 | getSumUtil(st, mid+1, se, qs, qe, 2*si+2); 45 | } 46 | 47 | // Return sum of elements in range from index qs (quey start) 48 | // to qe (query end). It mainly uses getSumUtil() 49 | int getSum(int *st, int n, int qs, int qe) 50 | { 51 | // Check for erroneous input values 52 | if (qs < 0 || qe > n-1 || qs > qe) 53 | { 54 | printf("Invalid Input"); 55 | return -1; 56 | } 57 | 58 | return getSumUtil(st, 0, n-1, qs, qe, 0); 59 | } 60 | 61 | /* A recursive function to update the nodes which have the given 62 | index in their range. The following are parameters 63 | st, si, ss and se are same as getSumUtil() 64 | i --> index of the element to be updated. This index is 65 | in the input array. 66 | diff --> Value to be added to all nodes which have i in range */ 67 | void updateValueUtil(int *st, int ss, int se, int i, int diff, int si) 68 | { 69 | // Base Case: If the input index lies outside the range of 70 | // this segment 71 | if (i < ss || i > se) 72 | return; 73 | 74 | // If the input index is in range of this node, then update 75 | // the value of the node and its children 76 | st[si] = st[si] + diff; 77 | if (se != ss) 78 | { 79 | int mid = getMid(ss, se); 80 | updateValueUtil(st, ss, mid, i, diff, 2*si + 1); 81 | updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); 82 | } 83 | } 84 | 85 | 86 | // The function to update a value in input array and segment tree. 87 | // It uses updateValueUtil() to update the value in segment tree 88 | void updateValue(int arr[], int *st, int n, int i, int new_val) 89 | { 90 | // Check for erroneous input index 91 | if (i < 0 || i > n-1) 92 | { 93 | printf("Invalid Input"); 94 | return; 95 | } 96 | 97 | // Get the difference between new value and old value 98 | int diff = new_val - arr[i]; 99 | 100 | // Update the value in array 101 | arr[i] = new_val; 102 | 103 | // Update the values of nodes in segment tree 104 | updateValueUtil(st, 0, n-1, i, diff, 0); 105 | } 106 | 107 | // A recursive function that constructs Segment Tree for array[ss..se]. 108 | // si is index of current node in segment tree st 109 | int constructSTUtil(int arr[], int ss, int se, int *st, int si) 110 | { 111 | // If there is one element in array, store it in current node of 112 | // segment tree and return 113 | if (ss == se) 114 | { 115 | st[si] = arr[ss]; 116 | return arr[ss]; 117 | } 118 | 119 | // If there are more than one elements, then recur for left and 120 | // right subtrees and store the sum of values in this node 121 | int mid = getMid(ss, se); 122 | st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + 123 | constructSTUtil(arr, mid+1, se, st, si*2+2); 124 | return st[si]; 125 | } 126 | 127 | /* Function to construct segment tree from given array. This function 128 | allocates memory for segment tree and calls constructSTUtil() to 129 | fill the allocated memory */ 130 | int *constructST(int arr[], int n) 131 | { 132 | // Allocate memory for the segment tree 133 | 134 | //Height of segment tree 135 | int x = (int)(ceil(log2(n))); 136 | 137 | //Maximum size of segment tree 138 | int max_size = 2*(int)pow(2, x) - 1; 139 | 140 | // Allocate memory 141 | int *st = new int[max_size]; 142 | 143 | // Fill the allocated memory st 144 | constructSTUtil(arr, 0, n-1, st, 0); 145 | 146 | // Return the constructed segment tree 147 | return st; 148 | } -------------------------------------------------------------------------------- /stacks_queue/src/stacks_queue.cpp: -------------------------------------------------------------------------------- 1 | #include "stacks_queue.h" 2 | 3 | void printPrevSmaller(int arr[], int n) 4 | { 5 | // Create an empty stack 6 | stack S; 7 | 8 | // Traverse all array elements 9 | for (int i=0; i= arr[i]) 14 | S.pop(); 15 | 16 | // If all elements in S were greater than arr[i] 17 | if (S.empty()) 18 | cout << "_, "; 19 | else //Else print the nearest smaller element 20 | cout << S.top() << ", "; 21 | 22 | // Push this element 23 | S.push(arr[i]); 24 | } 25 | } 26 | 27 | 28 | void Stack::push(int x) 29 | { 30 | curr_size++; 31 | // Push x first in empty q2 32 | q2.push(x); 33 | // Push all the remaining 34 | // elements in q1 to q2. 35 | while (!q1.empty()) 36 | { 37 | q2.push(q1.front()); 38 | q1.pop(); 39 | } 40 | // swap the names of two queues 41 | queue q = q1; 42 | q1 = q2; 43 | q2 = q; 44 | } 45 | 46 | 47 | // A user defined stack that supports getMin() in 48 | // addition to push() and pop() 49 | struct MyStack 50 | { 51 | stack s; 52 | int minEle; 53 | 54 | // Prints minimum element of MyStack 55 | void getMin() 56 | { 57 | if (s.empty()) 58 | cout << "Stack is empty\n"; 59 | 60 | // variable minEle stores the minimum element 61 | // in the stack. 62 | else 63 | cout <<"Minimum Element in the stack is: " 64 | << minEle << "\n"; 65 | } 66 | 67 | // Prints top element of MyStack 68 | void peek() 69 | { 70 | if (s.empty()) 71 | { 72 | cout << "Stack is empty "; 73 | return; 74 | } 75 | 76 | int t = s.top(); // Top element. 77 | 78 | cout << "Top Most Element is: "; 79 | 80 | // If t < minEle means minEle stores 81 | // value of t. 82 | (t < minEle)? cout << minEle: cout << t; 83 | } 84 | 85 | // Remove the top element from MyStack 86 | void pop() 87 | { 88 | if (s.empty()) 89 | { 90 | cout << "Stack is empty\n"; 91 | return; 92 | } 93 | 94 | cout << "Top Most Element Removed: "; 95 | int t = s.top(); 96 | s.pop(); 97 | 98 | // Minimum will change as the minimum element 99 | // of the stack is being removed. 100 | if (t < minEle) 101 | { 102 | cout << minEle << "\n"; 103 | minEle = 2*minEle - t; 104 | } 105 | 106 | else 107 | cout << t << "\n"; 108 | } 109 | 110 | // Removes top element from MyStack 111 | void push(int x) 112 | { 113 | // Insert new number into the stack 114 | if (s.empty()) 115 | { 116 | minEle = x; 117 | s.push(x); 118 | cout << "Number Inserted: " << x << "\n"; 119 | return; 120 | } 121 | 122 | // If new number is less than minEle 123 | if (x < minEle) 124 | { 125 | s.push(2*x - minEle); 126 | minEle = x; 127 | } 128 | 129 | else 130 | s.push(x); 131 | 132 | cout << "Number Inserted: " << x << "\n"; 133 | } 134 | }; 135 | 136 | // A stack based efficient method to calculate 137 | // stock span values 138 | void calculateSpan(int price[], int n, int S[]) 139 | { 140 | // Create a stack and push index of first 141 | // element to it 142 | stack st; 143 | st.push(0); 144 | 145 | // Span value of first element is always 1 146 | S[0] = 1; 147 | 148 | // Calculate span values for rest of the elements 149 | for (int i = 1; i < n; i++) 150 | { 151 | // Pop elements from stack while stack is not 152 | // empty and top of stack is smaller than 153 | // price[i] 154 | while (!st.empty() && price[st.top()] <= price[i]) 155 | st.pop(); 156 | 157 | // If stack becomes empty, then price[i] is 158 | // greater than all elements on left of it, 159 | // i.e., price[0], price[1],..price[i-1]. Else 160 | // price[i] is greater than elements after 161 | // top of stack 162 | S[i] = (st.empty())? (i + 1) : (i - st.top()); 163 | 164 | // Push this element to stack 165 | st.push(i); 166 | } 167 | } 168 | 169 | 170 | 171 | // Function to find precedence of 172 | // operators. 173 | int precedence(char op){ 174 | if(op == '+'||op == '-') 175 | return 1; 176 | if(op == '*'||op == '/') 177 | return 2; 178 | return 0; 179 | } 180 | 181 | // Function to perform arithmetic operations. 182 | int applyOp(int a, int b, char op){ 183 | switch(op){ 184 | case '+': return a + b; 185 | case '-': return a - b; 186 | case '*': return a * b; 187 | case '/': return a / b; 188 | } 189 | } 190 | 191 | // Function that returns value of 192 | // expression after evaluation. 193 | int evaluate(string tokens){ 194 | int i; 195 | 196 | // stack to store integer values. 197 | stack values; 198 | 199 | // stack to store operators. 200 | stack ops; 201 | 202 | for(i = 0; i < tokens.length(); i++){ 203 | 204 | // Current token is a whitespace, 205 | // skip it. 206 | if(tokens[i] == ' ') 207 | continue; 208 | 209 | // Current token is an opening 210 | // brace, push it to 'ops' 211 | else if(tokens[i] == '('){ 212 | ops.push(tokens[i]); 213 | } 214 | 215 | // Current token is a number, push 216 | // it to stack for numbers. 217 | else if(isdigit(tokens[i])){ 218 | int val = 0; 219 | 220 | // There may be more than one 221 | // digits in number. 222 | while(i < tokens.length() && 223 | isdigit(tokens[i])) 224 | { 225 | val = (val*10) + (tokens[i]-'0'); 226 | i++; 227 | } 228 | 229 | values.push(val); 230 | } 231 | 232 | // Closing brace encountered, solve 233 | // entire brace. 234 | else if(tokens[i] == ')') 235 | { 236 | while(!ops.empty() && ops.top() != '(') 237 | { 238 | int val2 = values.top(); 239 | values.pop(); 240 | 241 | int val1 = values.top(); 242 | values.pop(); 243 | 244 | char op = ops.top(); 245 | ops.pop(); 246 | 247 | values.push(applyOp(val1, val2, op)); 248 | } 249 | 250 | // pop opening brace. 251 | ops.pop(); 252 | } 253 | 254 | // Current token is an operator. 255 | else 256 | { 257 | // While top of 'ops' has same or greater 258 | // precedence to current token, which 259 | // is an operator. Apply operator on top 260 | // of 'ops' to top two elements in values stack. 261 | while(!ops.empty() && precedence(ops.top()) 262 | >= precedence(tokens[i])){ 263 | int val2 = values.top(); 264 | values.pop(); 265 | 266 | int val1 = values.top(); 267 | values.pop(); 268 | 269 | char op = ops.top(); 270 | ops.pop(); 271 | 272 | values.push(applyOp(val1, val2, op)); 273 | } 274 | 275 | // Push current token to 'ops'. 276 | ops.push(tokens[i]); 277 | } 278 | } 279 | 280 | // Entire expression has been parsed at this 281 | // point, apply remaining ops to remaining 282 | // values. 283 | while(!ops.empty()){ 284 | int val2 = values.top(); 285 | values.pop(); 286 | 287 | int val1 = values.top(); 288 | values.pop(); 289 | 290 | char op = ops.top(); 291 | ops.pop(); 292 | 293 | values.push(applyOp(val1, val2, op)); 294 | } 295 | 296 | // Top of 'values' contains result, return it. 297 | return values.top(); 298 | } -------------------------------------------------------------------------------- /search_sort/src/search_sort.cpp: -------------------------------------------------------------------------------- 1 | #include "search_sort.h" 2 | 3 | 4 | int binarySearch(int arr[], int l, int r, int x) 5 | { 6 | if (r >= l) 7 | { 8 | int mid = l + (r - l)/2; 9 | 10 | // If the element is present at the middle 11 | // itself 12 | if (arr[mid] == x) 13 | return mid; 14 | 15 | // If element is smaller than mid, then 16 | // it can only be present in left subarray 17 | if (arr[mid] > x) 18 | return binarySearch(arr, l, mid-1, x); 19 | 20 | // Else the element can only be present 21 | // in right subarray 22 | return binarySearch(arr, mid+1, r, x); 23 | } 24 | 25 | // We reach here when element is not 26 | // present in array 27 | return -1; 28 | } 29 | 30 | void merge(int arr[], int l, int m, int r) 31 | { 32 | int i, j, k; 33 | int n1 = m - l + 1; 34 | int n2 = r - m; 35 | 36 | /* create temp arrays */ 37 | int L[n1], R[n2]; 38 | 39 | /* Copy data to temp arrays L[] and R[] */ 40 | for (i = 0; i < n1; i++) 41 | L[i] = arr[l + i]; 42 | for (j = 0; j < n2; j++) 43 | R[j] = arr[m + 1+ j]; 44 | 45 | /* Merge the temp arrays back into arr[l..r]*/ 46 | i = 0; // Initial index of first subarray 47 | j = 0; // Initial index of second subarray 48 | k = l; // Initial index of merged subarray 49 | while (i < n1 && j < n2) 50 | { 51 | if (L[i] <= R[j]) 52 | { 53 | arr[k] = L[i]; 54 | i++; 55 | } 56 | else 57 | { 58 | arr[k] = R[j]; 59 | j++; 60 | } 61 | k++; 62 | } 63 | 64 | /* Copy the remaining elements of L[], if there 65 | are any */ 66 | while (i < n1) 67 | { 68 | arr[k] = L[i]; 69 | i++; 70 | k++; 71 | } 72 | 73 | /* Copy the remaining elements of R[], if there 74 | are any */ 75 | while (j < n2) 76 | { 77 | arr[k] = R[j]; 78 | j++; 79 | k++; 80 | } 81 | } 82 | 83 | /* l is for left index and r is right index of the 84 | sub-array of arr to be sorted */ 85 | void mergeSort(int arr[], int l, int r) 86 | { 87 | if (l < r) 88 | { 89 | // Same as (l+r)/2, but avoids overflow for 90 | // large l and h 91 | int m = l+(r-l)/2; 92 | 93 | // Sort first and second halves 94 | mergeSort(arr, l, m); 95 | mergeSort(arr, m+1, r); 96 | 97 | merge(arr, l, m, r); 98 | } 99 | } 100 | 101 | // A utility function to swap two elements 102 | void swap(int* a, int* b) 103 | { 104 | int t = *a; 105 | *a = *b; 106 | *b = t; 107 | } 108 | 109 | /* This function takes last element as pivot, places 110 | the pivot element at its correct position in sorted 111 | array, and places all smaller (smaller than pivot) 112 | to left of pivot and all greater elements to right 113 | of pivot */ 114 | int partition (int arr[], int low, int high) 115 | { 116 | int pivot = arr[high]; // pivot 117 | int i = (low - 1); // Index of smaller element 118 | 119 | for (int j = low; j <= high- 1; j++) 120 | { 121 | // If current element is smaller than or 122 | // equal to pivot 123 | if (arr[j] <= pivot) 124 | { 125 | i++; // increment index of smaller element 126 | swap(&arr[i], &arr[j]); 127 | } 128 | } 129 | swap(&arr[i + 1], &arr[high]); 130 | return (i + 1); 131 | } 132 | 133 | int randomPartition(int arr[], int l, int r) 134 | { 135 | int n = r-l+1; 136 | int pivot = rand() % n; 137 | swap(&arr[l + pivot], &arr[r]); 138 | return partition(arr, l, r); 139 | } 140 | 141 | /* The main function that implements QuickSort 142 | arr[] --> Array to be sorted, 143 | low --> Starting index, 144 | high --> Ending index */ 145 | void quickSort(int arr[], int low, int high) 146 | { 147 | if (low < high) 148 | { 149 | /* pi is partitioning index, arr[p] is now 150 | at right place */ 151 | int pi = partition(arr, low, high); 152 | 153 | // Separately sort elements before 154 | // partition and after partition 155 | quickSort(arr, low, pi - 1); 156 | quickSort(arr, pi + 1, high); 157 | } 158 | } 159 | 160 | int kthSmallest(int arr[], int l, int r, int k) 161 | { 162 | // If k is smaller than number of elements in array 163 | if (k > 0 && k <= r - l + 1) 164 | { 165 | // Partition the array around last element and get 166 | // position of pivot element in sorted array 167 | int pos = partition(arr, l, r); 168 | 169 | // If position is same as k 170 | if (pos-l == k-1) 171 | return arr[pos]; 172 | if (pos-l > k-1) // If position is more, recur for left subarray 173 | return kthSmallest(arr, l, pos-1, k); 174 | 175 | // Else recur for right subarray 176 | return kthSmallest(arr, pos+1, r, k-pos+l-1); 177 | } 178 | 179 | // If k is more than number of elements in array 180 | return INT_MAX; 181 | } 182 | 183 | 184 | // Search in a rotated Array 185 | 186 | /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 187 | it returns 3 (index of 6) */ 188 | int findPivot(int arr[], int low, int high) 189 | { 190 | // base cases 191 | if (high < low) return -1; 192 | if (high == low) return low; 193 | 194 | int mid = (low + high)/2; /*low + (high - low)/2;*/ 195 | if (mid < high && arr[mid] > arr[mid + 1]) 196 | return mid; 197 | 198 | if (mid > low && arr[mid] < arr[mid - 1]) 199 | return (mid-1); 200 | 201 | if (arr[low] >= arr[mid]) 202 | return findPivot(arr, low, mid-1); 203 | 204 | return findPivot(arr, mid + 1, high); 205 | } 206 | 207 | /* Searches an element key in a pivoted 208 | sorted array arr[] of size n */ 209 | int pivotedBinarySearch(int arr[], int n, int key) 210 | { 211 | int pivot = findPivot(arr, 0, n-1); 212 | 213 | // If we didn't find a pivot, 214 | // then array is not rotated at all 215 | if (pivot == -1) 216 | return binarySearch(arr, 0, n-1, key); 217 | 218 | // If we found a pivot, then first compare with pivot 219 | // and then search in two subarrays around pivot 220 | if (arr[pivot] == key) 221 | return pivot; 222 | 223 | if (arr[0] <= key) 224 | return binarySearch(arr, 0, pivot-1, key); 225 | 226 | return binarySearch(arr, pivot+1, n-1, key); 227 | } 228 | 229 | 230 | // Function to find median of two sorted arrays 231 | double findMedianSortedArrays(int *a, int n, int *b, int m) 232 | { 233 | 234 | int min_index = 0, max_index = n, i, j, median; 235 | 236 | while (min_index <= max_index) 237 | { 238 | i = (min_index + max_index) / 2; 239 | j = ((n + m + 1) / 2) - i; 240 | 241 | // if i = n, it means that Elements from a[] in 242 | // the second half is an empty set. and if j = 0, 243 | // it means that Elements from b[] in the first 244 | // half is an empty set. so it is necessary to 245 | // check that, because we compare elements from 246 | // these two groups. 247 | // Searching on right 248 | if (i < n && j > 0 && b[j - 1] > a[i]) 249 | min_index = i + 1; 250 | 251 | // if i = 0, it means that Elements from a[] in 252 | // the first half is an empty set and if j = m, 253 | // it means that Elements from b[] in the second 254 | // half is an empty set. so it is necessary to 255 | // check that, because we compare elements 256 | // from these two groups. 257 | // searching on left 258 | else if (i > 0 && j < m && b[j] < a[i - 1]) 259 | max_index = i - 1; 260 | 261 | // we have found the desired halves. 262 | else 263 | { 264 | // this condition happens when we don't have any 265 | // elements in the first half from a[] so we 266 | // returning the last element in b[] from 267 | // the first half. 268 | if (i == 0) 269 | median = b[j - 1]; 270 | 271 | // and this condition happens when we don't 272 | // have any elements in the first half from 273 | // b[] so we returning the last element in 274 | // a[] from the first half. 275 | else if (j == 0) 276 | median = a[i - 1]; 277 | else 278 | median = maximum(a[i - 1], b[j - 1]); 279 | break; 280 | } 281 | } 282 | 283 | // calculating the median. 284 | // If number of elements is odd there is 285 | // one middle element. 286 | if ((n + m) % 2 == 1) 287 | return (double)median; 288 | 289 | // Elements from a[] in the second half is an empty set. 290 | if (i == n) 291 | return (median+b[j]) / 2.0; 292 | 293 | // Elements from b[] in the second half is an empty set. 294 | if (j == m) 295 | return (median + a[i]) / 2.0; 296 | 297 | return (median + minimum(a[i], b[j])) / 2.0; 298 | } 299 | 300 | 301 | // Sort the input array, the array is assumed to 302 | // have values in {0, 1, 2} 303 | void sort012(int a[], int arr_size) 304 | { 305 | int lo = 0; 306 | int hi = arr_size - 1; 307 | int mid = 0; 308 | 309 | while (mid <= hi) 310 | { 311 | switch (a[mid]) 312 | { 313 | case 0: 314 | swap(&a[lo++], &a[mid++]); 315 | break; 316 | case 1: 317 | mid++; 318 | break; 319 | case 2: 320 | swap(&a[mid], &a[hi--]); 321 | break; 322 | } 323 | } 324 | } 325 | 326 | /* This function returns 327 | median of ar1[] and ar2[]. 328 | Assumptions in this function: 329 | Both ar1[] and ar2[] 330 | are sorted arrays 331 | Both have n elements */ 332 | int getMedian(int ar1[], 333 | int ar2[], int n) 334 | { 335 | int i = 0; /* Current index of i/p array ar1[] */ 336 | int j = 0; /* Current index of i/p array ar2[] */ 337 | int count; 338 | int m1 = -1, m2 = -1; 339 | 340 | /* Since there are 2n elements, 341 | median will be average of elements 342 | at index n-1 and n in the array 343 | obtained after merging ar1 and ar2 */ 344 | for (count = 0; count <= n; count++) 345 | { 346 | /* Below is to handle case where 347 | all elements of ar1[] are 348 | smaller than smallest(or first) 349 | element of ar2[]*/ 350 | if (i == n) 351 | { 352 | m1 = m2; 353 | m2 = ar2[0]; 354 | break; 355 | } 356 | 357 | /*Below is to handle case where 358 | all elements of ar2[] are 359 | smaller than smallest(or first) 360 | element of ar1[]*/ 361 | else if (j == n) 362 | { 363 | m1 = m2; 364 | m2 = ar1[0]; 365 | break; 366 | } 367 | 368 | if (ar1[i] < ar2[j]) 369 | { 370 | /* Store the prev median */ 371 | m1 = m2; 372 | m2 = ar1[i]; 373 | i++; 374 | } 375 | else 376 | { 377 | /* Store the prev median */ 378 | m1 = m2; 379 | m2 = ar2[j]; 380 | j++; 381 | } 382 | } 383 | 384 | return (m1 + m2)/2; 385 | } -------------------------------------------------------------------------------- /arrays/src/array.cpp: -------------------------------------------------------------------------------- 1 | #include "array.h" 2 | 3 | // Sort stuff 4 | 5 | void swap(int *a, int *b) 6 | { 7 | int temp = *a; 8 | *a = *b; 9 | *b = temp; 10 | } 11 | 12 | // Standard partition process of QuickSort(). It considers the last 13 | // element as pivot and moves all smaller element to left of it 14 | // and greater elements to right 15 | int partition(int arr[], int l, int r) 16 | { 17 | int x = arr[r], i = l; 18 | for (int j = l; j <= r - 1; j++) 19 | { 20 | if (arr[j] <= x) 21 | { 22 | swap(&arr[i], &arr[j]); 23 | i++; 24 | } 25 | } 26 | swap(&arr[i], &arr[r]); 27 | return i; 28 | } 29 | 30 | void quickSort(int A[], int si, int ei) 31 | { 32 | int pi; /* Partitioning index */ 33 | if(si < ei) 34 | { 35 | pi = partition(A, si, ei); 36 | quickSort(A, si, pi - 1); 37 | quickSort(A, pi + 1, ei); 38 | } 39 | } 40 | 41 | // Largest Sum Contiguous Subarray, Kadane Algo 42 | 43 | int maxSubArraySum(int a[], int size) 44 | { 45 | int max_so_far = INT_MIN, max_ending_here = 0; 46 | 47 | for (int i = 0; i < size; i++) 48 | { 49 | max_ending_here = max_ending_here + a[i]; 50 | if (max_so_far < max_ending_here) 51 | max_so_far = max_ending_here; 52 | 53 | if (max_ending_here < 0) 54 | max_ending_here = 0; 55 | } 56 | 57 | return max_so_far; 58 | } 59 | 60 | // Find subarray with given sum | Set 1 (Nonnegative Numbers) 61 | 62 | int subArraySum(int arr[], int n, int sum) 63 | { 64 | /* Initialize curr_sum as value of first element 65 | and starting point as 0 */ 66 | int curr_sum = arr[0], start = 0, i; 67 | 68 | /* Add elements one by one to curr_sum and if the curr_sum exceeds the 69 | sum, then remove starting element */ 70 | for (i = 1; i <= n; i++) 71 | { 72 | // If curr_sum exceeds the sum, then remove the starting elements 73 | while (curr_sum > sum && start < i-1) 74 | { 75 | curr_sum = curr_sum - arr[start]; 76 | start++; 77 | } 78 | 79 | // If curr_sum becomes equal to sum, then return true 80 | if (curr_sum == sum) 81 | { 82 | printf ("Sum found between indexes %d and %d", start, i-1); 83 | return 1; 84 | } 85 | 86 | // Add this element to curr_sum 87 | if (i < n) 88 | curr_sum = curr_sum + arr[i]; 89 | } 90 | 91 | // If we reach here, then no subarray 92 | printf("No subarray found"); 93 | return 0; 94 | } 95 | 96 | // This function returns k'th smallest element in arr[l..r] using 97 | // QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT 98 | int kthSmallest(int arr[], int l, int r, int k) 99 | { 100 | // If k is smaller than number of elements in array 101 | if (k > 0 && k <= r - l + 1) 102 | { 103 | // Partition the array around last element and get 104 | // position of pivot element in sorted array 105 | int pos = partition(arr, l, r); 106 | 107 | // If position is same as k 108 | if (pos-l == k-1) 109 | return arr[pos]; 110 | if (pos-l > k-1) // If position is more, recur for left subarray 111 | return kthSmallest(arr, l, pos-1, k); 112 | 113 | // Else recur for right subarray 114 | return kthSmallest(arr, pos+1, r, k-pos+l-1); 115 | } 116 | 117 | // If k is more than number of elements in array 118 | return INT_MAX; 119 | } 120 | 121 | // An Inplace function to rotate a N x N matrix 122 | // by 90 degrees in anti-clockwise direction 123 | void rotateMatrix(int mat[][N]) 124 | { 125 | // Consider all squares one by one 126 | for (int x = 0; x < N / 2; x++) 127 | { 128 | // Consider elements in group of 4 in 129 | // current square 130 | for (int y = x; y < N-x-1; y++) 131 | { 132 | // store current cell in temp variable 133 | int temp = mat[x][y]; 134 | 135 | // move values from right to top 136 | mat[x][y] = mat[y][N-1-x]; 137 | 138 | // move values from bottom to right 139 | mat[y][N-1-x] = mat[N-1-x][N-1-y]; 140 | 141 | // move values from left to bottom 142 | mat[N-1-x][N-1-y] = mat[N-1-y][x]; 143 | 144 | // assign temp to left 145 | mat[N-1-y][x] = temp; 146 | } 147 | } 148 | } 149 | 150 | 151 | /* Function to find the candidate for Majority */ 152 | int findCandidate(int a[], int size) 153 | { 154 | int maj_index = 0, count = 1; 155 | for (int i = 1; i < size; i++) 156 | { 157 | if (a[maj_index] == a[i]) 158 | count++; 159 | else 160 | count--; 161 | if (count == 0) 162 | { 163 | maj_index = i; 164 | count = 1; 165 | } 166 | } 167 | return a[maj_index]; 168 | } 169 | 170 | bool isMajority(int a[], int size, int cand) 171 | { 172 | int count = 0; 173 | 174 | for (int i = 0; i < size; i++) 175 | if (a[i] == cand) 176 | count++; 177 | 178 | if (count > size/2) 179 | return 1; 180 | else 181 | return 0; 182 | } 183 | 184 | // Maximum Area Histogram 185 | 186 | // The main function to find the maximum rectangular 187 | // area under given histogram with n bars 188 | int getMaxArea(int hist[], int n) 189 | { 190 | // Create an empty stack. The stack holds indexes 191 | // of hist[] array. The bars stored in stack are 192 | // always in increasing order of their heights. 193 | stack s; 194 | 195 | int max_area = 0; // Initalize max area 196 | int tp; // To store top of stack 197 | int area_with_top; // To store area with top bar 198 | // as the smallest bar 199 | 200 | // Run through all bars of given histogram 201 | int i = 0; 202 | while (i < n) 203 | { 204 | // If this bar is higher than the bar on top 205 | // stack, push it to stack 206 | if (s.empty() || hist[s.top()] <= hist[i]) 207 | s.push(i++); 208 | 209 | // If this bar is lower than top of stack, 210 | // then calculate area of rectangle with stack 211 | // top as the smallest (or minimum height) bar. 212 | // 'i' is 'right index' for the top and element 213 | // before top in stack is 'left index' 214 | else 215 | { 216 | tp = s.top(); // store the top index 217 | s.pop(); // pop the top 218 | 219 | // Calculate the area with hist[tp] stack 220 | // as smallest bar 221 | area_with_top = hist[tp] * (s.empty() ? i : 222 | i - s.top() - 1); 223 | 224 | // update max area, if needed 225 | if (max_area < area_with_top) 226 | max_area = area_with_top; 227 | } 228 | } 229 | 230 | // Now pop the remaining bars from stack and calculate 231 | // area with every popped bar as the smallest bar 232 | while (s.empty() == false) 233 | { 234 | tp = s.top(); 235 | s.pop(); 236 | area_with_top = hist[tp] * (s.empty() ? i : 237 | i - s.top() - 1); 238 | 239 | if (max_area < area_with_top) 240 | max_area = area_with_top; 241 | } 242 | 243 | return max_area; 244 | } 245 | 246 | 247 | // Sudoku Back Tracking 248 | 249 | 250 | /* Takes a partially filled-in grid and attempts to assign values to 251 | all unassigned locations in such a way to meet the requirements 252 | for Sudoku solution (non-duplication across rows, columns, and boxes) */ 253 | bool SolveSudoku(int grid[N][N]) 254 | { 255 | int row, col; 256 | 257 | // If there is no unassigned location, we are done 258 | if (!FindUnassignedLocation(grid, row, col)) 259 | return true; // success! 260 | 261 | // consider digits 1 to 9 262 | for (int num = 1; num <= 9; num++) 263 | { 264 | // if looks promising 265 | if (isSafe(grid, row, col, num)) 266 | { 267 | // make tentative assignment 268 | grid[row][col] = num; 269 | 270 | // return, if success, yay! 271 | if (SolveSudoku(grid)) 272 | return true; 273 | 274 | // failure, unmake & try again 275 | grid[row][col] = UNASSIGNED; 276 | } 277 | } 278 | return false; // this triggers backtracking 279 | } 280 | 281 | /* Searches the grid to find an entry that is still unassigned. If 282 | found, the reference parameters row, col will be set the location 283 | that is unassigned, and true is returned. If no unassigned entries 284 | remain, false is returned. */ 285 | bool FindUnassignedLocation(int grid[N][N], int &row, int &col) 286 | { 287 | for (row = 0; row < N; row++) 288 | for (col = 0; col < N; col++) 289 | if (grid[row][col] == UNASSIGNED) 290 | return true; 291 | return false; 292 | } 293 | 294 | /* Returns a boolean which indicates whether an assigned entry 295 | in the specified row matches the given number. */ 296 | bool UsedInRow(int grid[N][N], int row, int num) 297 | { 298 | for (int col = 0; col < N; col++) 299 | if (grid[row][col] == num) 300 | return true; 301 | return false; 302 | } 303 | 304 | /* Returns a boolean which indicates whether an assigned entry 305 | in the specified column matches the given number. */ 306 | bool UsedInCol(int grid[N][N], int col, int num) 307 | { 308 | for (int row = 0; row < N; row++) 309 | if (grid[row][col] == num) 310 | return true; 311 | return false; 312 | } 313 | 314 | /* Returns a boolean which indicates whether an assigned entry 315 | within the specified 3x3 box matches the given number. */ 316 | bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num) 317 | { 318 | for (int row = 0; row < 3; row++) 319 | for (int col = 0; col < 3; col++) 320 | if (grid[row+boxStartRow][col+boxStartCol] == num) 321 | return true; 322 | return false; 323 | } 324 | 325 | /* Returns a boolean which indicates whether it will be legal to assign 326 | num to the given row,col location. */ 327 | bool isSafe(int grid[N][N], int row, int col, int num) 328 | { 329 | /* Check if 'num' is not already placed in current row, 330 | current column and current 3x3 box */ 331 | return !UsedInRow(grid, row, num) && 332 | !UsedInCol(grid, col, num) && 333 | !UsedInBox(grid, row - row%3 , col - col%3, num); 334 | } 335 | 336 | // Find the length of largest subarray with 0 sum 337 | 338 | // Returns Length of the required subarray 339 | int maxLen(int arr[], int n) 340 | { 341 | // Map to store the previous sums 342 | unordered_map presum; 343 | 344 | int sum = 0; // Initialize the sum of elements 345 | int max_len = 0; // Initialize result 346 | 347 | // Traverse through the given array 348 | for(int i=0; i arr[j] && lis[i] < lis[j] + 1) 16 | lis[i] = lis[j] + 1; 17 | 18 | /* Pick maximum of all LIS values */ 19 | for (i = 0; i < n; i++ ) 20 | if (max < lis[i]) 21 | max = lis[i]; 22 | 23 | /* Free memory to avoid memory leak */ 24 | free(lis); 25 | 26 | return max; 27 | } 28 | 29 | // LCS 30 | 31 | /* 32 | 33 | Seq 1 : ABCDGH 34 | 35 | Seq 2 : AEDFHR 36 | 37 | A B C D G H 38 | 39 | 0 0 0 0 0 0 0 40 | 41 | A 0 1 1 1 1 1 1 42 | 43 | E 0 1 1 1 1 1 1 44 | 45 | D 0 1 1 1 2 2 2 46 | 47 | F 0 1 1 1 2 2 2 48 | 49 | H 0 1 1 1 2 2 3 50 | 51 | R 0 1 1 1 2 2 3 52 | 53 | if (L1[i] == L2[j]) 54 | 55 | LCS[i][j] = LCS[i-1][j-1] + 1 56 | 57 | else 58 | 59 | LCS[i][j] = max(LCS[i-1][j],LCS[i][j-1]) 60 | 61 | */ 62 | 63 | int lcs( char *X, char *Y, int m, int n ) 64 | { 65 | int L[m+1][n+1]; 66 | int i, j; 67 | 68 | /* Following steps build L[m+1][n+1] in bottom up fashion. Note 69 | that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ 70 | for (i=0; i<=m; i++) 71 | { 72 | for (j=0; j<=n; j++) 73 | { 74 | if (i == 0 || j == 0) 75 | L[i][j] = 0; 76 | 77 | else if (X[i-1] == Y[j-1]) 78 | L[i][j] = L[i-1][j-1] + 1; 79 | 80 | else 81 | L[i][j] = max(L[i-1][j], L[i][j-1]); 82 | } 83 | } 84 | 85 | /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ 86 | return L[m][n]; 87 | } 88 | 89 | 90 | // Largest Sum Contiguous Subarray, Kadane Algo 91 | 92 | int maxSubArraySum(int a[], int size) 93 | { 94 | int max_so_far = INT_MIN, max_ending_here = 0; 95 | 96 | for (int i = 0; i < size; i++) 97 | { 98 | max_ending_here = max_ending_here + a[i]; 99 | 100 | if (max_so_far < max_ending_here) 101 | max_so_far = max_ending_here; 102 | 103 | if (max_ending_here < 0) 104 | max_ending_here = 0; 105 | } 106 | 107 | return max_so_far; 108 | } 109 | 110 | // Edit distance 111 | 112 | /* 113 | 114 | Seq 1 : sunday 115 | 116 | Seq 2 : saturday 117 | 118 | 119 | s u n d a y 120 | 121 | 0 1 2 3 4 5 6 122 | 123 | s 1 0 1 2 3 4 5 124 | 125 | a 2 1 1 2 3 3 4 126 | 127 | t 3 2 2 2 3 4 5 128 | 129 | u 4 3 2 3 3 4 5 130 | 131 | r 5 4 3 3 4 4 5 132 | 133 | d 6 5 4 4 3 4 5 134 | 135 | a 7 6 5 5 4 3 4 136 | 137 | y 8 7 6 6 5 4 3 138 | 139 | 140 | if (str1[i-1] == str2[j-1]) 141 | 142 | dp[i][j] = dp[i-1][j-1]; 143 | 144 | else 145 | dp[i][j] = 1 + min(dp[i][j-1], // Insert 146 | dp[i-1][j], // Remove 147 | dp[i-1][j-1]); // Replace 148 | 149 | */ 150 | 151 | int editDistDP(string str1, string str2, int m, int n) 152 | { 153 | // Create a table to store results of subproblems 154 | int dp[m+1][n+1]; 155 | 156 | // Fill d[][] in bottom up manner 157 | for (int i=0; i<=m; i++) 158 | { 159 | for (int j=0; j<=n; j++) 160 | { 161 | // If first string is empty, only option is to 162 | // isnert all characters of second string 163 | if (i==0) 164 | dp[i][j] = j; // Min. operations = j 165 | 166 | // If second string is empty, only option is to 167 | // remove all characters of second string 168 | else if (j==0) 169 | dp[i][j] = i; // Min. operations = i 170 | 171 | // If last characters are same, ignore last char 172 | // and recur for remaining string 173 | else if (str1[i-1] == str2[j-1]) 174 | dp[i][j] = dp[i-1][j-1]; 175 | 176 | // If the last character is different, consider all 177 | // possibilities and find the minimum 178 | else 179 | dp[i][j] = 1 + min(dp[i][j-1], // Insert 180 | dp[i-1][j], // Remove 181 | dp[i-1][j-1]); // Replace 182 | } 183 | } 184 | 185 | return dp[m][n]; 186 | } 187 | 188 | // Min cost path 189 | 190 | /* 191 | 192 | Optimal Substructure 193 | 194 | minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n] 195 | 196 | Mat : 197 | 198 | 1 2 3 199 | 200 | 4 8 2 201 | 202 | 1 5 3 203 | 204 | 205 | Cost Mat 206 | 207 | 208 | 1 3 6 209 | 210 | 5 9 5 211 | 212 | 6 10 8 213 | 214 | */ 215 | 216 | int minCost(int cost[R][C], int m, int n) 217 | { 218 | int i, j; 219 | 220 | // Instead of following line, we can use int tc[m+1][n+1] or 221 | // dynamically allocate memoery to save space. The following line is 222 | // used to keep te program simple and make it working on all compilers. 223 | int tc[R][C]; 224 | 225 | tc[0][0] = cost[0][0]; 226 | 227 | /* Initialize first column of total cost(tc) array */ 228 | for (i = 1; i <= m; i++) 229 | tc[i][0] = tc[i-1][0] + cost[i][0]; 230 | 231 | /* Initialize first row of tc array */ 232 | for (j = 1; j <= n; j++) 233 | tc[0][j] = tc[0][j-1] + cost[0][j]; 234 | 235 | /* Construct rest of the tc array */ 236 | for (i = 1; i <= m; i++) 237 | for (j = 1; j <= n; j++) 238 | tc[i][j] = min(tc[i-1][j-1], 239 | tc[i-1][j], 240 | tc[i][j-1]) + cost[i][j]; 241 | 242 | return tc[m][n]; 243 | } 244 | 245 | // Coin change path 246 | 247 | /* 248 | 249 | 250 | 251 | */ 252 | 253 | // C program for coin change problem. 254 | 255 | int count_coin( int S[], int m, int n ) 256 | { 257 | int i, j, x, y; 258 | 259 | // We need n+1 rows as the table is constructed 260 | // in bottom up manner using the base case 0 261 | // value case (n = 0) 262 | int table[n+1][m]; 263 | 264 | // Fill the enteries for 0 value case (n = 0) 265 | for (i=0; i= 0)? table[i - S[j]][j]: 0; 276 | 277 | // Count of solutions excluding S[j] 278 | y = (j >= 1)? table[i][j-1]: 0; 279 | 280 | // total count 281 | table[i][j] = x + y; 282 | } 283 | } 284 | return table[n][m-1]; 285 | } 286 | 287 | 288 | // 0-1 Knapsnack problem 289 | 290 | /* 291 | 292 | Total wt = 7 293 | 294 | wt [] = [1,3,4,5] 295 | 296 | val = [1,4,5,7] 297 | 298 | Mat : 299 | 300 | val wt 0 1 2 3 4 5 6 7 -> wt 301 | 302 | 1 1 0 1 1 1 1 1 1 1 -> val 303 | 304 | 4 3 0 1 1 4 5 5 5 5 -> val 305 | 306 | 5 4 0 1 1 4 5 6 6 9 -> val 307 | 308 | 7 5 0 1 1 4 5 7 8 9 -> val 309 | 310 | 311 | if (j < wt[i] ) 312 | 313 | T[i][j] = T[i-1][j] 314 | 315 | else 316 | 317 | T[i][j] = max( val[i] + T[i-1][j-wt[i]] , T[i-1][j] ) 318 | 319 | */ 320 | 321 | // Returns the maximum value that can be put in a knapsack of capacity W 322 | int knapSack(int W, int wt[], int val[], int n) 323 | { 324 | int i, w; 325 | int K[n+1][W+1]; 326 | 327 | // Build table K[][] in bottom up manner 328 | for (i = 0; i <= n; i++) 329 | { 330 | for (w = 0; w <= W; w++) 331 | { 332 | if (i==0 || w==0) 333 | K[i][w] = 0; 334 | else if (wt[i-1] <= w) 335 | K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); 336 | else 337 | K[i][w] = K[i-1][w]; 338 | } 339 | } 340 | 341 | return K[n][W]; 342 | } 343 | 344 | 345 | /* 346 | 347 | Input : agbdba 348 | 349 | Output : bdb 350 | 351 | a g b d b a 352 | 353 | a 1 1 1 1 1 1 354 | 355 | 356 | g 1 1 357 | 358 | 359 | b 1 1 360 | 361 | 362 | d 1 1 363 | 364 | 365 | b 1 1 366 | 367 | 368 | a 1 369 | 370 | 371 | */ 372 | 373 | 374 | 375 | /// Maximum size square sub-matrix with all 1s 376 | 377 | 378 | /* 379 | 380 | Matrix : Mat[M][M] 381 | 382 | 383 | 0 0 1 1 1 384 | 385 | 1 0 1 1 1 386 | 387 | 0 1 1 1 1 388 | 389 | 1 0 1 1 1 390 | 391 | 392 | DP Mat : Mat[M+1][N+1] 393 | 394 | 0 1 2 3 4 5 395 | 396 | 0 0 0 0 0 0 0 397 | 398 | 1 0 0 0 1 1 1 399 | 400 | 2 0 1 0 1 2 2 401 | 402 | 3 0 0 1 1 2 3 403 | 404 | 4 0 1 0 1 2 3 405 | 406 | */ 407 | 408 | void printMaxSubSquare(bool M[R][C]) 409 | { 410 | int i,j; 411 | int S[R][C]; 412 | int max_of_s, max_i, max_j; 413 | 414 | /* Set first column of S[][]*/ 415 | for(i = 0; i < R; i++) 416 | S[i][0] = M[i][0]; 417 | 418 | /* Set first row of S[][]*/ 419 | for(j = 0; j < C; j++) 420 | S[0][j] = M[0][j]; 421 | 422 | /* Construct other entries of S[][]*/ 423 | for(i = 1; i < R; i++) 424 | { 425 | for(j = 1; j < C; j++) 426 | { 427 | if(M[i][j] == 1) 428 | S[i][j] = min(S[i][j-1], S[i-1][j], 429 | S[i-1][j-1]) + 1; 430 | else 431 | S[i][j] = 0; 432 | } 433 | } 434 | 435 | /* Find the maximum entry, and indexes of maximum entry 436 | in S[][] */ 437 | max_of_s = S[0][0]; max_i = 0; max_j = 0; 438 | for(i = 0; i < R; i++) 439 | { 440 | for(j = 0; j < C; j++) 441 | { 442 | if(max_of_s < S[i][j]) 443 | { 444 | max_of_s = S[i][j]; 445 | max_i = i; 446 | max_j = j; 447 | } 448 | } 449 | } 450 | 451 | printf("Maximum size sub-matrix is: \n"); 452 | for(i = max_i; i > max_i - max_of_s; i--) 453 | { 454 | for(j = max_j; j > max_j - max_of_s; j--) 455 | { 456 | printf("%d ", M[i][j]); 457 | } 458 | printf("\n"); 459 | } 460 | 461 | } 462 | 463 | 464 | // Max Size Rectangle : 465 | 466 | // Returns area of the largest rectangle with all 1s in A[][] 467 | int maxRectangle(int A[][C]) 468 | { 469 | // Calculate area for first row and initialize it as 470 | // result 471 | int result = maxHist(A[0]); 472 | 473 | // iterate over row to find maximum rectangular area 474 | // considering each row as histogram 475 | for (int i = 1; i < R; i++) 476 | { 477 | 478 | for (int j = 0; j < C; j++) 479 | 480 | // if A[i][j] is 1 then add A[i -1][j] 481 | if (A[i][j]) A[i][j] += A[i - 1][j]; 482 | 483 | 484 | // Update result if area with current row (as last row) 485 | // of rectangle) is more 486 | result = max(result, maxHist(A[i])); 487 | } 488 | 489 | return result; 490 | } 491 | 492 | /* Returns the product of max product subarray. 493 | Assumes that the given array always has a subarray 494 | with product more than 1 */ 495 | int maxSubarrayProduct(int arr[], int n) 496 | { 497 | // max positive product ending at the current position 498 | int max_ending_here = 1; 499 | 500 | // min negative product ending at the current position 501 | int min_ending_here = 1; 502 | 503 | // Initialize overall max product 504 | int max_so_far = 1; 505 | 506 | /* Traverse through the array. Following values are 507 | maintained after the i'th iteration: 508 | max_ending_here is always 1 or some positive product 509 | ending with arr[i] 510 | min_ending_here is always 1 or some negative product 511 | ending with arr[i] */ 512 | for (int i = 0; i < n; i++) 513 | { 514 | /* If this element is positive, update max_ending_here. 515 | Update min_ending_here only if min_ending_here is 516 | negative */ 517 | if (arr[i] > 0) 518 | { 519 | max_ending_here = max_ending_here*arr[i]; 520 | min_ending_here = min (min_ending_here * arr[i], 1); 521 | } 522 | 523 | /* If this element is 0, then the maximum product 524 | cannot end here, make both max_ending_here and 525 | min_ending_here 0 526 | Assumption: Output is alway greater than or equal 527 | to 1. */ 528 | else if (arr[i] == 0) 529 | { 530 | max_ending_here = 1; 531 | min_ending_here = 1; 532 | } 533 | 534 | /* If element is negative. This is tricky 535 | max_ending_here can either be 1 or positive. 536 | min_ending_here can either be 1 or negative. 537 | next min_ending_here will always be prev. 538 | max_ending_here * arr[i] next max_ending_here 539 | will be 1 if prev min_ending_here is 1, otherwise 540 | next max_ending_here will be prev min_ending_here * 541 | arr[i] */ 542 | else 543 | { 544 | int temp = max_ending_here; 545 | max_ending_here = max (min_ending_here * arr[i], 1); 546 | min_ending_here = temp * arr[i]; 547 | } 548 | 549 | // update max_so_far, if needed 550 | if (max_so_far < max_ending_here) 551 | max_so_far = max_ending_here; 552 | } 553 | 554 | return max_so_far; 555 | } -------------------------------------------------------------------------------- /linked_list/src/linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include "linked_list.h" 2 | 3 | void printList(struct Node *n) 4 | { 5 | while (n != NULL) 6 | { 7 | printf(" %d ", n->data); 8 | n = n->next; 9 | } 10 | } 11 | 12 | /* Given a reference (pointer to pointer) to the head of a list and 13 | an int, inserts a new node on the front of the list. */ 14 | void push(struct Node** head_ref, int new_data) 15 | { 16 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 17 | 18 | new_node->data = new_data; 19 | 20 | new_node->next = (*head_ref); 21 | 22 | (*head_ref) = new_node; 23 | } 24 | 25 | void insertAfter(struct Node* prev_node, int new_data) 26 | { 27 | /*1. check if the given prev_node is NULL */ 28 | if (prev_node == NULL) 29 | { 30 | printf("the given previous node cannot be NULL"); 31 | return; 32 | } 33 | 34 | struct Node* new_node =(struct Node*) malloc(sizeof(struct Node)); 35 | 36 | new_node->data = new_data; 37 | 38 | new_node->next = prev_node->next; 39 | 40 | prev_node->next = new_node; 41 | } 42 | 43 | void append(struct Node** head_ref, int new_data) 44 | { 45 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 46 | 47 | struct Node *last = *head_ref; /* used in step 5*/ 48 | 49 | new_node->data = new_data; 50 | 51 | /* 3. This new node is going to be the last node, so make next of 52 | it as NULL*/ 53 | new_node->next = NULL; 54 | 55 | /* 4. If the Linked List is empty, then make the new node as head */ 56 | if (*head_ref == NULL) 57 | { 58 | *head_ref = new_node; 59 | return; 60 | } 61 | 62 | /* 5. Else traverse till the last node */ 63 | while (last->next != NULL) 64 | last = last->next; 65 | 66 | /* 6. Change the next of last node */ 67 | last->next = new_node; 68 | return; 69 | } 70 | 71 | 72 | /* Given a reference (pointer to pointer) to the head of a list 73 | and a position, deletes the node at the given position */ 74 | void deleteNode(struct Node **head_ref, int position) 75 | { 76 | // If linked list is empty 77 | if (*head_ref == NULL) 78 | return; 79 | 80 | // Store head node 81 | struct Node* temp = *head_ref; 82 | 83 | // If head needs to be removed 84 | if (position == 0) 85 | { 86 | *head_ref = temp->next; // Change head 87 | free(temp); // free old head 88 | return; 89 | } 90 | 91 | // Find previous node of the node to be deleted 92 | for (int i=0; temp!=NULL && inext; 94 | 95 | // If position is more than number of ndoes 96 | if (temp == NULL || temp->next == NULL) 97 | return; 98 | 99 | // Node temp->next is the node to be deleted 100 | // Store pointer to the next of node to be deleted 101 | struct Node *next = temp->next->next; 102 | 103 | // Unlink the node from linked list 104 | free(temp->next); // Free memory 105 | 106 | temp->next = next; // Unlink the deleted node from list 107 | } 108 | 109 | 110 | // Deletes every k-th node and returns head 111 | // of modified list. 112 | Node *deleteKthNode(struct Node *head, int k) 113 | { 114 | // If linked list is empty 115 | if (head == NULL) 116 | return NULL; 117 | 118 | if (k == 1) 119 | { 120 | freeList(head); 121 | return NULL; 122 | } 123 | 124 | // Initialize ptr and prev before starting 125 | // traversal. 126 | struct Node *ptr = head, *prev = NULL; 127 | 128 | // Traverse list and delete every k-th node 129 | int count = 0; 130 | while (ptr != NULL) 131 | { 132 | // increment Node count 133 | count++; 134 | 135 | // check if count is equal to k 136 | // if yes, then delete current Node 137 | if (k == count) 138 | { 139 | // put the next of current Node in 140 | // the next of previous Node 141 | delete(prev->next); 142 | prev->next = ptr->next; 143 | 144 | // set count = 0 to reach further 145 | // k-th Node 146 | count = 0; 147 | } 148 | 149 | // update prev if count is not 0 150 | if (count != 0) 151 | prev = ptr; 152 | 153 | ptr = prev->next; 154 | } 155 | 156 | return head; 157 | } 158 | 159 | 160 | /* Function to delete the entire linked list */ 161 | void deleteList(struct Node** head_ref) 162 | { 163 | /* deref head_ref to get the real head */ 164 | struct Node* current = *head_ref; 165 | struct Node* next; 166 | 167 | while (current != NULL) 168 | { 169 | next = current->next; 170 | free(current); 171 | current = next; 172 | } 173 | 174 | /* deref head_ref to affect the real head back 175 | in the caller. */ 176 | *head_ref = NULL; 177 | } 178 | 179 | /* Counts no. of nodes in linked list */ 180 | int getCount(struct Node* head) 181 | { 182 | int count = 0; // Initialize count 183 | struct Node* current = head; // Initialize current 184 | while (current != NULL) 185 | { 186 | count++; 187 | current = current->next; 188 | } 189 | return count; 190 | } 191 | 192 | // Takes head pointer of 193 | // the linked list and index 194 | // as arguments and return 195 | // data at index 196 | int GetNth(struct Node* head, 197 | int index) 198 | { 199 | 200 | struct Node* current = head; 201 | 202 | // the index of the 203 | // node we're currently 204 | // looking at 205 | int count = 0; 206 | while (current != NULL) 207 | { 208 | if (count == index) 209 | return(current->data); 210 | count++; 211 | current = current->next; 212 | } 213 | 214 | /* if we get to this line, 215 | the caller was asking 216 | for a non-existent element 217 | so we assert fail */ 218 | assert(0); 219 | } 220 | 221 | /* Function to get the nth node from the last of a linked list*/ 222 | void printNthFromLast(struct Node *head, int n) 223 | { 224 | struct Node *main_ptr = head; 225 | struct Node *ref_ptr = head; 226 | 227 | int count = 0; 228 | if(head != NULL) 229 | { 230 | while( count < n ) 231 | { 232 | if(ref_ptr == NULL) 233 | { 234 | printf("%d is greater than the no. of " 235 | "nodes in list", n); 236 | return; 237 | } 238 | ref_ptr = ref_ptr->next; 239 | count++; 240 | } /* End of while*/ 241 | 242 | while(ref_ptr != NULL) 243 | { 244 | main_ptr = main_ptr->next; 245 | ref_ptr = ref_ptr->next; 246 | } 247 | printf("Node no. %d from last is %d ", 248 | n, main_ptr->data); 249 | } 250 | } 251 | 252 | /* Function to reverse the linked list */ 253 | void recursiveReverse(struct Node** head_ref) 254 | { 255 | struct Node* first; 256 | struct Node* rest; 257 | 258 | /* empty list */ 259 | if (*head_ref == NULL) 260 | return; 261 | 262 | /* suppose first = {1, 2, 3}, rest = {2, 3} */ 263 | first = *head_ref; 264 | rest = first->next; 265 | 266 | /* List has only one node */ 267 | if (rest == NULL) 268 | return; 269 | 270 | /* reverse the rest list and put the first element at the end */ 271 | recursiveReverse(&rest); 272 | first->next->next = first; 273 | 274 | /* tricky step -- see the diagram */ 275 | first->next = NULL; 276 | 277 | /* fix the head pointer */ 278 | *head_ref = rest; 279 | } 280 | 281 | 282 | void reverse(struct Node** head_ref) 283 | { 284 | // Initialize current, previous and 285 | // next pointers 286 | Node *current = head; 287 | Node *prev = NULL, *next = NULL; 288 | 289 | 290 | while (current != NULL) 291 | { 292 | // Store next 293 | next = current->next; 294 | 295 | // Reverse current node's pointer 296 | current->next = prev; 297 | 298 | // Move pointers one position ahead. 299 | prev = current; 300 | current = next; 301 | } 302 | head = prev; 303 | } 304 | 305 | /* Function to get the middle of the linked list*/ 306 | void printMiddle(struct Node *head) 307 | { 308 | struct Node *slow_ptr = head; 309 | struct Node *fast_ptr = head; 310 | 311 | if (head!=NULL) 312 | { 313 | while (fast_ptr != NULL && fast_ptr->next != NULL) 314 | { 315 | fast_ptr = fast_ptr->next->next; 316 | slow_ptr = slow_ptr->next; 317 | } 318 | printf("The middle element is [%d]\n\n", slow_ptr->data); 319 | } 320 | } 321 | 322 | 323 | // This function rotates a linked list counter-clockwise and 324 | // updates the head. The function assumes that k is smaller 325 | // than size of linked list. It doesn't modify the list if 326 | // k is greater than or equal to size 327 | 328 | void rotate(struct Node **head_ref, int k) 329 | { 330 | if (k == 0) 331 | return; 332 | 333 | struct Node* current = *head_ref; 334 | 335 | int count = 1; 336 | while (count < k && current != NULL) 337 | { 338 | current = current->next; 339 | count++; 340 | } 341 | 342 | if (current == NULL) 343 | return; 344 | 345 | struct Node *kthNode = current; 346 | 347 | while (current->next != NULL) 348 | current = current->next; 349 | 350 | current->next = *head_ref; 351 | 352 | *head_ref = kthNode->next; 353 | 354 | kthNode->next = NULL; 355 | } 356 | 357 | struct Node* SortedMerge(struct Node* a, struct Node* b) 358 | { 359 | struct Node* result = NULL; 360 | 361 | /* Base cases */ 362 | if (a == NULL) 363 | return(b); 364 | else if (b==NULL) 365 | return(a); 366 | 367 | /* Pick either a or b, and recur */ 368 | if (a->data <= b->data) 369 | { 370 | result = a; 371 | result->next = SortedMerge(a->next, b); 372 | } 373 | else 374 | { 375 | result = b; 376 | result->next = SortedMerge(a, b->next); 377 | } 378 | return(result); 379 | } 380 | 381 | struct Node* SortedMergeReverse(Node *a, Node *b) 382 | { 383 | // If both lists are empty 384 | if (a==NULL && b==NULL) return NULL; 385 | 386 | // Initialize head of resultant list 387 | Node *res = NULL; 388 | 389 | // Traverse both lists while both of then 390 | // have nodes. 391 | while (a != NULL && b != NULL) 392 | { 393 | // If a's current value is smaller or equal to 394 | // b's current value. 395 | if (a->key <= b->key) 396 | { 397 | // Store next of current Node in first list 398 | Node *temp = a->next; 399 | 400 | // Add 'a' at the front of resultant list 401 | a->next = res; 402 | res = a; 403 | 404 | // Move ahead in first list 405 | a = temp; 406 | } 407 | 408 | // If a's value is greater. Below steps are similar 409 | // to above (Only 'a' is replaced with 'b') 410 | else 411 | { 412 | Node *temp = b->next; 413 | b->next = res; 414 | res = b; 415 | b = temp; 416 | } 417 | } 418 | 419 | // If second list reached end, but first list has 420 | // nodes. Add remaining nodes of first list at the 421 | // front of result list 422 | while (a != NULL) 423 | { 424 | Node *temp = a->next; 425 | a->next = res; 426 | res = a; 427 | a = temp; 428 | } 429 | 430 | // If first list reached end, but second list has 431 | // node. Add remaining nodes of first list at the 432 | // front of result list 433 | while (b != NULL) 434 | { 435 | Node *temp = b->next; 436 | b->next = res; 437 | res = b; 438 | b = temp; 439 | } 440 | 441 | return res; 442 | } 443 | 444 | int getIntesectionNode(struct Node* head1, struct Node* head2) 445 | { 446 | int c1 = getCount(head1); 447 | int c2 = getCount(head2); 448 | int d; 449 | 450 | if(c1 > c2) 451 | { 452 | d = c1 - c2; 453 | return _getIntesectionNode(d, head1, head2); 454 | } 455 | else 456 | { 457 | d = c2 - c1; 458 | return _getIntesectionNode(d, head2, head1); 459 | } 460 | } 461 | 462 | /* function to get the intersection point of two linked 463 | lists head1 and head2 where head1 has d more nodes than 464 | head2 */ 465 | int _getIntesectionNode(int d, struct Node* head1, struct Node* head2) 466 | { 467 | int i; 468 | struct Node* current1 = head1; 469 | struct Node* current2 = head2; 470 | 471 | for(i = 0; i < d; i++) 472 | { 473 | if(current1 == NULL) 474 | { return -1; } 475 | current1 = current1->next; 476 | } 477 | 478 | while(current1 != NULL && current2 != NULL) 479 | { 480 | if(current1 == current2) 481 | return current1->data; 482 | current1= current1->next; 483 | current2= current2->next; 484 | } 485 | 486 | return -1; 487 | } 488 | 489 | // Add two linked lists : most significant node is first node 490 | 491 | struct node* addSameSize(Node* head1, Node* head2, int* carry) 492 | { 493 | // Since the function assumes linked lists are of same size, 494 | // check any of the two head pointers 495 | if (head1 == NULL) 496 | return NULL; 497 | 498 | int sum; 499 | 500 | // Allocate memory for sum node of current two nodes 501 | Node* result = (Node *)malloc(sizeof(Node)); 502 | 503 | // Recursively add remaining nodes and get the carry 504 | result->next = addSameSize(head1->next, head2->next, carry); 505 | 506 | // add digits of current nodes and propagated carry 507 | sum = head1->data + head2->data + *carry; 508 | *carry = sum / 10; 509 | sum = sum % 10; 510 | 511 | // Assigne the sum to current node of resultant list 512 | result->data = sum; 513 | 514 | return result; 515 | } 516 | 517 | // This function is called after the smaller list is added to the bigger 518 | // lists's sublist of same size. Once the right sublist is added, the carry 519 | // must be added toe left side of larger list to get the final result. 520 | void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result) 521 | { 522 | int sum; 523 | 524 | // If diff. number of nodes are not traversed, add carry 525 | if (head1 != cur) 526 | { 527 | addCarryToRemaining(head1->next, cur, carry, result); 528 | 529 | sum = head1->data + *carry; 530 | *carry = sum/10; 531 | sum %= 10; 532 | 533 | // add this node to the front of the result 534 | push(result, sum); 535 | } 536 | } 537 | 538 | // The main function that adds two linked lists represented by head1 and head2. 539 | // The sum of two lists is stored in a list referred by result 540 | void addList(Node* head1, Node* head2, Node** result) 541 | { 542 | Node *cur; 543 | 544 | // first list is empty 545 | if (head1 == NULL) 546 | { 547 | *result = head2; 548 | return; 549 | } 550 | 551 | // second list is empty 552 | else if (head2 == NULL) 553 | { 554 | *result = head1; 555 | return; 556 | } 557 | 558 | int size1 = getSize(head1); 559 | int size2 = getSize(head2) ; 560 | 561 | int carry = 0; 562 | 563 | // Add same size lists 564 | if (size1 == size2) 565 | *result = addSameSize(head1, head2, &carry); 566 | 567 | else 568 | { 569 | int diff = abs(size1 - size2); 570 | 571 | // First list should always be larger than second list. 572 | // If not, swap pointers 573 | if (size1 < size2) 574 | swapPointer(&head1, &head2); 575 | 576 | // move diff. number of nodes in first list 577 | for (cur = head1; diff--; cur = cur->next); 578 | 579 | // get addition of same size lists 580 | *result = addSameSize(cur, head2, &carry); 581 | 582 | // get addition of remaining first list and carry 583 | addCarryToRemaining(head1, cur, &carry, result); 584 | } 585 | 586 | // if some carry is still there, add a new node to the fron of 587 | // the result list. e.g. 999 and 87 588 | if (carry) 589 | push(result, carry); 590 | } 591 | 592 | /* Adds contents of two linked lists and return the head node of resultant list */ 593 | // least significant digit is first node 594 | struct Node* addTwoLists (struct Node* first, struct Node* second) 595 | { 596 | struct Node* res = NULL; // res is head node of the resultant list 597 | struct Node *temp, *prev = NULL; 598 | int carry = 0, sum; 599 | 600 | while (first != NULL || second != NULL) //while both lists exist 601 | { 602 | // Calculate value of next digit in resultant list. 603 | // The next digit is sum of following things 604 | // (i) Carry 605 | // (ii) Next digit of first list (if there is a next digit) 606 | // (ii) Next digit of second list (if there is a next digit) 607 | sum = carry + (first? first->data: 0) + (second? second->data: 0); 608 | 609 | // update carry for next calulation 610 | carry = (sum >= 10)? 1 : 0; 611 | 612 | // update sum if it is greater than 10 613 | sum = sum % 10; 614 | 615 | // Create a new node with sum as data 616 | temp = newNode(sum); 617 | 618 | // if this is the first node then set it as head of the resultant list 619 | if(res == NULL) 620 | res = temp; 621 | else // If this is not the first node then connect it to the rest. 622 | prev->next = temp; 623 | 624 | // Set prev for next insertion 625 | prev = temp; 626 | 627 | // Move first and second pointers to next nodes 628 | if (first) first = first->next; 629 | if (second) second = second->next; 630 | } 631 | 632 | if (carry > 0) 633 | temp->next = newNode(carry); 634 | 635 | // return head of the resultant list 636 | return res; 637 | } 638 | 639 | /* Flatten Linked List 640 | 641 | Let us create the following linked list 642 | 643 | 5 -> 10 -> 19 -> 28 644 | | | | | 645 | V V V V 646 | 7 20 22 35 647 | | | | 648 | V V V 649 | 8 50 40 650 | | | 651 | V V 652 | 30 45 653 | 654 | Flat : 5->7->8->10->19->20->22->28->30->35->40->45->50. 655 | 656 | Linked list node for flat : 657 | 658 | // A Linked List Node 659 | typedef struct Node 660 | { 661 | int data; 662 | struct Node *right; 663 | struct Node *down; 664 | } Node; 665 | 666 | 667 | */ 668 | 669 | // The main function that flattens a given linked list 670 | Node* flatten (Node* root) 671 | { 672 | // Base cases 673 | if (root == NULL || root->right == NULL) 674 | return root; 675 | 676 | // Merge this list with the list on right side 677 | return merge( root, flatten(root->right) ); 678 | } 679 | 680 | // A utsility function to merge two sorted linked lists 681 | Node* merge( Node* a, Node* b ) 682 | { 683 | // If first list is empty, the second list is result 684 | if (a == NULL) 685 | return b; 686 | 687 | // If second list is empty, the second list is result 688 | if (b == NULL) 689 | return a; 690 | 691 | // Compare the data members of head nodes of both lists 692 | // and put the smaller one in result 693 | Node* result; 694 | if (a->data < b->data) 695 | { 696 | result = a; 697 | result->down = merge( a->down, b ); 698 | } 699 | else 700 | { 701 | result = b; 702 | result->down = merge( a, b->down ); 703 | } 704 | 705 | return result; 706 | } 707 | 708 | 709 | bool detectLoop(struct Node *h) 710 | { 711 | unordered_set s; 712 | while (h != NULL) 713 | { 714 | // If this node is already present 715 | // in hashmap it means there is a cycle 716 | // (Because you we encountering the 717 | // node for the second time). 718 | if (s.find(h) != s.end()) 719 | return true; 720 | 721 | // If we are seeing the node for 722 | // the first time, insert it in hash 723 | s.insert(h); 724 | 725 | h = h->next; 726 | } 727 | 728 | return false; 729 | } 730 | 731 | int detectloop_floyd(struct Node *list) 732 | { 733 | struct Node *slow_p = list, *fast_p = list; 734 | 735 | while (slow_p && fast_p && fast_p->next ) 736 | { 737 | slow_p = slow_p->next; 738 | fast_p = fast_p->next->next; 739 | if (slow_p == fast_p) 740 | { 741 | printf("Found Loop"); 742 | return 1; 743 | } 744 | } 745 | return 0; 746 | } 747 | 748 | 749 | struct Node *reverse (struct Node *head, int k) 750 | { 751 | struct Node* current = head; 752 | struct Node* next = NULL; 753 | struct Node* prev = NULL; 754 | int count = 0; 755 | 756 | /*reverse first k nodes of the linked list */ 757 | while (current != NULL && count < k) 758 | { 759 | next = current->next; 760 | current->next = prev; 761 | prev = current; 762 | current = next; 763 | count++; 764 | } 765 | 766 | /* next is now a pointer to (k+1)th node 767 | Recursively call for the list starting from current. 768 | And make rest of the list as next of first node */ 769 | if (next != NULL) 770 | head->next = reverse(next, k); 771 | 772 | /* prev is new head of the input list */ 773 | return prev; 774 | } 775 | 776 | void BinaryTree2DoubleLinkedList(node *root, node **head) 777 | { 778 | // Base case 779 | if (root == NULL) return; 780 | 781 | // Initialize previously visited node as NULL. This is 782 | // static so that the same value is accessible in all recursive 783 | // calls 784 | static node* prev = NULL; 785 | 786 | // Recursively convert left subtree 787 | BinaryTree2DoubleLinkedList(root->left, head); 788 | 789 | // Now convert this node 790 | if (prev == NULL) 791 | *head = root; 792 | else 793 | { 794 | root->left = prev; 795 | prev->right = root; 796 | } 797 | prev = root; 798 | 799 | // Finally convert right subtree 800 | BinaryTree2DoubleLinkedList(root->right, head); 801 | } 802 | 803 | /* Function to pairwise swap elements of a linked list */ 804 | void pairWiseSwap(struct Node *head) 805 | { 806 | struct Node *temp = head; 807 | 808 | /* Traverse further only if there are at-least two nodes left */ 809 | while (temp != NULL && temp->next != NULL) 810 | { 811 | /* Swap data of node with its next node's data */ 812 | swap(&temp->data, &temp->next->data); 813 | 814 | /* Move temp by 2 for the next pair */ 815 | temp = temp->next->next; 816 | } 817 | } 818 | 819 | /* Function to pairwise swap elements of a linked list */ 820 | void pairWiseSwap_inplace(struct Node **head) 821 | { 822 | // If linked list is empty or there is only one node in list 823 | if (*head == NULL || (*head)->next == NULL) 824 | return; 825 | 826 | // Initialize previous and current pointers 827 | struct Node *prev = *head; 828 | struct Node *curr = (*head)->next; 829 | 830 | *head = curr; // Change head before proceeeding 831 | 832 | // Traverse the list 833 | while (true) 834 | { 835 | struct Node *next = curr->next; 836 | curr->next = prev; // Change next of current as previous node 837 | 838 | // If next NULL or next is the last node 839 | if (next == NULL || next->next == NULL) 840 | { 841 | prev->next = next; 842 | break; 843 | } 844 | 845 | // Change next of previous to next next 846 | prev->next = next->next; 847 | 848 | // Update previous and curr 849 | prev = next; 850 | curr = prev->next; 851 | } 852 | 853 | } 854 | 855 | 856 | /* The function removes duplicates from a sorted list */ 857 | void removeDuplicates(struct Node* head) 858 | { 859 | /* Pointer to traverse the linked list */ 860 | struct Node* current = head; 861 | 862 | /* Pointer to store the next pointer of a node to be deleted*/ 863 | struct Node* next_next; 864 | 865 | /* do nothing if the list is empty */ 866 | if (current == NULL) 867 | return; 868 | 869 | /* Traverse the list till last node */ 870 | while (current->next != NULL) 871 | { 872 | /* Compare current node with next node */ 873 | if (current->data == current->next->data) 874 | { 875 | /* The sequence of steps is important*/ 876 | next_next = current->next->next; 877 | free(current->next); 878 | current->next = next_next; 879 | } 880 | else /* This is tricky: only advance if no deletion */ 881 | { 882 | current = current->next; 883 | } 884 | } 885 | } 886 | 887 | 888 | /* This function detects and removes loop in the list 889 | If loop was there in the list then it returns 1, 890 | otherwise returns 0 */ 891 | int detectAndRemoveLoop(struct Node *list) 892 | { 893 | struct Node *slow_p = list, *fast_p = list; 894 | 895 | while (slow_p && fast_p && fast_p->next) 896 | { 897 | slow_p = slow_p->next; 898 | fast_p = fast_p->next->next; 899 | 900 | /* If slow_p and fast_p meet at some point then there 901 | is a loop */ 902 | if (slow_p == fast_p) 903 | { 904 | removeLoop(slow_p, list); 905 | 906 | /* Return 1 to indicate that loop is found */ 907 | return 1; 908 | } 909 | } 910 | 911 | /* Return 0 to indeciate that ther is no loop*/ 912 | return 0; 913 | } 914 | 915 | /* Function to remove loop. 916 | loop_node --> Pointer to one of the loop nodes 917 | head --> Pointer to the start node of the linked list */ 918 | void removeLoop(struct Node *loop_node, struct Node *head) 919 | { 920 | struct Node *ptr1; 921 | struct Node *ptr2; 922 | 923 | /* Set a pointer to the beging of the Linked List and 924 | move it one by one to find the first node which is 925 | part of the Linked List */ 926 | ptr1 = head; 927 | while (1) 928 | { 929 | /* Now start a pointer from loop_node and check if it ever 930 | reaches ptr2 */ 931 | ptr2 = loop_node; 932 | while (ptr2->next != loop_node && ptr2->next != ptr1) 933 | ptr2 = ptr2->next; 934 | 935 | /* If ptr2 reahced ptr1 then there is a loop. So break the 936 | loop */ 937 | if (ptr2->next == ptr1) 938 | break; 939 | 940 | /* If ptr2 did't reach ptr1 then try the next node after ptr1 */ 941 | ptr1 = ptr1->next; 942 | } 943 | 944 | /* After the end of loop ptr2 is the last node of the loop. So 945 | make next of ptr2 as NULL */ 946 | ptr2->next = NULL; 947 | } 948 | 949 | // Returns count of nodes present in loop. 950 | 951 | int countNodes(struct Node *n) 952 | { 953 | int res = 1; 954 | struct Node *temp = n; 955 | while (temp->next != n) 956 | { 957 | res++; 958 | temp = temp->next; 959 | } 960 | return res; 961 | } 962 | 963 | int countNodesinLoop(struct Node *list) 964 | { 965 | struct Node *slow_p = list, *fast_p = list; 966 | 967 | while (slow_p && fast_p && fast_p->next) 968 | { 969 | slow_p = slow_p->next; 970 | fast_p = fast_p->next->next; 971 | 972 | /* If slow_p and fast_p meet at some point 973 | then there is a loop */ 974 | if (slow_p == fast_p) 975 | return countNodes(slow_p); 976 | } 977 | 978 | /* Return 0 to indeciate that ther is no loop*/ 979 | return 0; 980 | } 981 | 982 | // This function clones a given linked list 983 | // in O(1) space 984 | Node* clone(Node *start) 985 | { 986 | Node* curr = start, *temp; 987 | 988 | // insert additional node after 989 | // every node of original list 990 | while (curr) 991 | { 992 | temp = curr->next; 993 | 994 | // Inserting node 995 | curr->next = new Node(curr->data); 996 | curr->next->next = temp; 997 | curr = temp; 998 | } 999 | 1000 | curr = start; 1001 | 1002 | // adjust the random pointers of the 1003 | // newly added nodes 1004 | while (curr) 1005 | { 1006 | if(curr->next) 1007 | curr->next->random = curr->random ? curr->random->next : curr->random; 1008 | 1009 | // move to the next newly added node by 1010 | // skipping an original node 1011 | curr = curr->next?curr->next->next:curr->next; 1012 | } 1013 | 1014 | Node* original = start, *copy = start->next; 1015 | 1016 | // save the start of copied linked list 1017 | temp = copy; 1018 | 1019 | // now separate the original list and copied list 1020 | while (original && copy) 1021 | { 1022 | original->next = 1023 | original->next? original->next->next : original->next; 1024 | 1025 | copy->next = copy->next?copy->next->next:copy->next; 1026 | original = original->next; 1027 | copy = copy->next; 1028 | } 1029 | 1030 | return temp; 1031 | } -------------------------------------------------------------------------------- /binary_tree/src/binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include "binary_tree.h" 2 | 3 | Node* newNode(int data) 4 | { 5 | struct Node* newnode = new Node; 6 | newnode->left = NULL; 7 | newnode->right = NULL; 8 | newnode->key = data; 9 | return newnode; 10 | } 11 | 12 | // All Traversals, Recursive 13 | 14 | void printPostorder(struct Node* node) 15 | { 16 | if (node == NULL) 17 | return; 18 | 19 | // first recur on left subtree 20 | printPostorder(node->left); 21 | 22 | // then recur on right subtree 23 | printPostorder(node->right); 24 | 25 | // now deal with the node 26 | cout << node->data << " "; 27 | } 28 | 29 | /* Given a binary tree, print its nodes in inorder*/ 30 | void printInorder(struct Node* node) 31 | { 32 | if (node == NULL) 33 | return; 34 | 35 | /* first recur on left child */ 36 | printInorder(node->left); 37 | 38 | /* then print the data of node */ 39 | cout << node->data << " "; 40 | 41 | /* now recur on right child */ 42 | printInorder(node->right); 43 | } 44 | 45 | /* Given a binary tree, print its nodes in preorder*/ 46 | void printPreorder(struct Node* node) 47 | { 48 | if (node == NULL) 49 | return; 50 | 51 | /* first print data of node */ 52 | cout << node->data << " "; 53 | 54 | /* then recur on left sutree */ 55 | printPreorder(node->left); 56 | 57 | /* now recur on right subtree */ 58 | printPreorder(node->right); 59 | } 60 | 61 | // Inorder traversal without recurrsion 62 | 63 | void inOrder(struct Node *root) 64 | { 65 | stack s; 66 | Node *curr = root; 67 | 68 | while(curr != NULL || s.empty() == false) 69 | { 70 | while(curr != NULL) 71 | { 72 | s.push(curr); 73 | curr = curr->left; 74 | } 75 | 76 | curr = s.top(); 77 | s.pop(); 78 | 79 | cout << curr->key << " "; 80 | 81 | curr = curr->right ; 82 | 83 | } 84 | 85 | } 86 | 87 | // An iterative process to print preorder traversal of Binary tree 88 | void iterativePreorder(node *root) 89 | { 90 | // Base Case 91 | if (root == NULL) 92 | return; 93 | 94 | // Create an empty stack and push root to it 95 | stack nodeStack; 96 | nodeStack.push(root); 97 | 98 | /* Pop all items one by one. Do following for every popped item 99 | a) print it 100 | b) push its right child 101 | c) push its left child 102 | Note that right child is pushed first so that left is processed first */ 103 | while (nodeStack.empty() == false) 104 | { 105 | // Pop the top item from stack and print it 106 | struct node *node = nodeStack.top(); 107 | printf ("%d ", node->data); 108 | nodeStack.pop(); 109 | 110 | // Push right and left children of the popped node to stack 111 | if (node->right) 112 | nodeStack.push(node->right); 113 | if (node->left) 114 | nodeStack.push(node->left); 115 | } 116 | } 117 | 118 | /* Given a binary tree, print its nth nodes of inorder*/ 119 | void NthInorder(struct Node* node, int n) 120 | { 121 | static int count = 0; 122 | if (node == NULL) 123 | return; 124 | 125 | if (count <= n) { 126 | 127 | /* first recur on left child */ 128 | NthInorder(node->left, n); 129 | count++; 130 | 131 | // when count = n then print element 132 | if (count == n) 133 | printf("%d ", node->data); 134 | 135 | /* now recur on right child */ 136 | NthInorder(node->right, n); 137 | } 138 | } 139 | 140 | // function to find the N-th node in the postorder 141 | // traversal of a given binary tree 142 | void NthPostordernode(struct Node* root, int N) 143 | { 144 | static int flag = 0; 145 | 146 | if (root == NULL) 147 | return; 148 | 149 | if (flag <= N) { 150 | 151 | // left recursion 152 | NthPostordernode(root->left, N); 153 | 154 | // right recursion 155 | NthPostordernode(root->right, N); 156 | 157 | flag++; 158 | 159 | // prints the n-th node of preorder traversal 160 | if (flag == N) 161 | cout << root->data; 162 | } 163 | } 164 | /*function to insert element in binary tree */ 165 | 166 | void insert(struct Node* temp, int key) 167 | { 168 | queue q; 169 | 170 | q.push(temp); 171 | 172 | while(!q.empty()) 173 | { 174 | Node* temp = q.front(); 175 | q.pop(); 176 | 177 | if(temp->left == NULL) 178 | { 179 | q->left = newnode(key); 180 | break; 181 | } 182 | else 183 | q.push(temp->left); 184 | if(temp->right == NULL) 185 | { 186 | q->right = newnode(key); 187 | break; 188 | } 189 | else 190 | q.push(temp->right); 191 | } 192 | } 193 | 194 | int findLevel(Node *root, int k, int level) 195 | { 196 | if(root == NULL) 197 | return -1 ; 198 | 199 | if(root->key == k) 200 | return level; 201 | 202 | int l = findLevel(root->left,k,level+1); 203 | 204 | if(l != -1) 205 | return l; 206 | else 207 | return findLevel(root->right,k,level+1); 208 | } 209 | 210 | Node *findDistUtil(Node* root, int n1, int n2, int &d1, 211 | int &d2, int &dist, int lvl) 212 | { 213 | if(root == NULL) 214 | return NULL; 215 | 216 | if(root->key == n1) 217 | { 218 | d1 = lvl; 219 | return root; 220 | } 221 | 222 | if(root->key == n2) 223 | { 224 | d2 = lvl; 225 | return root; 226 | } 227 | 228 | 229 | Node* left_lca = findDistUtil(root->left, n1, n2, d1, d2, dist, lvl+1); 230 | Node* right_lca = findDistUtil(root->right, n1, n2, d1, d2, dist, lvl+1); 231 | 232 | if(left_lca && right_lca) 233 | { 234 | dist = d1 + d2 - 2*lvl; 235 | return root; 236 | } 237 | 238 | if(left_lca != NULL) 239 | return left_lca; 240 | else 241 | return right_lca; 242 | } 243 | 244 | int findDistance(Node *root, int n1, int n2) 245 | { 246 | int d1 = -1, d2 = -1, dist; 247 | 248 | Node *lca = findDistUtil(root, n1, n2, d1, d2, dist, 1); 249 | 250 | if(d1 != -1 && d2 != -1) 251 | return dist; 252 | 253 | if(d1 != -1) 254 | return findLevel(lca, n2, 0); 255 | 256 | if(d2 != -1) 257 | return findLevel(lca, n1, 0); 258 | 259 | return -1; 260 | } 261 | 262 | void deletDeepest(struct Node *root,struct Node * d_node) 263 | { 264 | queue q; 265 | q.push(root); 266 | 267 | while(!q.empty()) 268 | { 269 | temp = q.front(); 270 | q.pop(); 271 | 272 | if(temp->right) 273 | { 274 | if(temp->right == d_node) 275 | { 276 | temp->right = NULL; 277 | delete(d_node); 278 | return; 279 | } 280 | else 281 | q.push(temp->right); 282 | } 283 | 284 | if (temp->left) 285 | { 286 | if (temp->left == d_node) 287 | { 288 | temp->left=NULL; 289 | delete(d_node); 290 | return; 291 | } 292 | else 293 | q.push(temp->left); 294 | } 295 | } 296 | } 297 | 298 | /* function to delete element in binary tree */ 299 | void deletion(struct Node* root, int key) 300 | { 301 | queue q; 302 | 303 | q.push(temp); 304 | 305 | Node *key_node = NULL; 306 | Node* temp; 307 | 308 | while(!q.empty()) 309 | { 310 | temp = q.front(); 311 | q.pop(); 312 | 313 | if(temp->key == key) 314 | key_node = temp; 315 | 316 | if(temp->left) 317 | q.push(temp->left); 318 | 319 | if(temp->right) 320 | q.push(temp->right); 321 | } 322 | 323 | int x = temp->key; 324 | deletDeepest(root, temp); 325 | key_node->key = x; 326 | } 327 | 328 | // Is Mirror Tree /Symmetric Tree 329 | 330 | bool isMirror(struct Node* root1, struct Node* root2) 331 | { 332 | if(root1 == NULL && root2 == NULL) 333 | return true; 334 | 335 | if(root1 && root2 && root1->key == root2->key) 336 | return (isMirror(root1->left,root2->right) && isMirror(root1->right,root2->left)) ; 337 | return false; 338 | } 339 | 340 | bool isSymmetric(struct Node* root) 341 | { 342 | return isMirror(root, root); 343 | } 344 | 345 | /* Given two trees, return true if they are 346 | structurally identical */ 347 | int identicalTrees(struct node* a, struct node* b) 348 | { 349 | /*1. both empty */ 350 | if (a==NULL && b==NULL) 351 | return 1; 352 | 353 | /* 2. both non-empty -> compare them */ 354 | if (a!=NULL && b!=NULL) 355 | { 356 | return 357 | ( 358 | a->data == b->data && 359 | identicalTrees(a->left, b->left) && 360 | identicalTrees(a->right, b->right) 361 | ); 362 | } 363 | 364 | /* 3. one empty, one not -> false */ 365 | return 0; 366 | } 367 | 368 | int height(struct node* node) 369 | { 370 | /* base case tree is empty */ 371 | if(node == NULL) 372 | return 0; 373 | 374 | /* If tree is not empty then height = 1 + max of left 375 | height and right heights */ 376 | return 1 + max(height(node->left), height(node->right)); 377 | } 378 | 379 | //Recurrsive 380 | 381 | void printGivenLevel(struct node* root, int level) 382 | { 383 | if (root == NULL) 384 | return; 385 | if (level == 1) 386 | printf("%d ", root->data); 387 | else if (level > 1) 388 | { 389 | printGivenLevel(root->left, level-1); 390 | printGivenLevel(root->right, level-1); 391 | } 392 | } 393 | 394 | void printLevelOrder(struct node* root) 395 | { 396 | int h = height(root); 397 | int i; 398 | for (i=1; i<=h; i++) 399 | printGivenLevel(root, i); 400 | } 401 | 402 | // Using Queue 403 | 404 | void printLevelOrder_queue(struct node* root) 405 | { 406 | int rear, front; 407 | 408 | queue q; 409 | 410 | struct node *temp_node = root; 411 | 412 | while (temp_node) 413 | { 414 | printf("%d ", temp_node->data); 415 | 416 | /*Enqueue left child */ 417 | if (temp_node->left) 418 | q.push(temp_node->left); 419 | 420 | /*Enqueue right child */ 421 | if (temp_node->right) 422 | q.push(temp_node->right); 423 | 424 | /*Dequeue node and make it temp_node*/ 425 | temp_node = q.front(); 426 | q.pop(); 427 | } 428 | } 429 | 430 | // Boundary Traversal 431 | 432 | void printBoundaryLeft(struct node* root) 433 | { 434 | if(root) 435 | { 436 | if(root->left) 437 | { 438 | cout<data; 439 | printBoundaryLeft(root->left); 440 | } 441 | else if(root->right) 442 | { 443 | cout<data; 444 | printBoundaryLeft(root->right); 445 | } 446 | } 447 | } 448 | 449 | // A simple function to print leaf nodes of a binary tree 450 | void printLeaves(struct node* root) 451 | { 452 | if ( root ) 453 | { 454 | printLeaves(root->left); 455 | 456 | // Print it if it is a leaf node 457 | if ( !(root->left) && !(root->right) ) 458 | printf("%d ", root->data); 459 | 460 | printLeaves(root->right); 461 | } 462 | } 463 | 464 | void printBoundaryRight(struct node* root) 465 | { 466 | if (root) 467 | { 468 | if ( root->right ) 469 | { 470 | // to ensure bottom up order, first call for right 471 | // subtree, then print this node 472 | printBoundaryRight(root->right); 473 | printf("%d ", root->data); 474 | } 475 | else if ( root->left ) 476 | { 477 | printBoundaryRight(root->left); 478 | printf("%d ", root->data); 479 | } 480 | // do nothing if it is a leaf node, this way we avoid 481 | // duplicates in output 482 | } 483 | } 484 | 485 | void printBoundary (struct node* root) 486 | { 487 | if(root) 488 | { 489 | printf("%d ",root->data); 490 | 491 | // Print the left boundary in top-down manner. 492 | printBoundaryLeft(root->left); 493 | 494 | // Print all leaf nodes 495 | printLeaves(root->left); 496 | printLeaves(root->right); 497 | 498 | // Print the right boundary in bottom-up manner 499 | printBoundaryRight(root->right); 500 | } 501 | } 502 | 503 | // Spiral print levelorder 504 | 505 | /* Function to print spiral traversal of a tree*/ 506 | void printSpiral(struct node* root) 507 | { 508 | int h = height(root); 509 | int i; 510 | 511 | /*ltr -> Left to Right. If this variable is set, 512 | then the given level is traverseed from left to right. */ 513 | bool ltr = false; 514 | for(i=1; i<=h; i++) 515 | { 516 | printGivenLevel(root, i, ltr); 517 | 518 | /*Revert ltr to traverse next level in opposite order*/ 519 | ltr = !ltr; 520 | } 521 | } 522 | 523 | /* Print nodes at a given level */ 524 | void printGivenLevel(struct node* root, int level, int ltr) 525 | { 526 | if(root == NULL) 527 | return; 528 | if(level == 1) 529 | printf("%d ", root->data); 530 | else if (level > 1) 531 | { 532 | if(ltr) 533 | { 534 | printGivenLevel(root->left, level-1, ltr); 535 | printGivenLevel(root->right, level-1, ltr); 536 | } 537 | else 538 | { 539 | printGivenLevel(root->right, level-1, ltr); 540 | printGivenLevel(root->left, level-1, ltr); 541 | } 542 | } 543 | } 544 | 545 | // Spiral -> Iterative 546 | 547 | void printSpiral(struct node *root) 548 | { 549 | if (root == NULL) return; // NULL check 550 | 551 | // Create two stacks to store alternate levels 552 | stack s1; // For levels to be printed from right to left 553 | stack s2; // For levels to be printed from left to right 554 | 555 | // Push first level to first stack 's1' 556 | s1.push(root); 557 | 558 | // Keep ptinting while any of the stacks has some nodes 559 | while (!s1.empty() || !s2.empty()) 560 | { 561 | // Print nodes of current level from s1 and push nodes of 562 | // next level to s2 563 | while (!s1.empty()) 564 | { 565 | struct node *temp = s1.top(); 566 | s1.pop(); 567 | cout << temp->data << " "; 568 | 569 | // Note that is right is pushed before left 570 | if (temp->right) 571 | s2.push(temp->right); 572 | if (temp->left) 573 | s2.push(temp->left); 574 | } 575 | 576 | // Print nodes of current level from s2 and push nodes of 577 | // next level to s1 578 | while (!s2.empty()) 579 | { 580 | struct node *temp = s2.top(); 581 | s2.pop(); 582 | cout << temp->data << " "; 583 | 584 | // Note that is left is pushed before right 585 | if (temp->left) 586 | s1.push(temp->left); 587 | if (temp->right) 588 | s1.push(temp->right); 589 | } 590 | } 591 | } 592 | 593 | // Construction & Conversion : 594 | 595 | /* Recursive function to construct binary of size len from 596 | Inorder traversal in[] and Preorder traversal pre[]. Initial values 597 | of inStrt and inEnd should be 0 and len -1. The function doesn't 598 | do any error checking for cases where inorder and preorder 599 | do not form a tree */ 600 | struct Node* buildTree(char in[], char pre[], int inStrt, int inEnd) 601 | { 602 | static int preIndex = 0; 603 | 604 | if(inStrt > inEnd) 605 | return NULL; 606 | 607 | /* Pick current node from Preorder traversal using preIndex 608 | and increment preIndex */ 609 | struct node *tNode = newNode(pre[preIndex++]); 610 | 611 | /* If this node has no children then return */ 612 | if(inStrt == inEnd) 613 | return tNode; 614 | 615 | /* Else find the index of this node in Inorder traversal */ 616 | int inIndex = search(in, inStrt, inEnd, tNode->data); 617 | 618 | /* Using index in Inorder traversal, construct left and 619 | right subtress */ 620 | tNode->left = buildTree(in, pre, inStrt, inIndex-1); 621 | tNode->right = buildTree(in, pre, inIndex+1, inEnd); 622 | 623 | return tNode; 624 | } 625 | 626 | /* UTILITY FUNCTIONS */ 627 | /* Function to find index of value in arr[start...end] 628 | The function assumes that value is present in in[] */ 629 | int search(char arr[], int strt, int end, char value) 630 | { 631 | int i; 632 | for(i = strt; i <= end; i++) 633 | { 634 | if(arr[i] == value) 635 | return i; 636 | } 637 | } 638 | 639 | // LCA 640 | 641 | struct Node *findLCA(struct Node* root, int n1, int n2) 642 | { 643 | // Base case 644 | if (root == NULL) return NULL; 645 | 646 | // If either n1 or n2 matches with root's key, report 647 | // the presence by returning root (Note that if a key is 648 | // ancestor of other, then the ancestor key becomes LCA 649 | if (root->key == n1 || root->key == n2) 650 | return root; 651 | 652 | // Look for keys in left and right subtrees 653 | Node *left_lca = findLCA(root->left, n1, n2); 654 | Node *right_lca = findLCA(root->right, n1, n2); 655 | 656 | // If both of the above calls return Non-NULL, then one key 657 | // is present in once subtree and other is present in other, 658 | // So this node is the LCA 659 | if (left_lca && right_lca) return root; 660 | 661 | // Otherwise check if left subtree or right subtree is LCA 662 | return (left_lca != NULL)? left_lca: right_lca; 663 | } 664 | 665 | // Diameter 666 | 667 | /* Function to get diameter of a binary tree */ 668 | int diameter(struct node * tree) 669 | { 670 | /* base case where tree is empty */ 671 | if (tree == NULL) 672 | return 0; 673 | 674 | /* get the height of left and right sub-trees */ 675 | int lheight = height(tree->left); 676 | int rheight = height(tree->right); 677 | 678 | /* get the diameter of left and right sub-trees */ 679 | int ldiameter = diameter(tree->left); 680 | int rdiameter = diameter(tree->right); 681 | 682 | /* Return max of following three 683 | 1) Diameter of left subtree 684 | 2) Diameter of right subtree 685 | 3) Height of left subtree + height of right subtree + 1 */ 686 | return max(lheight + rheight + 1, max(ldiameter, rdiameter)); 687 | } 688 | 689 | /* Helper function for getLevel(). It returns level of the data if data is 690 | present in tree, otherwise returns 0.*/ 691 | int getLevelUtil(struct node *node, int data, int level) 692 | { 693 | if (node == NULL) 694 | return 0; 695 | 696 | if (node->data == data) 697 | return level; 698 | 699 | int downlevel = getLevelUtil(node->left, data, level+1); 700 | if (downlevel != 0) 701 | return downlevel; 702 | 703 | downlevel = getLevelUtil(node->right, data, level+1); 704 | return downlevel; 705 | } 706 | 707 | /* Returns level of given data value */ 708 | int getLevel(struct node *node, int data) 709 | { 710 | return getLevelUtil(node,data,1); 711 | } 712 | 713 | int getLeafCount(struct node* node) 714 | { 715 | if(node == NULL) 716 | return 0; 717 | if(node->left == NULL && node->right==NULL) 718 | return 1; 719 | else 720 | return getLeafCount(node->left) + getLeafCount(node->right); 721 | } 722 | 723 | // Left view of the tree 724 | // Recursive function to print left view of a binary tree. 725 | void leftViewUtil(struct node *root, int level, int *max_level) 726 | { 727 | // Base Case 728 | if (root==NULL) return; 729 | 730 | // If this is the first node of its level 731 | if (*max_level < level) 732 | { 733 | printf("%d\t", root->data); 734 | *max_level = level; 735 | } 736 | 737 | // Recur for left and right subtrees 738 | leftViewUtil(root->left, level+1, max_level); 739 | leftViewUtil(root->right, level+1, max_level); 740 | } 741 | 742 | // A wrapper over leftViewUtil() 743 | void leftView(struct node *root) 744 | { 745 | int max_level = 0; 746 | leftViewUtil(root, 1, &max_level); 747 | } 748 | 749 | // Bottom view of the tree 750 | // Method that prints the bottom view. 751 | void bottomView(Node *root) 752 | { 753 | if (root == NULL) 754 | return; 755 | 756 | // Initialize a variable 'hd' with 0 757 | // for the root element. 758 | int hd = 0; 759 | 760 | // TreeMap which stores key value pair 761 | // sorted on key value 762 | map m; 763 | 764 | // Queue to store tree nodes in level 765 | // order traversal 766 | queue q; 767 | 768 | // Assign initialized horizontal distance 769 | // value to root node and add it to the queue. 770 | root->hd = hd; 771 | q.push(root); // In STL, push() is used enqueue an item 772 | 773 | // Loop until the queue is empty (standard 774 | // level order loop) 775 | while (!q.empty()) 776 | { 777 | Node *temp = q.front(); 778 | q.pop(); // In STL, pop() is used dequeue an item 779 | 780 | // Extract the horizontal distance value 781 | // from the dequeued tree node. 782 | hd = temp->hd; 783 | 784 | // Put the dequeued tree node to TreeMap 785 | // having key as horizontal distance. Every 786 | // time we find a node having same horizontal 787 | // distance we need to replace the data in 788 | // the map. 789 | m[hd] = temp->data; 790 | 791 | // If the dequeued node has a left child, add 792 | // it to the queue with a horizontal distance hd-1. 793 | if (temp->left != NULL) 794 | { 795 | temp->left->hd = hd-1; 796 | q.push(temp->left); 797 | } 798 | 799 | // If the dequeued node has a right child, add 800 | // it to the queue with a horizontal distance 801 | // hd+1. 802 | if (temp->right != NULL) 803 | { 804 | temp->right->hd = hd+1; 805 | q.push(temp->right); 806 | } 807 | } 808 | 809 | // Traverse the map elements using the iterator. 810 | for (auto i = m.begin(); i != m.end(); ++i) 811 | cout << i->second << " "; 812 | } 813 | 814 | // The main function to print vertical oder of a 815 | // binary tree with given root 816 | void printVerticalOrder(Node* root) 817 | { 818 | // Base case 819 | if (!root) 820 | return; 821 | 822 | // Create a map and store vertical oder in 823 | // map using function getVerticalOrder() 824 | map < int,vector > m; 825 | int hd = 0; 826 | 827 | // Create queue to do level order traversal. 828 | // Every item of queue contains node and 829 | // horizontal distance. 830 | queue > que; 831 | que.push(make_pair(root, hd)); 832 | 833 | while (!que.empty()) 834 | { 835 | // pop from queue front 836 | pair temp = que.front(); 837 | que.pop(); 838 | hd = temp.second; 839 | Node* node = temp.first; 840 | 841 | // insert this node's data in vector of hash 842 | m[hd].push_back(node->key); 843 | 844 | if (node->left != NULL) 845 | que.push(make_pair(node->left, hd-1)); 846 | if (node->right != NULL) 847 | que.push(make_pair(node->right, hd+1)); 848 | } 849 | 850 | // Traverse the map and print nodes at 851 | // every horigontal distance (hd) 852 | map< int,vector > :: iterator it; 853 | for (it=m.begin(); it!=m.end(); it++) 854 | { 855 | for (int i=0; isecond.size(); ++i) 856 | cout << it->second[i] << " "; 857 | cout << endl; 858 | } 859 | } 860 | 861 | // Is Height Balanced 862 | 863 | bool isBalanced(struct node *root) 864 | { 865 | int lh; /* for height of left subtree */ 866 | int rh; /* for height of right subtree */ 867 | 868 | /* If tree is empty then return true */ 869 | if(root == NULL) 870 | return 1; 871 | 872 | /* Get the height of left and right sub trees */ 873 | lh = height(root->left); 874 | rh = height(root->right); 875 | 876 | if( abs(lh-rh) <= 1 && 877 | isBalanced(root->left) && 878 | isBalanced(root->right)) 879 | return 1; 880 | 881 | /* If we reach here then tree is not height-balanced */ 882 | return 0; 883 | } 884 | 885 | /* This is the core function to convert Tree to list. This function follows 886 | steps 1 and 2 of the above algorithm */ 887 | node* bintree2listUtil(node* root) 888 | { 889 | // Base case 890 | if (root == NULL) 891 | return root; 892 | 893 | // Convert the left subtree and link to root 894 | if (root->left != NULL) 895 | { 896 | // Convert the left subtree 897 | node* left = bintree2listUtil(root->left); 898 | 899 | // Find inorder predecessor. After this loop, left 900 | // will point to the inorder predecessor 901 | for (; left->right!=NULL; left=left->right); 902 | 903 | // Make root as next of the predecessor 904 | left->right = root; 905 | 906 | // Make predecssor as previous of root 907 | root->left = left; 908 | } 909 | 910 | // Convert the right subtree and link to root 911 | if (root->right!=NULL) 912 | { 913 | // Convert the right subtree 914 | node* right = bintree2listUtil(root->right); 915 | 916 | // Find inorder successor. After this loop, right 917 | // will point to the inorder successor 918 | for (; right->left!=NULL; right = right->left); 919 | 920 | // Make root as previous of successor 921 | right->left = root; 922 | 923 | // Make successor as next of root 924 | root->right = right; 925 | } 926 | 927 | return root; 928 | } 929 | 930 | // The main function that first calls bintree2listUtil(), then follows step 3 931 | // of the above algorithm 932 | node* bintree2list(node *root) 933 | { 934 | // Base case 935 | if (root == NULL) 936 | return root; 937 | 938 | // Convert to DLL using bintree2listUtil() 939 | root = bintree2listUtil(root); 940 | 941 | // bintree2listUtil() returns root node of the converted 942 | // DLL. We need pointer to the leftmost node which is 943 | // head of the constructed DLL, so move to the leftmost node 944 | while (root->left != NULL) 945 | root = root->left; 946 | 947 | return (root); 948 | } 949 | 950 | void mirror(struct Node* node) 951 | { 952 | if (node==NULL) 953 | return; 954 | else 955 | { 956 | struct Node* temp; 957 | 958 | /* do the subtrees */ 959 | mirror(node->left); 960 | mirror(node->right); 961 | 962 | /* swap the pointers in this node */ 963 | temp = node->left; 964 | node->left = node->right; 965 | node->right = temp; 966 | } 967 | } 968 | 969 | /* Returns true if the given tree is a binary search tree 970 | (efficient version). */ 971 | int isBST(struct node* node) 972 | { 973 | return(isBSTUtil(node, INT_MIN, INT_MAX)); 974 | } 975 | 976 | /* Returns true if the given tree is a BST and its 977 | values are >= min and <= max. */ 978 | int isBSTUtil(struct node* node, int min, int max) 979 | { 980 | /* an empty tree is BST */ 981 | if (node==NULL) 982 | return 1; 983 | 984 | /* false if this node violates the min/max constraint */ 985 | if (node->data < min || node->data > max) 986 | return 0; 987 | 988 | /* otherwise check the subtrees recursively, 989 | tightening the min or max constraint */ 990 | return 991 | isBSTUtil(node->left, min, node->data-1) && // Allow only distinct values 992 | isBSTUtil(node->right, node->data+1, max); // Allow only distinct values 993 | } 994 | 995 | // Function to check if root to leaf path 996 | // sum to a given number in BST 997 | int checkThesum(struct Node *root, int path[], int i, int sum) 998 | { 999 | int sum1 = 0, x, y, j; 1000 | 1001 | if(root == NULL) 1002 | return 0; 1003 | 1004 | // insert the data of a node 1005 | path[i] = root->data; 1006 | 1007 | // if the node is leaf 1008 | // add all the element in array 1009 | if(root->left==NULL&&root->right==NULL) 1010 | { 1011 | for(j = 0; j <= i; j++) 1012 | sum1 = sum1 + path[j]; 1013 | 1014 | // if the sum of root node to leaf 1015 | // node data is equal then return 1 1016 | if(sum == sum1) 1017 | return 1; 1018 | else 1019 | return 0; 1020 | } 1021 | 1022 | x = checkThesum(root->left, path, i+1, sum); 1023 | 1024 | // if x is 1, it means the given sum is matched 1025 | // with root to leaf node sum 1026 | if(x==1) 1027 | return 1; 1028 | else 1029 | { 1030 | return checkThesum(root->right, path, i+1, sum); 1031 | } 1032 | } 1033 | 1034 | bool hasPathSum(struct node* node, int sum) 1035 | { 1036 | /* return true if we run out of tree and sum==0 */ 1037 | if (node == NULL) 1038 | { 1039 | return (sum == 0); 1040 | } 1041 | 1042 | else 1043 | { 1044 | bool ans = 0; 1045 | 1046 | /* otherwise check both subtrees */ 1047 | int subSum = sum - node->data; 1048 | 1049 | /* If we reach a leaf node and sum becomes 0 then return true*/ 1050 | if ( subSum == 0 && node->left == NULL && node->right == NULL ) 1051 | return 1; 1052 | 1053 | if(node->left) 1054 | ans = ans || hasPathSum(node->left, subSum); 1055 | if(node->right) 1056 | ans = ans || hasPathSum(node->right, subSum); 1057 | 1058 | return ans; 1059 | } 1060 | } 1061 | 1062 | // Returns sum of all root to leaf paths. The first parameter is root 1063 | // of current subtree, the second parameter is value of the number formed 1064 | // by nodes from root to this node 1065 | int treePathsSumUtil(struct node *root, int val) 1066 | { 1067 | // Base case 1068 | if (root == NULL) return 0; 1069 | 1070 | // Update val 1071 | val = (val*10 + root->data); 1072 | 1073 | // if current node is leaf, return the current value of val 1074 | if (root->left==NULL && root->right==NULL) 1075 | return val; 1076 | 1077 | // recur sum of values for left and right subtree 1078 | return treePathsSumUtil(root->left, val) + 1079 | treePathsSumUtil(root->right, val); 1080 | } 1081 | 1082 | // A wrapper function over treePathsSumUtil() 1083 | int treePathsSum(struct node *root) 1084 | { 1085 | // Pass the initial value as 0 as there is nothing above root 1086 | return treePathsSumUtil(root, 0); 1087 | } 1088 | 1089 | // Function to convert binary tree into 1090 | // linked list by altering the right node 1091 | // and making left node point to NULL 1092 | void flatten(struct Node* root) 1093 | { 1094 | // base condition- return if root is NULL 1095 | // or if it is a leaf node 1096 | if (root == NULL || root->left == NULL && 1097 | root->right == NULL) { 1098 | return; 1099 | } 1100 | 1101 | // if root->left exists then we have 1102 | // to make it root->right 1103 | if (root->left != NULL) 1104 | { 1105 | // move left recursively 1106 | flatten(root->left); 1107 | 1108 | // store the node root->right 1109 | struct Node* tmpRight = root->right; 1110 | root->right = root->left; 1111 | root->left = NULL; 1112 | 1113 | // find the position to insert 1114 | // the stored value 1115 | struct Node* t = root->right; 1116 | while (t->right != NULL) 1117 | { 1118 | t = t->right; 1119 | } 1120 | 1121 | // insert the stored value 1122 | t->right = tmpRight; 1123 | } 1124 | 1125 | // now call the same function 1126 | // for root->right 1127 | flatten(root->right); 1128 | } --------------------------------------------------------------------------------