├── 1.cpp ├── 10.cpp ├── 100.cpp ├── 101.cpp ├── 102.cpp ├── 103.cpp ├── 104.cpp ├── 105.cpp ├── 106.cpp ├── 107.cpp ├── 108.cpp ├── 109.cpp ├── 11.cpp ├── 110.cpp ├── 111.cpp ├── 112.cpp ├── 113.cpp ├── 114.cpp ├── 115.cpp ├── 116.cpp ├── 117.cpp ├── 118.cpp ├── 119.cpp ├── 12.cpp ├── 120.cpp ├── 121.cpp ├── 122.cpp ├── 123.cpp ├── 124.cpp ├── 125.cpp ├── 126.cpp ├── 127.cpp ├── 128.cpp ├── 129.cpp ├── 13.cpp ├── 130.cpp ├── 131.cpp ├── 132.cpp ├── 134.cpp ├── 135.cpp ├── 136.cpp ├── 137.cpp ├── 138.cpp ├── 139.cpp ├── 14.cpp ├── 140.cpp ├── 141.cpp ├── 142.cpp ├── 143.cpp ├── 144.cpp ├── 145.cpp ├── 146.cpp ├── 147.cpp ├── 148.cpp ├── 149.cpp ├── 15.cpp ├── 150.cpp ├── 151.cpp ├── 152.cpp ├── 153.cpp ├── 154.cpp ├── 155.cpp ├── 156.cpp ├── 157.cpp ├── 158.cpp ├── 159.cpp ├── 16.cpp ├── 160.cpp ├── 161.cpp ├── 162.cpp ├── 163.cpp ├── 164.cpp ├── 165.cpp ├── 166.cpp ├── 167.cpp ├── 168.cpp ├── 169.cpp ├── 17.cpp ├── 170.cpp ├── 171.cpp ├── 172.cpp ├── 173.cpp ├── 174.cpp ├── 175.cpp ├── 176.cpp ├── 177.cpp ├── 178.cpp ├── 179.cpp ├── 18.cpp ├── 180.cpp ├── 181.cpp ├── 182.cpp ├── 183.cpp ├── 184.cpp ├── 185.cpp ├── 186.cpp ├── 187.cpp ├── 188.cpp ├── 189.cpp ├── 19.cpp ├── 190.cpp ├── 191.cpp ├── 192.cpp ├── 193.cpp ├── 194.cpp ├── 195.cpp ├── 196.cpp ├── 197.cpp ├── 198.cpp ├── 199.cpp ├── 2.cpp ├── 20.cpp ├── 200.cpp ├── 201.cpp ├── 202.cpp ├── 203.cpp ├── 204.cpp ├── 205.cpp ├── 206.cpp ├── 207.cpp ├── 208.cpp ├── 209.cpp ├── 21.cpp ├── 210.cpp ├── 211.cpp ├── 212.cpp ├── 213.cpp ├── 214.cpp ├── 215.cpp ├── 216.cpp ├── 217.cpp ├── 218.cpp ├── 219.cpp ├── 22.cpp ├── 220.cpp ├── 221.cpp ├── 222.cpp ├── 223.cpp ├── 224.cpp ├── 225.cpp ├── 226.cpp ├── 227.cpp ├── 228.cpp ├── 229.cpp ├── 23.cpp ├── 230.cpp ├── 231.cpp ├── 232.cpp ├── 233.cpp ├── 234.cpp ├── 235.cpp ├── 236.cpp ├── 237.cpp ├── 238.cpp ├── 239.cpp ├── 24.cpp ├── 240.cpp ├── 241.cpp ├── 242.cpp ├── 243.cpp ├── 244.cpp ├── 245.cpp ├── 246.cpp ├── 247.cpp ├── 248.cpp ├── 249.cpp ├── 25.cpp ├── 250.cpp ├── 251.cpp ├── 252.cpp ├── 253.cpp ├── 254.cpp ├── 255.cpp ├── 256.cpp ├── 257.cpp ├── 258.cpp ├── 259.cpp ├── 26.cpp ├── 260.cpp ├── 261.cpp ├── 262.cpp ├── 263.cpp ├── 264.cpp ├── 265.cpp ├── 266.cpp ├── 267.cpp ├── 268.cpp ├── 269.cpp ├── 27.cpp ├── 270.cpp ├── 271.cpp ├── 272.cpp ├── 273.cpp ├── 274.cpp ├── 275.cpp ├── 276.cpp ├── 277.cpp ├── 278.cpp ├── 279.cpp ├── 28.cpp ├── 280.cpp ├── 281.cpp ├── 282.cpp ├── 283.cpp ├── 284.cpp ├── 285.cpp ├── 286.cpp ├── 287.cpp ├── 288.cpp ├── 289.cpp ├── 29.cpp ├── 290.cpp ├── 291.cpp ├── 292.cpp ├── 293.cpp ├── 294.cpp ├── 295.cpp ├── 296.cpp ├── 297.cpp ├── 298.cpp ├── 299.cpp ├── 3.cpp ├── 30.cpp ├── 300.cpp ├── 301.cpp ├── 302.cpp ├── 303.cpp ├── 304.cpp ├── 305.cpp ├── 306.cpp ├── 307.cpp ├── 308.cpp ├── 309.cpp ├── 31.cpp ├── 310.cpp ├── 311.cpp ├── 312.cpp ├── 313.cpp ├── 314.cpp ├── 315.cpp ├── 316.cpp ├── 317.cpp ├── 318.cpp ├── 319.cpp ├── 32.cpp ├── 320.cpp ├── 321.cpp ├── 322.cpp ├── 323.cpp ├── 324.cpp ├── 325.cpp ├── 326.cpp ├── 327.cpp ├── 328.cpp ├── 329.cpp ├── 33.cpp ├── 330.cpp ├── 331.cpp ├── 332.cpp ├── 333.cpp ├── 334.cpp ├── 335.cpp ├── 336.cpp ├── 337.cpp ├── 338.cpp ├── 339.cpp ├── 34.cpp ├── 340.cpp ├── 341.cpp ├── 342.cpp ├── 343.cpp ├── 344.cpp ├── 345.cpp ├── 346.cpp ├── 347.cpp ├── 348.cpp ├── 349.cpp ├── 35.cpp ├── 350.cpp ├── 351.cpp ├── 352.cpp ├── 353.cpp ├── 354.cpp ├── 355.cpp ├── 356.cpp ├── 357.cpp ├── 358.cpp ├── 359.cpp ├── 36.cpp ├── 360.cpp ├── 361.cpp ├── 362.cpp ├── 363.cpp ├── 364.cpp ├── 365.cpp ├── 366.cpp ├── 367.cpp ├── 368.cpp ├── 369.cpp ├── 37.cpp ├── 370.cpp ├── 371.cpp ├── 372.cpp ├── 373.cpp ├── 374.cpp ├── 375.cpp ├── 376.cpp ├── 377.cpp ├── 378.cpp ├── 379.cpp ├── 38.cpp ├── 380.cpp ├── 381.cpp ├── 382.cpp ├── 383.cpp ├── 384.cpp ├── 385.cpp ├── 386.cpp ├── 387.cpp ├── 388.cpp ├── 389.cpp ├── 39.cpp ├── 390.cpp ├── 391.cpp ├── 392.cpp ├── 393.cpp ├── 394.cpp ├── 395.cpp ├── 396.cpp ├── 397.cpp ├── 398.cpp ├── 399.cpp ├── 4.cpp ├── 40.cpp ├── 400.cpp ├── 401.cpp ├── 402.cpp ├── 403.cpp ├── 404.cpp ├── 405.cpp ├── 406.cpp ├── 407.cpp ├── 408.cpp ├── 409.cpp ├── 41.cpp ├── 410.cpp ├── 411.cpp ├── 412.cpp ├── 413.cpp ├── 414.cpp ├── 415.cpp ├── 416.cpp ├── 417.cpp ├── 418.cpp ├── 419.cpp ├── 42.cpp ├── 420.cpp ├── 421.cpp ├── 422.cpp ├── 423.cpp ├── 424.cpp ├── 425.cpp ├── 426.cpp ├── 427.cpp ├── 428.cpp ├── 429.cpp ├── 43.cpp ├── 430.cpp ├── 431.cpp ├── 432.cpp ├── 433.cpp ├── 434.cpp ├── 435.cpp ├── 436.cpp ├── 437.cpp ├── 438.cpp ├── 439.cpp ├── 44.cpp ├── 440.cpp ├── 441.cpp ├── 442.cpp ├── 443.cpp ├── 444.cpp ├── 445.cpp ├── 446.cpp ├── 447.cpp ├── 448.cpp ├── 449.cpp ├── 45.cpp ├── 450.cpp ├── 451.cpp ├── 452.cpp ├── 453.cpp ├── 454.cpp ├── 455.cpp ├── 456.cpp ├── 457.cpp ├── 458.cpp ├── 459.cpp ├── 46.cpp ├── 460.cpp ├── 461.cpp ├── 462.cpp ├── 463.cpp ├── 464.cpp ├── 465.cpp ├── 466.cpp ├── 467.cpp ├── 468.cpp ├── 469.cpp ├── 47.cpp ├── 470.cpp ├── 471.cpp ├── 472.cpp ├── 473.cpp ├── 474.cpp ├── 475.cpp ├── 476.cpp ├── 477.cpp ├── 478.cpp ├── 479.cpp ├── 48.cpp ├── 480.cpp ├── 481.cpp ├── 482.cpp ├── 483.cpp ├── 484.cpp ├── 485.cpp ├── 486.cpp ├── 487.cpp ├── 488.cpp ├── 489.cpp ├── 49.cpp ├── 490.cpp ├── 491.cpp ├── 492.cpp ├── 493.cpp ├── 495.cpp ├── 496.cpp ├── 497.cpp ├── 498.cpp ├── 499.cpp ├── 5.cpp ├── 50.cpp ├── 500.cpp ├── 51.cpp ├── 52.cpp ├── 53.cpp ├── 54.cpp ├── 55.cpp ├── 56.cpp ├── 57.cpp ├── 58.cpp ├── 59.cpp ├── 6.cpp ├── 60.cpp ├── 61.cpp ├── 62.cpp ├── 63.cpp ├── 64.cpp ├── 65.cpp ├── 66.cpp ├── 67.cpp ├── 68.cpp ├── 69.cpp ├── 7.cpp ├── 70.cpp ├── 71.cpp ├── 72.cpp ├── 73.cpp ├── 74.cpp ├── 75.cpp ├── 76.cpp ├── 77.cpp ├── 78.cpp ├── 79.cpp ├── 8.cpp ├── 80.cpp ├── 81.cpp ├── 82.cpp ├── 83.cpp ├── 84.cpp ├── 85.cpp ├── 86.cpp ├── 87.cpp ├── 88.cpp ├── 89.cpp ├── 9.cpp ├── 90.cpp ├── 91.cpp ├── 92.cpp ├── 93.cpp ├── 94.cpp ├── 95.cpp ├── 96.cpp ├── 97.cpp ├── 98.cpp ├── 99.cpp └── README.md /1.cpp: -------------------------------------------------------------------------------- 1 | /* C++ Program to find sum of elements 2 | in a given array */ 3 | #include 4 | using namespace std; 5 | 6 | // function to return sum of elements 7 | // in an array of size n 8 | int sum(int arr[], int n) 9 | { 10 | int sum = 0; // initialize sum 11 | 12 | // Iterate through all elements 13 | // and add them to sum 14 | for (int i = 0; i < n; i++) 15 | sum += arr[i]; 16 | 17 | return sum; 18 | } 19 | 20 | // Driver code 21 | int main() 22 | { 23 | int arr[] = {12, 3, 4, 15}; 24 | int n = sizeof(arr) / sizeof(arr[0]); 25 | cout << "Sum of given array is " << sum(arr, n); 26 | return 0; 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /101.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for counting sort 2 | #include 3 | #include 4 | using namespace std; 5 | #define RANGE 255 6 | 7 | // The main function that sort 8 | // the given string arr[] in 9 | // alphabetical order 10 | void countSort(char arr[]) 11 | { 12 | // The output character array 13 | // that will have sorted arr 14 | char output[strlen(arr)]; 15 | 16 | // Create a count array to store count of individual 17 | // characters and initialize count array as 0 18 | int count[RANGE + 1], i; 19 | memset(count, 0, sizeof(count)); 20 | 21 | // Store count of each character 22 | for (i = 0; arr[i]; ++i) 23 | ++count[arr[i]]; 24 | 25 | // Change count[i] so that count[i] now contains actual 26 | // position of this character in output array 27 | for (i = 1; i <= RANGE; ++i) 28 | count[i] += count[i - 1]; 29 | 30 | // Build the output character array 31 | for (i = 0; arr[i]; ++i) { 32 | output[count[arr[i]] - 1] = arr[i]; 33 | --count[arr[i]]; 34 | } 35 | 36 | /* 37 | For Stable algorithm 38 | for (i = sizeof(arr)-1; i>=0; --i) 39 | { 40 | output[count[arr[i]]-1] = arr[i]; 41 | --count[arr[i]]; 42 | } 43 | 44 | For Logic : See implementation 45 | */ 46 | 47 | // Copy the output array to arr, so that arr now 48 | // contains sorted characters 49 | for (i = 0; arr[i]; ++i) 50 | arr[i] = output[i]; 51 | } 52 | 53 | // Driver code 54 | int main() 55 | { 56 | char arr[] = "geeksforgeeks"; 57 | 58 | countSort(arr); 59 | 60 | cout << "Sorted character array is " << arr; 61 | return 0; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /103.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find the maximum repeating number 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Returns maximum repeating element in arr[0..n-1]. 7 | // The array elements are in range from 0 to k-1 8 | int maxRepeating(int* arr, int n, int k) 9 | { 10 | // Iterate though input array, for every element 11 | // arr[i], increment arr[arr[i]%k] by k 12 | for (int i = 0; i< n; i++) 13 | arr[arr[i]%k] += k; 14 | 15 | // Find index of the maximum repeating element 16 | int max = arr[0], result = 0; 17 | for (int i = 1; i < n; i++) 18 | { 19 | if (arr[i] > max) 20 | { 21 | max = arr[i]; 22 | result = i; 23 | } 24 | } 25 | 26 | /* Uncomment this code to get the original array back 27 | for (int i = 0; i< n; i++) 28 | arr[i] = arr[i]%k; */ 29 | 30 | // Return index of the maximum element 31 | return result; 32 | } 33 | 34 | // Driver program to test above function 35 | int main() 36 | { 37 | int arr[] = {2, 3, 3, 5, 3, 4, 1, 7}; 38 | int n = sizeof(arr)/sizeof(arr[0]); 39 | int k = 8; 40 | 41 | cout << "The maximum repeating number is " << 42 | maxRepeating(arr, n, k) << endl; 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /104.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of the approach 2 | #include 3 | using namespace std; 4 | 5 | // Function to return the maximum profit 6 | // that can be made after buying and 7 | // selling the given stocks 8 | int maxProfit(int price[], int start, int end) 9 | { 10 | 11 | // If the stocks can't be bought 12 | if (end <= start) 13 | return 0; 14 | 15 | // Initialise the profit 16 | int profit = 0; 17 | 18 | // The day at which the stock 19 | // must be bought 20 | for (int i = start; i < end; i++) { 21 | 22 | // The day at which the 23 | // stock must be sold 24 | for (int j = i + 1; j <= end; j++) { 25 | 26 | // If byuing the stock at ith day and 27 | // selling it at jth day is profitable 28 | if (price[j] > price[i]) { 29 | 30 | // Update the current profit 31 | int curr_profit = price[j] - price[i] 32 | + maxProfit(price, start, i - 1) 33 | + maxProfit(price, j + 1, end); 34 | 35 | // Update the maximum profit so far 36 | profit = max(profit, curr_profit); 37 | } 38 | } 39 | } 40 | return profit; 41 | } 42 | 43 | // Driver code 44 | int main() 45 | { 46 | int price[] = { 100, 180, 260, 310, 47 | 40, 535, 695 }; 48 | int n = sizeof(price) / sizeof(price[0]); 49 | 50 | cout << maxProfit(price, 0, n - 1); 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /107.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to find a peak element 2 | #include 3 | using namespace std; 4 | 5 | // Find the peak element in the array 6 | int findPeak(int arr[], int n) 7 | { 8 | // first or last element is peak element 9 | if (n == 1) 10 | return 0; 11 | if (arr[0] >= arr[1]) 12 | return 0; 13 | if (arr[n - 1] >= arr[n - 2]) 14 | return n - 1; 15 | 16 | // check for every other element 17 | for (int i = 1; i < n - 1; i++) { 18 | 19 | // check if the neighbors are smaller 20 | if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) 21 | return i; 22 | } 23 | } 24 | 25 | // Driver Code 26 | int main() 27 | { 28 | int arr[] = { 1, 3, 20, 4, 1, 0 }; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | cout << "Index of a peak point is " 31 | << findPeak(arr, n); 32 | return 0; 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /113.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to merge k sorted arrays of size n each. 2 | #include 3 | using namespace std; 4 | #define n 4 5 | 6 | 7 | // A utility function to print array elements 8 | void printArray(int arr[], int size) 9 | { 10 | for (int i=0; i < size; i++) 11 | cout << arr[i] << " "; 12 | } 13 | 14 | // This function takes an array of arrays as an argument and 15 | // All arrays are assumed to be sorted. It merges them together 16 | // and prints the final sorted output. 17 | void mergeKArrays(int arr[][n], int a, int output[]) 18 | { 19 | int c=0; 20 | 21 | //traverse the matrix 22 | for(int i=0; i 3 | using namespace std; 4 | 5 | // Function which pushes all zeros to end of an array. 6 | void pushZerosToEnd(int arr[], int n) 7 | { 8 | int count = 0; // Count of non-zero elements 9 | 10 | // Traverse the array. If element encountered is non- 11 | // zero, then replace the element at index 'count' 12 | // with this element 13 | for (int i = 0; i < n; i++) 14 | if (arr[i] != 0) 15 | arr[count++] = arr[i]; // here count is 16 | // incremented 17 | 18 | // Now all non-zero elements have been shifted to 19 | // front and 'count' is set as index of first 0. 20 | // Make all elements 0 from count to end. 21 | while (count < n) 22 | arr[count++] = 0; 23 | } 24 | 25 | // Driver program to test above function 26 | int main() 27 | { 28 | int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | pushZerosToEnd(arr, n); 31 | cout << "Array after pushing all zeros to end of array :\n"; 32 | for (int i = 0; i < n; i++) 33 | cout << arr[i] << " "; 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /117.cpp: -------------------------------------------------------------------------------- 1 | /* A simple program to count pairs with difference k*/ 2 | #include 3 | using namespace std; 4 | 5 | int countPairsWithDiffK(int arr[], int n, int k) 6 | { 7 | int count = 0; 8 | 9 | // Pick all elements one by one 10 | for (int i = 0; i < n; i++) 11 | { 12 | // See if there is a pair of this picked element 13 | for (int j = i+1; j < n; j++) 14 | if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) 15 | count++; 16 | } 17 | return count; 18 | } 19 | 20 | // Driver program to test above function 21 | int main() 22 | { 23 | int arr[] = {1, 5, 3, 4, 2}; 24 | int n = sizeof(arr)/sizeof(arr[0]); 25 | int k = 3; 26 | cout << "Count of pairs with given diff is " 27 | << countPairsWithDiffK(arr, n, k); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /118.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to count all possible paths 2 | // from top left to bottom right 3 | 4 | #include 5 | using namespace std; 6 | 7 | // Returns count of possible paths to reach cell at row 8 | // number m and column number n from the topmost leftmost 9 | // cell (cell at 1, 1) 10 | int numberOfPaths(int m, int n) 11 | { 12 | // If either given row number is first or given column 13 | // number is first 14 | if (m == 1 || n == 1) 15 | return 1; 16 | 17 | // If diagonal movements are allowed then the last 18 | // addition is required. 19 | return numberOfPaths(m - 1, n) + numberOfPaths(m, n - 1); 20 | // + numberOfPaths(m-1, n-1); 21 | } 22 | 23 | int main() 24 | { 25 | cout << numberOfPaths(3, 3); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /119.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to count all possible paths 2 | // from top left to bottom right 3 | #include 4 | using namespace std; 5 | 6 | // Returns count of possible paths to reach cell at 7 | // row number m and column number n from the topmost 8 | // leftmost cell (cell at 1, 1) 9 | int numberOfPaths(int m, int n) 10 | { 11 | // Create a 2D table to store results of subproblems 12 | int count[m][n]; 13 | 14 | // Count of paths to reach any cell in first column is 1 15 | for (int i = 0; i < m; i++) 16 | count[i][0] = 1; 17 | 18 | // Count of paths to reach any cell in first row is 1 19 | for (int j = 0; j < n; j++) 20 | count[0][j] = 1; 21 | 22 | // Calculate count of paths for other cells in 23 | // bottom-up manner using the recursive solution 24 | for (int i = 1; i < m; i++) { 25 | for (int j = 1; j < n; j++) 26 | 27 | // By uncommenting the last part the code calculates the total 28 | // possible paths if the diagonal Movements are allowed 29 | count[i][j] = count[i - 1][j] + count[i][j - 1]; //+ count[i-1][j-1]; 30 | } 31 | return count[m - 1][n - 1]; 32 | } 33 | 34 | // Driver program to test above functions 35 | int main() 36 | { 37 | cout << numberOfPaths(3, 3); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /120.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Returns count of possible paths to reach 6 | // cell at row number m and column number n from 7 | // the topmost leftmost cell (cell at 1, 1) 8 | int numberOfPaths(int m, int n) 9 | { 10 | // Create a 1D array to store results of subproblems 11 | int dp[n] = { 1 }; 12 | dp[0] = 1; 13 | 14 | for (int i = 0; i < m; i++) { 15 | for (int j = 1; j < n; j++) { 16 | dp[j] += dp[j - 1]; 17 | } 18 | } 19 | 20 | return dp[n - 1]; 21 | } 22 | 23 | // Driver code 24 | int main() 25 | { 26 | cout << numberOfPaths(3, 3); 27 | } 28 | 29 | -------------------------------------------------------------------------------- /121.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to count all possible paths from 2 | // top left to top bottom using combinatorics 3 | 4 | #include 5 | using namespace std; 6 | 7 | int numberOfPaths(int m, int n) 8 | { 9 | // We have to calculate m+n-2 C n-1 here 10 | // which will be (m+n-2)! / (n-1)! (m-1)! 11 | int path = 1; 12 | for (int i = n; i < (m + n - 1); i++) { 13 | path *= i; 14 | path /= (i - n + 1); 15 | } 16 | return path; 17 | } 18 | 19 | // Driver code 20 | int main() 21 | { 22 | cout << numberOfPaths(3, 3); 23 | return 0; 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /123.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // The function to rearrange an array 5 | // in-place so that arr[i] becomes arr[arr[i]]. 6 | void rearrange(int arr[], int n) 7 | { 8 | // First step: Increase all values by (arr[arr[i]]%n)*n 9 | for (int i=0; i < n; i++) 10 | arr[i] += (arr[arr[i]]%n)*n; 11 | 12 | // Second Step: Divide all values by n 13 | for (int i=0; i 4 | #define N 4 5 | using namespace std; 6 | 7 | // This function returns 1 if A[][] and B[][] are identical 8 | // otherwise returns 0 9 | int areSame(int A[][N], int B[][N]) 10 | { 11 | int i, j; 12 | for (i = 0; i < N; i++) 13 | for (j = 0; j < N; j++) 14 | if (A[i][j] != B[i][j]) 15 | return 0; 16 | return 1; 17 | } 18 | 19 | int main() 20 | { 21 | int A[N][N] = { {1, 1, 1, 1}, 22 | {2, 2, 2, 2}, 23 | {3, 3, 3, 3}, 24 | {4, 4, 4, 4}}; 25 | 26 | int B[N][N] = { {1, 1, 1, 1}, 27 | {2, 2, 2, 2}, 28 | {3, 3, 3, 3}, 29 | {4, 4, 4, 4}}; 30 | 31 | if (areSame(A, B)) 32 | cout << "Matrices are identical"; 33 | else 34 | cout << "Matrices are not identical"; 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /127.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define N 4 3 | 4 | // This function stores transpose of A[][] in B[][] 5 | void transpose(int A[][N], int B[][N]) 6 | { 7 | int i, j; 8 | for (i = 0; i < N; i++) 9 | for (j = 0; j < N; j++) 10 | B[i][j] = A[j][i]; 11 | } 12 | 13 | int main() 14 | { 15 | int A[N][N] = { {1, 1, 1, 1}, 16 | {2, 2, 2, 2}, 17 | {3, 3, 3, 3}, 18 | {4, 4, 4, 4}}; 19 | 20 | int B[N][N], i, j; 21 | 22 | transpose(A, B); 23 | 24 | printf("Result matrix is \n"); 25 | for (i = 0; i < N; i++) 26 | { 27 | for (j = 0; j < N; j++) 28 | printf("%d ", B[i][j]); 29 | printf("\n"); 30 | } 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /128.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define M 3 3 | #define N 4 4 | 5 | // This function stores transpose of A[][] in B[][] 6 | void transpose(int A[][N], int B[][M]) 7 | { 8 | int i, j; 9 | for (i = 0; i < N; i++) 10 | for (j = 0; j < M; j++) 11 | B[i][j] = A[j][i]; 12 | } 13 | 14 | int main() 15 | { 16 | int A[M][N] = { {1, 1, 1, 1}, 17 | {2, 2, 2, 2}, 18 | {3, 3, 3, 3}}; 19 | 20 | // Note dimensions of B[][] 21 | int B[N][M], i, j; 22 | 23 | transpose(A, B); 24 | 25 | printf("Result matrix is \n"); 26 | for (i = 0; i < N; i++) 27 | { 28 | for (j = 0; j < M; j++) 29 | printf("%d ", B[i][j]); 30 | printf("\n"); 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /129.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define N 4 5 | 6 | // Converts A[][] to its transpose 7 | void transpose(int A[][N]) 8 | { 9 | for (int i = 0; i < N; i++) 10 | for (int j = i+1; j < N; j++) 11 | swap(A[i][j], A[j][i]); 12 | } 13 | 14 | int main() 15 | { 16 | int A[N][N] = { {1, 1, 1, 1}, 17 | {2, 2, 2, 2}, 18 | {3, 3, 3, 3}, 19 | {4, 4, 4, 4}}; 20 | 21 | transpose(A); 22 | 23 | printf("Modified matrix is \n"); 24 | for (int i = 0; i < N; i++) 25 | { 26 | for (int j = 0; j < N; j++) 27 | printf("%d ", A[i][j]); 28 | printf("\n"); 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /13.cpp: -------------------------------------------------------------------------------- 1 | // Iterative C++ program to reverse an array 2 | #include 3 | using namespace std; 4 | 5 | /* Function to reverse arr[] from start to end*/ 6 | void rvereseArray(int arr[], int start, int end) 7 | { 8 | while (start < end) 9 | { 10 | int temp = arr[start]; 11 | arr[start] = arr[end]; 12 | arr[end] = temp; 13 | start++; 14 | end--; 15 | } 16 | } 17 | 18 | /* Utility function to print an array */ 19 | void printArray(int arr[], int size) 20 | { 21 | for (int i = 0; i < size; i++) 22 | cout << arr[i] << " "; 23 | 24 | cout << endl; 25 | } 26 | 27 | /* Driver function to test above functions */ 28 | int main() 29 | { 30 | int arr[] = {1, 2, 3, 4, 5, 6}; 31 | 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | 34 | // To print original array 35 | printArray(arr, n); 36 | 37 | // Function calling 38 | rvereseArray(arr, 0, n-1); 39 | 40 | cout << "Reversed array is" << endl; 41 | 42 | // To print the Reversed array 43 | printArray(arr, n); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /130.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for subtraction of matrices 2 | #include 3 | using namespace std; 4 | #define N 4 5 | 6 | // This function subtracts B[][] from A[][], and stores 7 | // the result in C[][] 8 | void subtract(int A[][N], int B[][N], int C[][N]) 9 | { 10 | int i, j; 11 | for (i = 0; i < N; i++) 12 | for (j = 0; j < N; j++) 13 | C[i][j] = A[i][j] - B[i][j]; 14 | } 15 | 16 | // Driver code 17 | int main() 18 | { 19 | int A[N][N] = { {1, 1, 1, 1}, 20 | {2, 2, 2, 2}, 21 | {3, 3, 3, 3}, 22 | {4, 4, 4, 4}}; 23 | 24 | int B[N][N] = { {1, 1, 1, 1}, 25 | {2, 2, 2, 2}, 26 | {3, 3, 3, 3}, 27 | {4, 4, 4, 4}}; 28 | 29 | int C[N][N]; // To store result 30 | int i, j; 31 | subtract(A, B, C); 32 | 33 | cout << "Result matrix is " << endl; 34 | for (i = 0; i < N; i++) 35 | { 36 | for (j = 0; j < N; j++) 37 | cout << C[i][j] << " "; 38 | cout << endl; 39 | } 40 | 41 | return 0; 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /131.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for addition 2 | // of two matrices 3 | #include 4 | using namespace std; 5 | #define N 4 6 | 7 | // This function adds A[][] and B[][], and stores 8 | // the result in C[][] 9 | void add(int A[][N], int B[][N], int C[][N]) 10 | { 11 | int i, j; 12 | for (i = 0; i < N; i++) 13 | for (j = 0; j < N; j++) 14 | C[i][j] = A[i][j] + B[i][j]; 15 | } 16 | 17 | // Driver code 18 | int main() 19 | { 20 | int A[N][N] = { {1, 1, 1, 1}, 21 | {2, 2, 2, 2}, 22 | {3, 3, 3, 3}, 23 | {4, 4, 4, 4}}; 24 | 25 | int B[N][N] = { {1, 1, 1, 1}, 26 | {2, 2, 2, 2}, 27 | {3, 3, 3, 3}, 28 | {4, 4, 4, 4}}; 29 | 30 | int C[N][N]; // To store result 31 | int i, j; 32 | add(A, B, C); 33 | 34 | cout << "Result matrix is " << endl; 35 | for (i = 0; i < N; i++) 36 | { 37 | for (j = 0; j < N; j++) 38 | cout << C[i][j] << " "; 39 | cout << endl; 40 | } 41 | 42 | return 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /132.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector spiralOrder(vector> &matrix) 5 | { 6 | vector ans; 7 | 8 | if (matrix.size() == 0) 9 | return ans; 10 | 11 | int R = matrix.size(), C = matrix[0].size(); 12 | bool seen[R][C]; 13 | int dr[] = { 0, 1, 0, -1 }; 14 | int dc[] = { 1, 0, -1, 0 }; 15 | int r = 0, c = 0, di = 0; 16 | 17 | // Iterate from 0 to R * C - 1 18 | for (int i = 0; i < R * C; i++) { 19 | ans.push_back(matrix[r]); 20 | seen[r] = true; 21 | int cr = r + dr[di]; 22 | int cc = c + dc[di]; 23 | 24 | if (0 <= cr && cr < R && 0 <= cc && cc < C 25 | && !seen[cr][cc]) 26 | { 27 | r = cr; 28 | c = cc; 29 | } 30 | else 31 | { 32 | di = (di + 1) % 4; 33 | r += dr[di]; 34 | c += dc[di]; 35 | } 36 | } 37 | return ans; 38 | } 39 | 40 | // Driver code 41 | int main() 42 | { 43 | vector> a { { 1, 2, 3, 4 }, 44 | { 5, 6, 7, 8 }, 45 | { 9, 10, 11, 12 }, 46 | { 13, 14, 15, 16 } }; 47 | 48 | for(int x:spiralOrder(a)) 49 | { 50 | cout << x << " "; 51 | } 52 | return 0; 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /134.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector spiralOrder(vector> &matrix) 5 | { 6 | vector ans; 7 | 8 | if (matrix.size() == 0) 9 | return ans; 10 | 11 | int R = matrix.size(), C = matrix[0].size(); 12 | bool seen[R][C]; 13 | int dr[] = { 0, 1, 0, -1 }; 14 | int dc[] = { 1, 0, -1, 0 }; 15 | int r = 0, c = 0, di = 0; 16 | 17 | // Iterate from 0 to R * C - 1 18 | for (int i = 0; i < R * C; i++) { 19 | ans.push_back(matrix[r]); 20 | seen[r] = true; 21 | int cr = r + dr[di]; 22 | int cc = c + dc[di]; 23 | 24 | if (0 <= cr && cr < R && 0 <= cc && cc < C 25 | && !seen[cr][cc]) 26 | { 27 | r = cr; 28 | c = cc; 29 | } 30 | else 31 | { 32 | di = (di + 1) % 4; 33 | r += dr[di]; 34 | c += dc[di]; 35 | } 36 | } 37 | return ans; 38 | } 39 | 40 | // Driver code 41 | int main() 42 | { 43 | vector> a { { 1, 2, 3, 4 }, 44 | { 5, 6, 7, 8 }, 45 | { 9, 10, 11, 12 }, 46 | { 13, 14, 15, 16 } }; 47 | 48 | for(int x:spiralOrder(a)) 49 | { 50 | cout << x << " "; 51 | } 52 | return 0; 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /14.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to rotate an array by 2 | // d elements 3 | #include 4 | using namespace std; 5 | 6 | /*Function to left Rotate arr[] of 7 | size n by 1*/ 8 | void leftRotatebyOne(int arr[], int n) 9 | { 10 | int temp = arr[0], i; 11 | for (i = 0; i < n - 1; i++) 12 | arr[i] = arr[i + 1]; 13 | 14 | arr[n-1] = temp; 15 | } 16 | 17 | /*Function to left rotate arr[] of size n by d*/ 18 | void leftRotate(int arr[], int d, int n) 19 | { 20 | for (int i = 0; i < d; i++) 21 | leftRotatebyOne(arr, n); 22 | } 23 | 24 | /* utility function to print an array */ 25 | void printArray(int arr[], int n) 26 | { 27 | for (int i = 0; i < n; i++) 28 | cout << arr[i] << " "; 29 | } 30 | 31 | /* Driver program to test above functions */ 32 | int main() 33 | { 34 | int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | 37 | // Function calling 38 | leftRotate(arr, 2, n); 39 | printArray(arr, n); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /140.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find celebrity 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Max # of persons in the party 7 | #define N 8 8 | 9 | // Person with 2 is celebrity 10 | bool MATRIX[N][N] = {{0, 0, 1, 0}, 11 | {0, 0, 1, 0}, 12 | {0, 0, 0, 0}, 13 | {0, 0, 1, 0}}; 14 | 15 | bool knows(int a, int b) 16 | { 17 | return MATRIX[a][b]; 18 | } 19 | 20 | // Returns -1 if celebrity 21 | // is not present. If present, 22 | // returns id (value from 0 to n-1). 23 | int findCelebrity(int n) 24 | { 25 | //the graph needs not be constructed 26 | //as the edges can be found by 27 | //using knows function 28 | 29 | //degree array; 30 | int indegree[n]={0},outdegree[n]={0}; 31 | 32 | //query for all edges 33 | for(int i=0; i 2 | void swap(char *str1, char *str2) 3 | { 4 | char *temp = str1; 5 | str1 = str2; 6 | str2 = temp; 7 | } 8 | 9 | int main() 10 | { 11 | char *str1 = "geeks"; 12 | char *str2 = "forgeeks"; 13 | swap(str1, str2); 14 | printf("str1 is %s, str2 is %s", str1, str2); 15 | getchar(); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /142.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* Swaps strings by swapping pointers */ 4 | void swap1(char **str1_ptr, char **str2_ptr) 5 | { 6 | char *temp = *str1_ptr; 7 | *str1_ptr = *str2_ptr; 8 | *str2_ptr = temp; 9 | } 10 | 11 | int main() 12 | { 13 | char *str1 = "geeks"; 14 | char *str2 = "forgeeks"; 15 | swap1(&str1, &str2); 16 | printf("str1 is %s, str2 is %s", str1, str2); 17 | getchar(); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /143.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // A function to check if a string str is palindrome 5 | void isPalindrome(char str[]) 6 | { 7 | // Start from leftmost and rightmost corners of str 8 | int l = 0; 9 | int h = strlen(str) - 1; 10 | 11 | // Keep comparing characters while they are same 12 | while (h > l) 13 | { 14 | if (str[l++] != str[h--]) 15 | { 16 | printf("%s is Not Palindrome", str); 17 | return; 18 | } 19 | } 20 | printf("%s is palindrome", str); 21 | } 22 | 23 | // Driver program to test above function 24 | int main() 25 | { 26 | isPalindrome("abba"); 27 | isPalindrome("abbccbba"); 28 | isPalindrome("geeks"); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /144.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Defining comparator function as per the requirement 6 | static int myCompare(const void* a, const void* b) 7 | { 8 | 9 | // setting up rules for comparison 10 | return strcmp(*(const char**)a, *(const char**)b); 11 | } 12 | 13 | // Function to sort the array 14 | void sort(const char* arr[], int n) 15 | { 16 | // calling qsort function to sort the array 17 | // with the help of Comparator 18 | qsort(arr, n, sizeof(const char*), myCompare); 19 | } 20 | 21 | int main() 22 | { 23 | 24 | // Get the array of names to be sorted 25 | const char* arr[] 26 | = { "geeksforgeeks", "geeksquiz", "clanguage" }; 27 | 28 | int n = sizeof(arr) / sizeof(arr[0]); 29 | int i; 30 | 31 | // Print the given names 32 | printf("Given array is\n"); 33 | for (i = 0; i < n; i++) 34 | printf("%d: %s \n", i, arr[i]); 35 | 36 | // Sort the given names 37 | sort(arr, n); 38 | 39 | // Print the sorted names 40 | printf("\nSorted array is\n"); 41 | for (i = 0; i < n; i++) 42 | printf("%d: %s \n", i, arr[i]); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /145.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to output the maximum occurring character 2 | // in a string 3 | #include 4 | #define ASCII_SIZE 256 5 | using namespace std; 6 | 7 | char getMaxOccuringChar(char* str) 8 | { 9 | // Create array to keep the count of individual 10 | // characters and initialize the array as 0 11 | int count[ASCII_SIZE] = {0}; 12 | 13 | // Construct character count array from the input 14 | // string. 15 | int len = strlen(str); 16 | int max = 0; // Initialize max count 17 | char result; // Initialize result 18 | 19 | // Traversing through the string and maintaining 20 | // the count of each character 21 | for (int i = 0; i < len; i++) { 22 | count[str[i]]++; 23 | if (max < count[str[i]]) { 24 | max = count[str[i]]; 25 | result = str[i]; 26 | } 27 | } 28 | 29 | return result; 30 | } 31 | 32 | // Driver program to test the above function 33 | int main() 34 | { 35 | char str[] = "sample string"; 36 | cout << "Max occurring character is " 37 | << getMaxOccuringChar(str); 38 | } 39 | -------------------------------------------------------------------------------- /146.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to remove duplicate character 2 | // from character array and print in sorted 3 | // order 4 | #include 5 | using namespace std; 6 | 7 | char *removeDuplicate(char str[], int n) 8 | { 9 | // Used as index in the modified string 10 | int index = 0; 11 | 12 | // Traverse through all characters 13 | for (int i=0; i 4 | using namespace std; 5 | # define NO_OF_CHARS 256 6 | 7 | class gfg 8 | { 9 | public : 10 | 11 | /* Fills count array with 12 | frequency of characters */ 13 | void fillCharCounts(char *str, int *count) 14 | { 15 | int i; 16 | for (i = 0; *(str + i); i++) 17 | count[*(str + i)]++; 18 | } 19 | 20 | /* Print duplicates present 21 | in the passed string */ 22 | void printDups(char *str) 23 | { 24 | 25 | // Create an array of size 256 and fill 26 | // count of every character in it 27 | int *count = (int *)calloc(NO_OF_CHARS, 28 | sizeof(int)); 29 | fillCharCounts(str, count); 30 | 31 | // Print characters having count more than 0 32 | int i; 33 | for (i = 0; i < NO_OF_CHARS; i++) 34 | if(count[i] > 1) 35 | printf("%c, count = %d \n", i, count[i]); 36 | 37 | free(count); 38 | } 39 | }; 40 | 41 | /* Driver code*/ 42 | int main() 43 | { 44 | gfg g ; 45 | char str[] = "test string"; 46 | g.printDups(str); 47 | //getchar(); 48 | return 0; 49 | } 50 | 51 | 52 | -------------------------------------------------------------------------------- /148.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to remove duplicates, the order of 2 | // characters is not maintained in this progress 3 | #include 4 | #define NO_OF_CHAR 256 5 | using namespace std; 6 | 7 | int* getcountarray(string str2) 8 | { 9 | int* count = (int*)calloc(sizeof(int), NO_OF_CHAR); 10 | 11 | for (int i = 0; i < str2.size(); i++) 12 | { 13 | count[str2[i]]++; 14 | } 15 | 16 | return count; 17 | } 18 | 19 | /* removeDirtyChars takes two 20 | string as arguments: First 21 | string (str1) is the one from 22 | where function removes dirty 23 | characters. Second string(str2) 24 | is the string which contain 25 | all dirty characters which need 26 | to be removed from first 27 | string */ 28 | string removeDirtyChars(string str1, string str2) 29 | { 30 | // str2 is the string 31 | // which is to be removed 32 | int* count = getcountarray(str2); 33 | string res; 34 | 35 | // ip_idx helps to keep 36 | // track of the first string 37 | int ip_idx = 0; 38 | 39 | while (ip_idx < str1.size()) 40 | { 41 | char temp = str1[ip_idx]; 42 | if (count[temp] == 0) 43 | { 44 | res.push_back(temp); 45 | } 46 | ip_idx++; 47 | } 48 | 49 | return res; 50 | } 51 | 52 | // Driver Code 53 | int main() 54 | { 55 | string str1 = "geeksforgeeks"; 56 | string str2 = "mask"; 57 | 58 | // Function call 59 | cout << removeDirtyChars(str1, str2) << endl; 60 | } 61 | -------------------------------------------------------------------------------- /149.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program to check if two given strings 3 | // are rotations of each other 4 | # include 5 | using namespace std; 6 | 7 | /* Function checks if passed strings (str1 8 | and str2) are rotations of each other */ 9 | bool areRotations(string str1, string str2) 10 | { 11 | /* Check if sizes of two strings are same */ 12 | if (str1.length() != str2.length()) 13 | return false; 14 | 15 | string temp = str1 + str1; 16 | return (temp.find(str2) != string::npos); 17 | } 18 | 19 | /* Driver program to test areRotations */ 20 | int main() 21 | { 22 | string str1 = "AACD", str2 = "ACDA"; 23 | if (areRotations(str1, str2)) 24 | printf("Strings are rotations of each other"); 25 | else 26 | printf("Strings are not rotations of each other"); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /150.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to reverse a string using recursion 2 | #include 3 | using namespace std; 4 | 5 | /* Function to print reverse of the passed string */ 6 | void reverse(string str) 7 | { 8 | if(str.size() == 0) 9 | { 10 | return; 11 | } 12 | reverse(str.substr(1)); 13 | cout << str[0]; 14 | } 15 | 16 | /* Driver program to test above function */ 17 | int main() 18 | { 19 | string a = "Geeks for Geeks"; 20 | reverse(a); 21 | return 0; 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /151.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print all 2 | // permutations with duplicates allowed 3 | #include 4 | using namespace std; 5 | 6 | 7 | // Function to print permutations of string 8 | // This function takes three parameters: 9 | // 1. String 10 | // 2. Starting index of the string 11 | // 3. Ending index of the string. 12 | void permute(string a, int l, int r) 13 | { 14 | // Base case 15 | if (l == r) 16 | cout< 4 | #include 5 | 6 | using namespace std; 7 | 8 | class gfg 9 | { 10 | 11 | // Function to print n equal parts of str 12 | public: 13 | void divideString(char str[], int n) 14 | { 15 | 16 | int str_size = strlen(str); 17 | int i; 18 | int part_size; 19 | 20 | // Check if string can be divided in 21 | // n equal parts 22 | if (str_size % n != 0) 23 | { 24 | cout<<"Invalid Input: String size"; 25 | cout<<" is not divisible by n"; 26 | return; 27 | } 28 | 29 | // Calculate the size of parts to 30 | // find the division points 31 | part_size = str_size / n; 32 | for (i = 0; i< str_size; i++) 33 | { 34 | if (i % part_size == 0) 35 | cout< 4 | #include 5 | #define NO_OF_CHARS 256 6 | 7 | /* Returns an array of size 256 containg count 8 | of characters in the passed char array */ 9 | int* getCharCountArray(char* str) 10 | { 11 | int* count = (int*)calloc(sizeof(int), NO_OF_CHARS); 12 | int i; 13 | for (i = 0; *(str + i); i++) 14 | count[*(str + i)]++; 15 | return count; 16 | } 17 | 18 | /* The function returns index of first 19 | non-repeating character in a string. If all 20 | characters are repeating then returns -1 */ 21 | int firstNonRepeating(char* str) 22 | { 23 | int* count = getCharCountArray(str); 24 | int index = -1, i; 25 | 26 | for (i = 0; *(str + i); i++) { 27 | if (count[*(str + i)] == 1) { 28 | index = i; 29 | break; 30 | } 31 | } 32 | 33 | // To avoid memory leak 34 | free(count); 35 | return index; 36 | } 37 | 38 | /* Driver program to test above function */ 39 | int main() 40 | { 41 | char str[] = "geeksforgeeks"; 42 | int index = firstNonRepeating(str); 43 | if (index == -1) 44 | printf("Either all characters are repeating or " 45 | "string is empty"); 46 | else 47 | printf("First non-repeating character is %c", 48 | str[index]); 49 | getchar(); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /154.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print all strings that contain all 2 | // characters of a word 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | # define NO_OF_CHARS 256 8 | 9 | /* prints list items having all caharacters of word */ 10 | void print(char list[][50], char *word, int list_size) 11 | { 12 | /*Since calloc is used, map[] is initialized as 0 */ 13 | int *map = new int[(sizeof(int)*NO_OF_CHARS)]; 14 | int i, j, count, word_size; 15 | 16 | /*Set the values in map */ 17 | for (i = 0; *(word+i); i++) 18 | map[*(word + i)] = 1; 19 | 20 | /* Get the length of given word */ 21 | word_size = strlen(word); 22 | 23 | /* Check each item of list if has all characters 24 | of word*/ 25 | for (i = 0; i < list_size; i++) 26 | { 27 | for (j = 0, count = 0; *(list[i] + j); j++) 28 | { 29 | if (map[*(list[i] + j)]) 30 | { 31 | count++; 32 | 33 | /* unset the bit so that strings like 34 | sss not printed*/ 35 | map[*(list[i] + j)] = 0; 36 | } 37 | } 38 | if (count == word_size) 39 | cout << list[i] << endl; 40 | 41 | /*Set the values in map for next item*/ 42 | for (j = 0; *(word + j); j++) 43 | map[*(word + j)] = 1; 44 | } 45 | } 46 | 47 | /* Driver code*/ 48 | int main() 49 | { 50 | char str[] = "sun"; 51 | char list[][50] = {"geeksforgeeks", "unsorted", "sunday", 52 | "just", "sss" }; 53 | print(list, str, 5); 54 | return 0; 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /155.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to reverse a string 2 | #include 3 | using namespace std; 4 | 5 | // Function to reverse words*/ 6 | void reverseWords(string s) 7 | { 8 | 9 | // temporary vector to store all words 10 | vector tmp; 11 | string str = ""; 12 | for (int i = 0; i < s.length(); i++) 13 | { 14 | 15 | // Check if we encounter space 16 | // push word(str) to vector 17 | // and make str NULL 18 | if (s[i] == ' ') 19 | { 20 | tmp.push_back(str); 21 | str = ""; 22 | } 23 | 24 | // Else add character to 25 | // str to form current word 26 | else 27 | str += s[i]; 28 | } 29 | 30 | // Last word remaining,add it to vector 31 | tmp.push_back(str); 32 | 33 | // Now print from last to first in vector 34 | int i; 35 | for (i = tmp.size() - 1; i > 0; i--) 36 | cout << tmp[i] << " "; 37 | // Last word remaining,print it 38 | cout << tmp[0] << endl; 39 | } 40 | 41 | // Driver Code 42 | int main() 43 | { 44 | string s = "i like this program very much"; 45 | reverseWords(s); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /156.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to implement run length encoding 2 | #include 3 | using namespace std; 4 | 5 | void printRLE(string str) 6 | { 7 | int n = str.length(); 8 | for (int i = 0; i < n; i++) { 9 | 10 | // Count occurrences of current character 11 | int count = 1; 12 | while (i < n - 1 && str[i] == str[i + 1]) { 13 | count++; 14 | i++; 15 | } 16 | 17 | // Print character and its count 18 | cout << str[i] << count; 19 | } 20 | } 21 | 22 | int main() 23 | { 24 | string str = "wwwwaaadexxxxxxywww"; 25 | printRLE(str); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /158.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Naive Pattern 2 | // Searching algorithm 3 | #include 4 | using namespace std; 5 | 6 | void search(char* pat, char* txt) 7 | { 8 | int M = strlen(pat); 9 | int N = strlen(txt); 10 | 11 | /* A loop to slide pat[] one by one */ 12 | for (int i = 0; i <= N - M; i++) { 13 | int j; 14 | 15 | /* For current index i, check for pattern match */ 16 | for (j = 0; j < M; j++) 17 | if (txt[i + j] != pat[j]) 18 | break; 19 | 20 | if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1] 21 | cout << "Pattern found at index " 22 | << i << endl; 23 | } 24 | } 25 | 26 | // Driver Code 27 | int main() 28 | { 29 | char txt[] = "AABAACAADAABAAABAA"; 30 | char pat[] = "AABA"; 31 | search(pat, txt); 32 | return 0; 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /16.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for reversal algorithm 2 | // of array rotation 3 | #include 4 | using namespace std; 5 | 6 | /*Function to reverse arr[] from index start to end*/ 7 | void reverseArray(int arr[], int start, int end) 8 | { 9 | while (start < end) { 10 | int temp = arr[start]; 11 | arr[start] = arr[end]; 12 | arr[end] = temp; 13 | start++; 14 | end--; 15 | } 16 | } 17 | 18 | /* Function to left rotate arr[] of size n by d */ 19 | void leftRotate(int arr[], int d, int n) 20 | { 21 | if (d == 0) 22 | return; 23 | // in case the rotating factor is 24 | // greater than array length 25 | d = d % n; 26 | 27 | reverseArray(arr, 0, d - 1); 28 | reverseArray(arr, d, n - 1); 29 | reverseArray(arr, 0, n - 1); 30 | } 31 | 32 | // Function to print an array 33 | void printArray(int arr[], int size) 34 | { 35 | for (int i = 0; i < size; i++) 36 | cout << arr[i] << " "; 37 | } 38 | 39 | /* Driver program to test above functions */ 40 | int main() 41 | { 42 | int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; 43 | int n = sizeof(arr) / sizeof(arr[0]); 44 | int d = 2; 45 | 46 | // Function calling 47 | leftRotate(arr, d, n); 48 | printArray(arr, n); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /162.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find the length of the longest substring 2 | // without repeating characters 3 | #include 4 | using namespace std; 5 | 6 | // This functionr eturns true if all characters in str[i..j] 7 | // are distinct, otherwise returns false 8 | bool areDistinct(string str, int i, int j) 9 | { 10 | 11 | // Note : Default values in visited are false 12 | vector visited(26); 13 | 14 | for (int k = i; k <= j; k++) { 15 | if (visited[str[k] - 'a'] == true) 16 | return false; 17 | visited[str[k] - 'a'] = true; 18 | } 19 | return true; 20 | } 21 | 22 | // Returns length of the longest substring 23 | // with all distinct characters. 24 | int longestUniqueSubsttr(string str) 25 | { 26 | int n = str.size(); 27 | int res = 0; // result 28 | for (int i = 0; i < n; i++) 29 | for (int j = i; j < n; j++) 30 | if (areDistinct(str, i, j)) 31 | res = max(res, j - i + 1); 32 | return res; 33 | } 34 | 35 | // Driver code 36 | int main() 37 | { 38 | string str = "geeksforgeeks"; 39 | cout << "The input string is " << str << endl; 40 | int len = longestUniqueSubsttr(str); 41 | cout << "The length of the longest non-repeating " 42 | "character substring is " 43 | << len; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /165.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check if given string is 2 | // an interleaving of the other two strings 3 | #include 4 | using namespace std; 5 | 6 | // Returns true if C is an interleaving of A and B, 7 | // otherwise returns false 8 | bool isInterleaved (char A[], char B[], char C[]) 9 | { 10 | // Iterate through all characters of C. 11 | while (*C != 0) 12 | { 13 | // Match first character of C with first character 14 | // of A. If matches them move A to next 15 | if (*A == *C) 16 | A++; 17 | 18 | // Else Match first character of C with first 19 | // character of B. If matches them move B to next 20 | else if (*B == *C) 21 | B++; 22 | 23 | // If doesn't match with either A or B, then return 24 | // false 25 | else 26 | return false; 27 | 28 | // Move C to next for next iteration 29 | C++; 30 | } 31 | 32 | // If A or B still have some characters, then length of 33 | // C is smaller than sum of lengths of A and B, so 34 | // return false 35 | if (*A || *B) 36 | return false; 37 | 38 | return true; 39 | } 40 | 41 | // Driver program to test above functions 42 | int main() 43 | { 44 | char A[] = "AB"; 45 | char B[] = "CD"; 46 | char C[] = "ACBG"; 47 | if (isInterleaved(A, B, C) == true) 48 | cout << C << " is interleaved of " << A << " and " << B; 49 | else 50 | cout << C << " is not interleaved of " << A << " and " << B; 51 | 52 | return 0; 53 | } 54 | 55 | -------------------------------------------------------------------------------- /166.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check whether two strings are anagrams 2 | // of each other 3 | #include 4 | using namespace std; 5 | 6 | /* function to check whether two strings are anagram of 7 | each other */ 8 | bool areAnagram(string str1, string str2) 9 | { 10 | // Get lengths of both strings 11 | int n1 = str1.length(); 12 | int n2 = str2.length(); 13 | 14 | // If length of both strings is not same, then they 15 | // cannot be anagram 16 | if (n1 != n2) 17 | return false; 18 | 19 | // Sort both the strings 20 | sort(str1.begin(), str1.end()); 21 | sort(str2.begin(), str2.end()); 22 | 23 | // Compare sorted strings 24 | for (int i = 0; i < n1; i++) 25 | if (str1[i] != str2[i]) 26 | return false; 27 | 28 | return true; 29 | } 30 | 31 | // Driver code 32 | int main() 33 | { 34 | string str1 = "test"; 35 | string str2 = "ttew"; 36 | 37 | // Function Call 38 | if (areAnagram(str1, str2)) 39 | cout << "The two strings are anagram of each other"; 40 | else 41 | cout << "The two strings are not anagram of each " 42 | "other"; 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /168.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define NO_OF_CHARS 256 4 | 5 | /* This function builds the TF table 6 | which represents Finite Automata for a 7 | given pattern */ 8 | void computeTransFun(char* pat, int M, int TF[][NO_OF_CHARS]) 9 | { 10 | int i, lps = 0, x; 11 | 12 | // Fill entries in first row 13 | for (x = 0; x < NO_OF_CHARS; x++) 14 | TF[0][x] = 0; 15 | TF[0][pat[0]] = 1; 16 | 17 | // Fill entries in other rows 18 | for (i = 1; i <= M; i++) { 19 | // Copy values from row at index lps 20 | for (x = 0; x < NO_OF_CHARS; x++) 21 | TF[i][x] = TF[lps][x]; 22 | 23 | // Update the entry corresponding to this character 24 | TF[i][pat[i]] = i + 1; 25 | 26 | // Update lps for next row to be filled 27 | if (i < M) 28 | lps = TF[lps][pat[i]]; 29 | } 30 | } 31 | 32 | /* Prints all occurrences of pat in txt */ 33 | void search(char pat[], char txt[]) 34 | { 35 | int M = strlen(pat); 36 | int N = strlen(txt); 37 | 38 | int TF[M + 1][NO_OF_CHARS]; 39 | 40 | computeTransFun(pat, M, TF); 41 | 42 | // process text over FA. 43 | int i, j = 0; 44 | for (i = 0; i < N; i++) { 45 | j = TF[j][txt[i]]; 46 | if (j == M) { 47 | cout << "pattern found at index " << i - M + 1 << endl; 48 | } 49 | } 50 | } 51 | 52 | /* Driver code */ 53 | int main() 54 | { 55 | char txt[] = "GEEKS FOR GEEKS"; 56 | char pat[] = "GEEKS"; 57 | search(pat, txt); 58 | return 0; 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /17.cpp: -------------------------------------------------------------------------------- 1 | //c++ program for the above approach 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | /*Function to return max sum such that no two elements 8 | are adjacent */ 9 | int FindMaxSum(vector arr, int n) 10 | { 11 | int incl = arr[0]; 12 | int excl = 0; 13 | int excl_new; 14 | int i; 15 | 16 | for (i = 1; i < n; i++) 17 | { 18 | /* current max excluding i */ 19 | excl_new = (incl > excl) ? incl : excl; 20 | 21 | /* current max including i */ 22 | incl = excl + arr[i]; 23 | excl = excl_new; 24 | } 25 | 26 | /* return max of incl and excl */ 27 | return ((incl > excl) ? incl : excl); 28 | } 29 | 30 | // Driver program to test above functions 31 | int main() 32 | { 33 | vector arr = {5, 5, 10, 100, 10, 5}; 34 | cout< 4 | using namespace std; 5 | 6 | bool isPalindrome(string String, int i, int j) 7 | { 8 | while(i < j) 9 | { 10 | if(String[i] != String[j]) 11 | return false; 12 | i++; 13 | j--; 14 | } 15 | return true; 16 | } 17 | int minPalPartion(string String, int i, int j) 18 | { 19 | if( i >= j || isPalindrome(String, i, j) ) 20 | return 0; 21 | int ans = INT_MAX, count; 22 | for(int k = i; k < j; k++) 23 | { 24 | count = minPalPartion(String, i, k) + 25 | minPalPartion(String, k + 1, j) + 1; 26 | 27 | ans = min(ans, count); 28 | } 29 | return ans; 30 | } 31 | 32 | // Driver code 33 | int main() { 34 | string str = "ababbbabbababa"; 35 | cout << "Min cuts needed for " << 36 | "Palindrome Partitioning is " << 37 | minPalPartion(str, 0, str.length() - 1) << endl; 38 | return 0; 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /171.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find lexicographic rank 2 | // of a string 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | // A utility function to find factorial of n 8 | int fact(int n) 9 | { 10 | return (n <= 1) ? 1 : n * fact(n - 1); 11 | } 12 | 13 | // A utility function to count smaller characters on right 14 | // of arr[low] 15 | int findSmallerInRight(char* str, int low, int high) 16 | { 17 | int countRight = 0, i; 18 | 19 | for (i = low + 1; i <= high; ++i) 20 | if (str[i] < str[low]) 21 | ++countRight; 22 | 23 | return countRight; 24 | } 25 | 26 | // A function to find rank of a string in all permutations 27 | // of characters 28 | int findRank(char* str) 29 | { 30 | int len = strlen(str); 31 | int mul = fact(len); 32 | int rank = 1; 33 | int countRight; 34 | 35 | int i; 36 | for (i = 0; i < len; ++i) { 37 | mul /= len - i; 38 | 39 | // count number of chars smaller than str[i] 40 | // from str[i+1] to str[len-1] 41 | countRight = findSmallerInRight(str, i, len - 1); 42 | 43 | rank += countRight * mul; 44 | } 45 | 46 | return rank; 47 | } 48 | 49 | // Driver program to test above function 50 | int main() 51 | { 52 | char str[] = "string"; 53 | cout << findRank(str); 54 | return 0; 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /173.cpp: -------------------------------------------------------------------------------- 1 | // A C++ solution for longest palindrome 2 | #include 3 | using namespace std; 4 | 5 | // Function to print a substring str[low..high] 6 | void printSubStr(string str, int low, int high) 7 | { 8 | for (int i = low; i <= high; ++i) 9 | cout << str[i]; 10 | } 11 | 12 | // This function prints the 13 | // longest palindrome substring 14 | // It also returns the length 15 | // of the longest palindrome 16 | int longestPalSubstr(string str) 17 | { 18 | // get length of input string 19 | int n = str.size(); 20 | 21 | // All substrings of length 1 22 | // are palindromes 23 | int maxLength = 1, start = 0; 24 | 25 | // Nested loop to mark start and end index 26 | for (int i = 0; i < str.length(); i++) { 27 | for (int j = i; j < str.length(); j++) { 28 | int flag = 1; 29 | 30 | // Check palindrome 31 | for (int k = 0; k < (j - i + 1) / 2; k++) 32 | if (str[i + k] != str[j - k]) 33 | flag = 0; 34 | 35 | // Palindrome 36 | if (flag && (j - i + 1) > maxLength) { 37 | start = i; 38 | maxLength = j - i + 1; 39 | } 40 | } 41 | } 42 | 43 | cout << "Longest palindrome substring is: "; 44 | printSubStr(str, start, start + maxLength - 1); 45 | 46 | // return length of LPS 47 | return maxLength; 48 | } 49 | 50 | // Driver Code 51 | int main() 52 | { 53 | string str = "forgeeksskeegfor"; 54 | cout << "\nLength is: " 55 | << longestPalSubstr(str); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /178.cpp: -------------------------------------------------------------------------------- 1 | /* C++ program to count no of words 2 | from given input string. */ 3 | #include 4 | using namespace std; 5 | 6 | #define OUT 0 7 | #define IN 1 8 | 9 | // returns number of words in str 10 | unsigned countWords(char *str) 11 | { 12 | int state = OUT; 13 | unsigned wc = 0; // word count 14 | 15 | // Scan all characters one by one 16 | while (*str) 17 | { 18 | // If next character is a separator, set the 19 | // state as OUT 20 | if (*str == ' ' || *str == '\n' || *str == '\t') 21 | state = OUT; 22 | 23 | // If next character is not a word separator and 24 | // state is OUT, then set the state as IN and 25 | // increment word count 26 | else if (state == OUT) 27 | { 28 | state = IN; 29 | ++wc; 30 | } 31 | 32 | // Move to next character 33 | ++str; 34 | } 35 | 36 | return wc; 37 | } 38 | 39 | // Driver code 40 | int main(void) 41 | { 42 | char str[] = "One two three\n four\tfive "; 43 | cout<<"No of words : "< 2 | using namespace std; 3 | 4 | /*C++ Function to print leaders in an array */ 5 | void printLeaders(int arr[], int size) 6 | { 7 | for (int i = 0; i < size; i++) 8 | { 9 | int j; 10 | for (j = i+1; j < size; j++) 11 | { 12 | if (arr[i] <=arr[j]) 13 | break; 14 | } 15 | if (j == size) // the loop didn't break 16 | cout << arr[i] << " "; 17 | } 18 | } 19 | 20 | /* Driver program to test above function */ 21 | int main() 22 | { 23 | int arr[] = {16, 17, 4, 3, 5, 2}; 24 | int n = sizeof(arr)/sizeof(arr[0]); 25 | printLeaders(arr, n); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /180.cpp: -------------------------------------------------------------------------------- 1 | // A simple C++ program for 2 | // implementation of atoi 3 | #include 4 | using namespace std; 5 | 6 | // A simple atoi() function 7 | int myAtoi(char* str) 8 | { 9 | // Initialize result 10 | int res = 0; 11 | 12 | // Iterate through all characters 13 | // of input string and update result 14 | // take ASCII character of corosponding digit and 15 | // subtract the code from '0' to get numerical 16 | // value and multiply res by 10 to shuffle 17 | // digits left to update running total 18 | for (int i = 0; str[i] != '\0'; ++i) 19 | res = res * 10 + str[i] - '0'; 20 | 21 | // return result. 22 | return res; 23 | } 24 | 25 | // Driver code 26 | int main() 27 | { 28 | char str[] = "89789"; 29 | 30 | // Function call 31 | int val = myAtoi(str); 32 | cout << val; 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /181.cpp: -------------------------------------------------------------------------------- 1 | /* Dynamic Programming solution to 2 | find length of the 3 | longest common substring */ 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | /* Returns length of longest 9 | common substring of X[0..m-1] 10 | and Y[0..n-1] */ 11 | int LCSubStr(char* X, char* Y, int m, int n) 12 | { 13 | // Create a table to store 14 | // lengths of longest 15 | // common suffixes of substrings. 16 | // Note that LCSuff[i][j] contains 17 | // length of longest common suffix 18 | // of X[0..i-1] and Y[0..j-1]. 19 | 20 | int LCSuff[m + 1][n + 1]; 21 | int result = 0; // To store length of the 22 | // longest common substring 23 | 24 | /* Following steps build LCSuff[m+1][n+1] in 25 | bottom up fashion. */ 26 | for (int i = 0; i <= m; i++) 27 | { 28 | for (int j = 0; j <= n; j++) 29 | { 30 | // The first row and first column 31 | // entries have no logical meaning, 32 | // they are used only for simplicity 33 | // of program 34 | if (i == 0 || j == 0) 35 | LCSuff[i][j] = 0; 36 | 37 | else if (X[i - 1] == Y[j - 1]) { 38 | LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1; 39 | result = max(result, LCSuff[i][j]); 40 | } 41 | else 42 | LCSuff[i][j] = 0; 43 | } 44 | } 45 | return result; 46 | } 47 | 48 | // Driver code 49 | int main() 50 | { 51 | char X[] = "OldSite:GeeksforGeeks.org"; 52 | char Y[] = "NewSite:GeeksQuiz.com"; 53 | 54 | int m = strlen(X); 55 | int n = strlen(Y); 56 | 57 | cout << "Length of Longest Common Substring is " 58 | << LCSubStr(X, Y, m, n); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /187.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define NO_OF_CHARS 256 4 | 5 | // CPP function to find the 6 | // second most frequent character 7 | // in a given string 'str' 8 | char getSecondMostFreq(string str) 9 | { 10 | // count number of occurrences of every character. 11 | int count[NO_OF_CHARS] = {0}, i; 12 | for (i = 0; str[i]; i++) 13 | (count[str[i]])++; 14 | 15 | // Traverse through the count[] and 16 | // find second highest element. 17 | int first = 0, second = 0; 18 | for (i = 0; i < NO_OF_CHARS; i++) 19 | { 20 | /* If current element is smaller 21 | than first then update both 22 | first and second */ 23 | if (count[i] > count[first]) 24 | { 25 | second = first; 26 | first = i; 27 | } 28 | 29 | /* If count[i] is in between first 30 | and second then update second */ 31 | else if (count[i] > count[second] && 32 | count[i] != count[first]) 33 | second = i; 34 | } 35 | 36 | return second; 37 | } 38 | 39 | // Driver code 40 | int main() 41 | { 42 | string str = "geeksforgeeks"; 43 | char res = getSecondMostFreq(str); 44 | if (res != '\0') 45 | cout << "Second most frequent char is " << res; 46 | else 47 | cout << "No second most frequent character"; 48 | return 0; 49 | } 50 | 51 | -------------------------------------------------------------------------------- /189.cpp: -------------------------------------------------------------------------------- 1 | // Given a reference (pointer to pointer) to the head 2 | // of a list and an int, appends a new node at the end 3 | void append(Node** head_ref, int new_data) 4 | { 5 | 6 | // 1. allocate node 7 | Node* new_node = new Node(); 8 | 9 | // Used in step 5 10 | Node *last = *head_ref; 11 | 12 | // 2. Put in the data 13 | new_node->data = new_data; 14 | 15 | // 3. This new node is going to be 16 | // the last node, so make next of 17 | // it as NULL 18 | new_node->next = NULL; 19 | 20 | // 4. If the Linked List is empty, 21 | // then make the new node as head 22 | if (*head_ref == NULL) 23 | { 24 | *head_ref = new_node; 25 | return; 26 | } 27 | 28 | // 5. Else traverse till the last node 29 | while (last->next != NULL) 30 | last = last->next; 31 | 32 | // 6. Change the next of last node 33 | last->next = new_node; 34 | return; 35 | } 36 | -------------------------------------------------------------------------------- /194.cpp: -------------------------------------------------------------------------------- 1 | // Simple C++ program to find n'th node from end 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | struct Node { 7 | int data; 8 | struct Node* next; 9 | }; 10 | 11 | /* Function to get the nth node from the last of a linked list*/ 12 | void printNthFromLast(struct Node* head, int n) 13 | { 14 | int len = 0, i; 15 | struct Node* temp = head; 16 | 17 | // count the number of nodes in Linked List 18 | while (temp != NULL) { 19 | temp = temp->next; 20 | len++; 21 | } 22 | 23 | // check if value of n is not 24 | // more than length of the linked list 25 | if (len < n) 26 | return; 27 | 28 | temp = head; 29 | 30 | // get the (len-n+1)th node from the beginning 31 | for (i = 1; i < len - n + 1; i++) 32 | temp = temp->next; 33 | 34 | cout << temp->data; 35 | 36 | return; 37 | } 38 | 39 | void push(struct Node** head_ref, int new_data) 40 | { 41 | /* allocate node */ 42 | struct Node* new_node = new Node(); 43 | 44 | /* put in the data */ 45 | new_node->data = new_data; 46 | 47 | /* link the old list off the new node */ 48 | new_node->next = (*head_ref); 49 | 50 | /* move the head to point to the new node */ 51 | (*head_ref) = new_node; 52 | } 53 | 54 | // Driver Code 55 | int main() 56 | { 57 | /* Start with the empty list */ 58 | struct Node* head = NULL; 59 | 60 | // create linked 35->15->4->20 61 | push(&head, 20); 62 | push(&head, 4); 63 | push(&head, 15); 64 | push(&head, 35); 65 | 66 | printNthFromLast(head, 4); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /198.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print reverse of a linked list 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node* next; 11 | }; 12 | 13 | /* Function to reverse the linked list */ 14 | void printReverse(Node* head) 15 | { 16 | // Base case 17 | if (head == NULL) 18 | return; 19 | 20 | // print the list after head node 21 | printReverse(head->next); 22 | 23 | // After everything else is printed, print head 24 | cout << head->data << " "; 25 | } 26 | 27 | /*UTILITY FUNCTIONS*/ 28 | /* Push a node to linked list. Note that this function 29 | changes the head */ 30 | void push(Node** head_ref, char new_data) 31 | { 32 | /* allocate node */ 33 | Node* new_node = new Node(); 34 | 35 | /* put in the data */ 36 | new_node->data = new_data; 37 | 38 | /* link the old list off the new node */ 39 | new_node->next = (*head_ref); 40 | 41 | /* move the head to pochar to the new node */ 42 | (*head_ref) = new_node; 43 | } 44 | 45 | /* Driver code*/ 46 | int main() 47 | { 48 | // Let us create linked list 1->2->3->4 49 | Node* head = NULL; 50 | push(&head, 4); 51 | push(&head, 3); 52 | push(&head, 2); 53 | push(&head, 1); 54 | 55 | printReverse(head); 56 | return 0; 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /2.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find maximum 2 | // in arr[] of size n 3 | #include 4 | using namespace std; 5 | 6 | int largest(int arr[], int n) 7 | { 8 | int i; 9 | 10 | // Initialize maximum element 11 | int max = arr[0]; 12 | 13 | // Traverse array elements 14 | // from second and compare 15 | // every element with current max 16 | for (i = 1; i < n; i++) 17 | if (arr[i] > max) 18 | max = arr[i]; 19 | 20 | return max; 21 | } 22 | 23 | // Driver Code 24 | int main() 25 | { 26 | int arr[] = {10, 324, 45, 90, 9808}; 27 | int n = sizeof(arr) / sizeof(arr[0]); 28 | cout << "Largest in given array is " 29 | << largest(arr, n); 30 | return 0; 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /20.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Count Inversions 2 | // in an array 3 | #include 4 | using namespace std; 5 | 6 | int getInvCount(int arr[], int n) 7 | { 8 | int inv_count = 0; 9 | for (int i = 0; i < n - 1; i++) 10 | for (int j = i + 1; j < n; j++) 11 | if (arr[i] > arr[j]) 12 | inv_count++; 13 | 14 | return inv_count; 15 | } 16 | 17 | // Driver Code 18 | int main() 19 | { 20 | int arr[] = { 1, 20, 6, 4, 5 }; 21 | int n = sizeof(arr) / sizeof(arr[0]); 22 | cout << " Number of inversions are " 23 | << getInvCount(arr, n); 24 | return 0; 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /21.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to find Two elements 2 | // whose sum is closest to zero 3 | # include 4 | # include /* for abs() */ 5 | # include 6 | 7 | using namespace std; 8 | void minAbsSumPair(int arr[], int arr_size) 9 | { 10 | int inv_count = 0; 11 | int l, r, min_sum, sum, min_l, min_r; 12 | 13 | /* Array should have at least 14 | two elements*/ 15 | if(arr_size < 2) 16 | { 17 | cout << "Invalid Input"; 18 | return; 19 | } 20 | 21 | /* Initialization of values */ 22 | min_l = 0; 23 | min_r = 1; 24 | min_sum = arr[0] + arr[1]; 25 | 26 | for(l = 0; l < arr_size - 1; l++) 27 | { 28 | for(r = l + 1; r < arr_size; r++) 29 | { 30 | sum = arr[l] + arr[r]; 31 | if(abs(min_sum) > abs(sum)) 32 | { 33 | min_sum = sum; 34 | min_l = l; 35 | min_r = r; 36 | } 37 | } 38 | } 39 | 40 | cout << "The two elements whose sum is minimum are " 41 | << arr[min_l] << " and " << arr[min_r]; 42 | } 43 | 44 | // Driver Code 45 | int main() 46 | { 47 | int arr[] = {1, 60, -10, 70, -80, 85}; 48 | minAbsSumPair(arr, 6); 49 | return 0; 50 | } 51 | 52 | 53 | -------------------------------------------------------------------------------- /22.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find smallest and 2 | // second smallest elements 3 | #include 4 | using namespace std; /* For INT_MAX */ 5 | 6 | void print2Smallest(int arr[], int arr_size) 7 | { 8 | int i, first, second; 9 | 10 | /* There should be atleast two elements */ 11 | if (arr_size < 2) 12 | { 13 | cout<<" Invalid Input "; 14 | return; 15 | } 16 | 17 | first = second = INT_MAX; 18 | for (i = 0; i < arr_size ; i ++) 19 | { 20 | /* If current element is smaller than first 21 | then update both first and second */ 22 | if (arr[i] < first) 23 | { 24 | second = first; 25 | first = arr[i]; 26 | } 27 | 28 | /* If arr[i] is in between first and second 29 | then update second */ 30 | else if (arr[i] < second && arr[i] != first) 31 | second = arr[i]; 32 | } 33 | if (second == INT_MAX) 34 | cout << "There is no second smallest element\n"; 35 | else 36 | cout << "The smallest element is " << first << " and second " 37 | "Smallest element is " << second << endl; 38 | } 39 | 40 | /* Driver code */ 41 | int main() 42 | { 43 | int arr[] = {12, 13, 1, 10, 34, 1}; 44 | int n = sizeof(arr)/sizeof(arr[0]); 45 | print2Smallest(arr, n); 46 | return 0; 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /23.cpp: -------------------------------------------------------------------------------- 1 | /* C++ Program to check for majority element in a sorted array */ 2 | #include 3 | using namespace std; 4 | 5 | bool isMajority(int arr[], int n, int x) 6 | { 7 | int i; 8 | 9 | /* get last index according to n (even or odd) */ 10 | int last_index = n % 2 ? (n / 2 + 1): (n / 2); 11 | 12 | /* search for first occurrence of x in arr[]*/ 13 | for (i = 0; i < last_index; i++) 14 | { 15 | 16 | /* check if x is present and is present more than n/2 17 | times */ 18 | if (arr[i] == x && arr[i + n / 2] == x) 19 | return 1; 20 | } 21 | return 0; 22 | } 23 | 24 | /* Driver code */ 25 | int main() 26 | { 27 | int arr[] ={1, 2, 3, 4, 4, 4, 4}; 28 | int n = sizeof(arr)/sizeof(arr[0]); 29 | int x = 4; 30 | if (isMajority(arr, n, x)) 31 | cout << x <<" appears more than "<< 32 | n/2 << " times in arr[]"<< endl; 33 | else 34 | cout < Array to be sorted, l --> Starting index, h --> Ending index */ 25 | void quickSort(int A[], int l, int h) 26 | { 27 | if (l < h) 28 | { 29 | int p = partition(A, l, h); /* Partitioning index */ 30 | quickSort(A, l, p - 1); 31 | quickSort(A, p + 1, h); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /238.cpp: -------------------------------------------------------------------------------- 1 | /* C++ program to implement basic stack 2 | operations */ 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define MAX 1000 8 | 9 | class Stack { 10 | int top; 11 | 12 | public: 13 | int a[MAX]; // Maximum size of Stack 14 | 15 | Stack() { top = -1; } 16 | bool push(int x); 17 | int pop(); 18 | int peek(); 19 | bool isEmpty(); 20 | }; 21 | 22 | bool Stack::push(int x) 23 | { 24 | if (top >= (MAX - 1)) { 25 | cout << "Stack Overflow"; 26 | return false; 27 | } 28 | else { 29 | a[++top] = x; 30 | cout << x << " pushed into stack\n"; 31 | return true; 32 | } 33 | } 34 | 35 | int Stack::pop() 36 | { 37 | if (top < 0) { 38 | cout << "Stack Underflow"; 39 | return 0; 40 | } 41 | else { 42 | int x = a[top--]; 43 | return x; 44 | } 45 | } 46 | int Stack::peek() 47 | { 48 | if (top < 0) { 49 | cout << "Stack is Empty"; 50 | return 0; 51 | } 52 | else { 53 | int x = a[top]; 54 | return x; 55 | } 56 | } 57 | 58 | bool Stack::isEmpty() 59 | { 60 | return (top < 0); 61 | } 62 | 63 | // Driver program to test above functions 64 | int main() 65 | { 66 | class Stack s; 67 | s.push(10); 68 | s.push(20); 69 | s.push(30); 70 | cout << s.pop() << " Popped from stack\n"; 71 | //print all elements in stack : 72 | cout<<"Elements present in stack : "; 73 | while(!s.isEmpty()) 74 | { 75 | // print top element in stack 76 | cout< 3 | using namespace std; 4 | 5 | // Pair struct is used to return 6 | // two values from getMinMax() 7 | struct Pair 8 | { 9 | int min; 10 | int max; 11 | }; 12 | 13 | struct Pair getMinMax(int arr[], int n) 14 | { 15 | struct Pair minmax; 16 | int i; 17 | 18 | // If there is only one element 19 | // then return it as min and max both 20 | if (n == 1) 21 | { 22 | minmax.max = arr[0]; 23 | minmax.min = arr[0]; 24 | return minmax; 25 | } 26 | 27 | // If there are more than one elements, 28 | // then initialize min and max 29 | if (arr[0] > arr[1]) 30 | { 31 | minmax.max = arr[0]; 32 | minmax.min = arr[1]; 33 | } 34 | else 35 | { 36 | minmax.max = arr[1]; 37 | minmax.min = arr[0]; 38 | } 39 | 40 | for(i = 2; i < n; i++) 41 | { 42 | if (arr[i] > minmax.max) 43 | minmax.max = arr[i]; 44 | 45 | else if (arr[i] < minmax.min) 46 | minmax.min = arr[i]; 47 | } 48 | return minmax; 49 | } 50 | 51 | // Driver code 52 | int main() 53 | { 54 | int arr[] = { 1000, 11, 445, 55 | 1, 330, 3000 }; 56 | int arr_size = 6; 57 | 58 | struct Pair minmax = getMinMax(arr, arr_size); 59 | 60 | cout << "Minimum element is " 61 | << minmax.min << endl; 62 | cout << "Maximum element is " 63 | << minmax.max; 64 | 65 | return 0; 66 | } 67 | 68 | 69 | -------------------------------------------------------------------------------- /242.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to check for balanced brackets. 2 | #include 3 | using namespace std; 4 | 5 | // function to check if brackets are balanced 6 | bool areBracketsBalanced(string expr) 7 | { 8 | stack s; 9 | char x; 10 | 11 | // Traversing the Expression 12 | for (int i = 0; i < expr.length(); i++) 13 | { 14 | if (expr[i] == '(' || expr[i] == '[' 15 | || expr[i] == '{') 16 | { 17 | // Push the element in the stack 18 | s.push(expr[i]); 19 | continue; 20 | } 21 | 22 | // IF current current character is not opening 23 | // bracket, then it must be closing. So stack 24 | // cannot be empty at this point. 25 | if (s.empty()) 26 | return false; 27 | 28 | switch (expr[i]) { 29 | case ')': 30 | 31 | // Store the top element in a 32 | x = s.top(); 33 | s.pop(); 34 | if (x == '{' || x == '[') 35 | return false; 36 | break; 37 | 38 | case '}': 39 | 40 | // Store the top element in b 41 | x = s.top(); 42 | s.pop(); 43 | if (x == '(' || x == '[') 44 | return false; 45 | break; 46 | 47 | case ']': 48 | 49 | // Store the top element in c 50 | x = s.top(); 51 | s.pop(); 52 | if (x == '(' || x == '{') 53 | return false; 54 | break; 55 | } 56 | } 57 | 58 | // Check Empty Stack 59 | return (s.empty()); 60 | } 61 | 62 | // Driver code 63 | int main() 64 | { 65 | string expr = "{()}[]"; 66 | 67 | // Function call 68 | if (areBracketsBalanced(expr)) 69 | cout << "Balanced"; 70 | else 71 | cout << "Not Balanced"; 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /244.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for brute force method 2 | // to calculate stock span values 3 | #include 4 | using namespace std; 5 | 6 | // Fills array S[] with span values 7 | void calculateSpan(int price[], int n, int S[]) 8 | { 9 | // Span value of first day is always 1 10 | S[0] = 1; 11 | 12 | // Calculate span value of remaining days 13 | // by linearly checking previous days 14 | for (int i = 1; i < n; i++) 15 | { 16 | S[i] = 1; // Initialize span value 17 | 18 | // Traverse left while the next element 19 | // on left is smaller than price[i] 20 | for (int j = i - 1; (j >= 0) && 21 | (price[i] >= price[j]); j--) 22 | S[i]++; 23 | } 24 | } 25 | 26 | // A utility function to print elements of array 27 | void printArray(int arr[], int n) 28 | { 29 | for (int i = 0; i < n; i++) 30 | cout << arr[i] << " "; 31 | } 32 | 33 | // Driver code 34 | int main() 35 | { 36 | int price[] = { 10, 4, 5, 90, 120, 80 }; 37 | int n = sizeof(price) / sizeof(price[0]); 38 | int S[n]; 39 | 40 | // Fill the span values in array S[] 41 | calculateSpan(price, n, S); 42 | 43 | // print the calculated span values 44 | printArray(S, n); 45 | 46 | return 0; 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /246.cpp: -------------------------------------------------------------------------------- 1 | /* Program to implement a stack using 2 | two queue */ 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Stack { 8 | // Two inbuilt queues 9 | queue q1, q2; 10 | 11 | // To maintain current number of 12 | // elements 13 | int curr_size; 14 | 15 | public: 16 | Stack() 17 | { 18 | curr_size = 0; 19 | } 20 | 21 | void push(int x) 22 | { 23 | curr_size++; 24 | 25 | // Push x first in empty q2 26 | q2.push(x); 27 | 28 | // Push all the remaining 29 | // elements in q1 to q2. 30 | while (!q1.empty()) { 31 | q2.push(q1.front()); 32 | q1.pop(); 33 | } 34 | 35 | // swap the names of two queues 36 | queue q = q1; 37 | q1 = q2; 38 | q2 = q; 39 | } 40 | 41 | void pop() 42 | { 43 | 44 | // if no elements are there in q1 45 | if (q1.empty()) 46 | return; 47 | q1.pop(); 48 | curr_size--; 49 | } 50 | 51 | int top() 52 | { 53 | if (q1.empty()) 54 | return -1; 55 | return q1.front(); 56 | } 57 | 58 | int size() 59 | { 60 | return curr_size; 61 | } 62 | }; 63 | 64 | // Driver code 65 | int main() 66 | { 67 | Stack s; 68 | s.push(1); 69 | s.push(2); 70 | s.push(3); 71 | 72 | cout << "current size: " << s.size() 73 | << endl; 74 | cout << s.top() << endl; 75 | s.pop(); 76 | cout << s.top() << endl; 77 | s.pop(); 78 | cout << s.top() << endl; 79 | 80 | cout << "current size: " << s.size() 81 | << endl; 82 | return 0; 83 | } 84 | 85 | -------------------------------------------------------------------------------- /249.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct QNode { 5 | int data; 6 | QNode* next; 7 | QNode(int d) 8 | { 9 | data = d; 10 | next = NULL; 11 | } 12 | }; 13 | 14 | struct Queue { 15 | QNode *front, *rear; 16 | Queue() 17 | { 18 | front = rear = NULL; 19 | } 20 | 21 | void enQueue(int x) 22 | { 23 | 24 | // Create a new LL node 25 | QNode* temp = new QNode(x); 26 | 27 | // If queue is empty, then 28 | // new node is front and rear both 29 | if (rear == NULL) { 30 | front = rear = temp; 31 | return; 32 | } 33 | 34 | // Add the new node at 35 | // the end of queue and change rear 36 | rear->next = temp; 37 | rear = temp; 38 | } 39 | 40 | // Function to remove 41 | // a key from given queue q 42 | void deQueue() 43 | { 44 | // If queue is empty, return NULL. 45 | if (front == NULL) 46 | return; 47 | 48 | // Store previous front and 49 | // move front one node ahead 50 | QNode* temp = front; 51 | front = front->next; 52 | 53 | // If front becomes NULL, then 54 | // change rear also as NULL 55 | if (front == NULL) 56 | rear = NULL; 57 | 58 | delete (temp); 59 | } 60 | }; 61 | 62 | // Driven Program 63 | int main() 64 | { 65 | 66 | Queue q; 67 | q.enQueue(10); 68 | q.enQueue(20); 69 | q.deQueue(); 70 | q.deQueue(); 71 | q.enQueue(30); 72 | q.enQueue(40); 73 | q.enQueue(50); 74 | q.deQueue(); 75 | cout << "Queue Front : " << (q.front)->data << endl; 76 | cout << "Queue Rear : " << (q.rear)->data; 77 | } 78 | 79 | -------------------------------------------------------------------------------- /25.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to Segregate 0s and 1s in an array 2 | #include 3 | using namespace std; 4 | 5 | // Function to segregate 0s and 1s 6 | void segregate0and1(int arr[], int n) 7 | { 8 | int count = 0; // Counts the no of zeros in arr 9 | 10 | for (int i = 0; i < n; i++) { 11 | if (arr[i] == 0) 12 | count++; 13 | } 14 | 15 | // Loop fills the arr with 0 until count 16 | for (int i = 0; i < count; i++) 17 | arr[i] = 0; 18 | 19 | // Loop fills remaining arr space with 1 20 | for (int i = count; i < n; i++) 21 | arr[i] = 1; 22 | } 23 | 24 | // Function to print segregated array 25 | void print(int arr[], int n) 26 | { 27 | cout << "Array after segregation is "; 28 | 29 | for (int i = 0; i < n; i++) 30 | cout << arr[i] << " "; 31 | } 32 | 33 | // Driver function 34 | int main() 35 | { 36 | int arr[] = { 0, 1, 0, 1, 1, 1 }; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | 39 | segregate0and1(arr, n); 40 | print(arr, n); 41 | 42 | return 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /250.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to implement Queue using 2 | // two stacks with costly enQueue() 3 | #include 4 | using namespace std; 5 | 6 | struct Queue { 7 | stack s1, s2; 8 | 9 | void enQueue(int x) 10 | { 11 | // Move all elements from s1 to s2 12 | while (!s1.empty()) { 13 | s2.push(s1.top()); 14 | s1.pop(); 15 | } 16 | 17 | // Push item into s1 18 | s1.push(x); 19 | 20 | // Push everything back to s1 21 | while (!s2.empty()) { 22 | s1.push(s2.top()); 23 | s2.pop(); 24 | } 25 | } 26 | 27 | // Dequeue an item from the queue 28 | int deQueue() 29 | { 30 | // if first stack is empty 31 | if (s1.empty()) { 32 | cout << "Q is Empty"; 33 | exit(0); 34 | } 35 | 36 | // Return top of s1 37 | int x = s1.top(); 38 | s1.pop(); 39 | return x; 40 | } 41 | }; 42 | 43 | // Driver code 44 | int main() 45 | { 46 | Queue q; 47 | q.enQueue(1); 48 | q.enQueue(2); 49 | q.enQueue(3); 50 | 51 | cout << q.deQueue() << '\n'; 52 | cout << q.deQueue() << '\n'; 53 | cout << q.deQueue() << '\n'; 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /254.cpp: -------------------------------------------------------------------------------- 1 | // A recursive C++ program to 2 | // calculate the size of the tree 3 | #include 4 | using namespace std; 5 | 6 | /* A binary tree node has data, pointer to left child 7 | and a pointer to right child */ 8 | class node 9 | { 10 | public: 11 | int data; 12 | node* left; 13 | node* right; 14 | }; 15 | 16 | /* Helper function that allocates a new node with the 17 | given data and NULL left and right pointers. */ 18 | node* newNode(int data) 19 | { 20 | node* Node = new node(); 21 | Node->data = data; 22 | Node->left = NULL; 23 | Node->right = NULL; 24 | 25 | return(Node); 26 | } 27 | 28 | /* Computes the number of nodes in a tree. */ 29 | int size(node* node) 30 | { 31 | if (node == NULL) 32 | return 0; 33 | else 34 | return(size(node->left) + 1 + size(node->right)); 35 | } 36 | 37 | /* Driver code*/ 38 | int main() 39 | { 40 | node *root = newNode(1); 41 | root->left = newNode(2); 42 | root->right = newNode(3); 43 | root->left->left = newNode(4); 44 | root->left->right = newNode(5); 45 | 46 | cout << "Size of the tree is " << size(root); 47 | return 0; 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /256.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find height of tree 2 | #include 3 | using namespace std; 4 | 5 | 6 | /* A binary tree node has data, pointer to left child 7 | and a pointer to right child */ 8 | class node 9 | { 10 | public: 11 | int data; 12 | node* left; 13 | node* right; 14 | }; 15 | 16 | /* Compute the "maxDepth" of a tree -- the number of 17 | nodes along the longest path from the root node 18 | down to the farthest leaf node.*/ 19 | int maxDepth(node* node) 20 | { 21 | if (node == NULL) 22 | return 0; 23 | else 24 | { 25 | /* compute the depth of each subtree */ 26 | int lDepth = maxDepth(node->left); 27 | int rDepth = maxDepth(node->right); 28 | 29 | /* use the larger one */ 30 | if (lDepth > rDepth) 31 | return(lDepth + 1); 32 | else return(rDepth + 1); 33 | } 34 | } 35 | 36 | /* Helper function that allocates a new node with the 37 | given data and NULL left and right pointers. */ 38 | node* newNode(int data) 39 | { 40 | node* Node = new node(); 41 | Node->data = data; 42 | Node->left = NULL; 43 | Node->right = NULL; 44 | 45 | return(Node); 46 | } 47 | 48 | // Driver code 49 | int main() 50 | { 51 | node *root = newNode(1); 52 | 53 | root->left = newNode(2); 54 | root->right = newNode(3); 55 | root->left->left = newNode(4); 56 | root->left->right = newNode(5); 57 | 58 | cout << "Height of tree is " << maxDepth(root); 59 | return 0; 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /257.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Delete a Tree 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | /* A binary tree node has data, 8 | pointer to left child and 9 | a pointer to right child */ 10 | class node 11 | { 12 | public: 13 | int data; 14 | node* left; 15 | node* right; 16 | 17 | /* Constructor that allocates 18 | a new node with the given data 19 | and NULL left and right pointers. */ 20 | node(int data) 21 | { 22 | this->data = data; 23 | this->left = NULL; 24 | this->right = NULL; 25 | } 26 | }; 27 | 28 | 29 | /* This function traverses tree 30 | in post order to delete each 31 | and every node of the tree */ 32 | void deleteTree(node* node) 33 | { 34 | if (node == NULL) return; 35 | 36 | /* first delete both subtrees */ 37 | deleteTree(node->left); 38 | deleteTree(node->right); 39 | 40 | /* then delete the node */ 41 | cout << "\n Deleting node: " << node->data; 42 | delete node; 43 | } 44 | 45 | 46 | /* Driver code*/ 47 | int main() 48 | { 49 | node *root = new node(1); 50 | root->left = new node(2); 51 | root->right = new node(3); 52 | root->left->left = new node(4); 53 | root->left->right = new node(5); 54 | 55 | deleteTree(root); 56 | root = NULL; 57 | 58 | cout << "\n Tree deleted "; 59 | 60 | return 0; 61 | } 62 | 63 | -------------------------------------------------------------------------------- /26.cpp: -------------------------------------------------------------------------------- 1 | // C++ code for k largest elements in an array 2 | #include 3 | using namespace std; 4 | 5 | void kLargest(int arr[], int n, int k) 6 | { 7 | // Sort the given array arr in reverse 8 | // order. 9 | sort(arr, arr + n, greater()); 10 | 11 | // Print the first kth largest elements 12 | for (int i = 0; i < k; i++) 13 | cout << arr[i] << " "; 14 | } 15 | 16 | // driver program 17 | int main() 18 | { 19 | int arr[] = { 1, 23, 12, 9, 30, 2, 50 }; 20 | int n = sizeof(arr) / sizeof(arr[0]); 21 | int k = 3; 22 | kLargest(arr, n, k); 23 | } 24 | 25 | 26 | -------------------------------------------------------------------------------- /263.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation to find leaf 2 | // count of a given Binary tree 3 | #include 4 | using namespace std; 5 | 6 | /* A binary tree node has data, 7 | pointer to left child and 8 | a pointer to right child */ 9 | struct node 10 | { 11 | int data; 12 | struct node* left; 13 | struct node* right; 14 | }; 15 | 16 | /* Function to get the count 17 | of leaf nodes in a binary tree*/ 18 | unsigned int getLeafCount(struct node* node) 19 | { 20 | if(node == NULL) 21 | return 0; 22 | if(node->left == NULL && node->right == NULL) 23 | return 1; 24 | else 25 | return getLeafCount(node->left)+ 26 | getLeafCount(node->right); 27 | } 28 | 29 | /* Helper function that allocates a new node with the 30 | given data and NULL left and right pointers. */ 31 | struct node* newNode(int data) 32 | { 33 | struct node* node = (struct node*) 34 | malloc(sizeof(struct node)); 35 | node->data = data; 36 | node->left = NULL; 37 | node->right = NULL; 38 | 39 | return(node); 40 | } 41 | 42 | /*Driver code*/ 43 | int main() 44 | { 45 | /*create a tree*/ 46 | struct node *root = newNode(1); 47 | root->left = newNode(2); 48 | root->right = newNode(3); 49 | root->left->left = newNode(4); 50 | root->left->right = newNode(5); 51 | 52 | /*get leaf count of the above created tree*/ 53 | cout << "Leaf count of the tree is : "<< 54 | getLeafCount(root) << endl; 55 | return 0; 56 | } 57 | 58 | -------------------------------------------------------------------------------- /278.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | /* A binary tree node has data, 6 | pointer to left child and 7 | a pointer to right child */ 8 | class node 9 | { 10 | public: 11 | int data; 12 | node* left; 13 | node* right; 14 | 15 | /* Constructor that allocates a new node with the 16 | given data and NULL left and right pointers. */ 17 | node(int data) 18 | { 19 | this->data = data; 20 | this->left = NULL; 21 | this->right = NULL; 22 | } 23 | }; 24 | 25 | void printKDistant(node *root , int k) 26 | { 27 | if(root == NULL|| k < 0 ) 28 | return; 29 | if( k == 0 ) 30 | { 31 | cout << root->data << " "; 32 | return; 33 | } 34 | 35 | printKDistant( root->left, k - 1 ) ; 36 | printKDistant( root->right, k - 1 ) ; 37 | 38 | } 39 | 40 | 41 | /* Driver code*/ 42 | int main() 43 | { 44 | 45 | /* Constructed binary tree is 46 | 1 47 | / \ 48 | 2 3 49 | / \ / 50 | 4 5 8 51 | */ 52 | node *root = new node(1); 53 | root->left = new node(2); 54 | root->right = new node(3); 55 | root->left->left = new node(4); 56 | root->left->right = new node(5); 57 | root->right->left = new node(8); 58 | 59 | printKDistant(root, 2); 60 | return 0; 61 | } 62 | 63 | -------------------------------------------------------------------------------- /28.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find Maximum difference 2 | // between two elements such that larger 3 | // element appears after the smaller number 4 | #include 5 | using namespace std; 6 | 7 | /* The function assumes that there are 8 | at least two elements in array. The 9 | function returns a negative value if the 10 | array is sorted in decreasing order and 11 | returns 0 if elements are equal */ 12 | int maxDiff(int arr[], int arr_size) 13 | { 14 | int max_diff = arr[1] - arr[0]; 15 | for (int i = 0; i < arr_size; i++) 16 | { 17 | for (int j = i+1; j < arr_size; j++) 18 | { 19 | if (arr[j] - arr[i] > max_diff) 20 | max_diff = arr[j] - arr[i]; 21 | } 22 | } 23 | return max_diff; 24 | } 25 | 26 | /* Driver program to test above function */ 27 | int main() 28 | { 29 | int arr[] = {1, 2, 90, 10, 110}; 30 | int n = sizeof(arr) / sizeof(arr[0]); 31 | 32 | // Function calling 33 | cout << "Maximum difference is " << maxDiff(arr, n); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /280.cpp: -------------------------------------------------------------------------------- 1 | // C++ Code for Sorted order printing of a 2 | // given array that represents a BST 3 | #include 4 | using namespace std; 5 | 6 | void printSorted(int arr[], int start, int end) 7 | { 8 | if(start > end) 9 | return; 10 | 11 | // print left subtree 12 | printSorted(arr, start*2 + 1, end); 13 | 14 | // print root 15 | cout << arr[start] << " "; 16 | 17 | // print right subtree 18 | printSorted(arr, start*2 + 2, end); 19 | } 20 | 21 | int main() 22 | { 23 | int arr[] = {4, 2, 5, 1, 3}; 24 | int arr_size = sizeof(arr)/sizeof(int); 25 | printSorted(arr, 0, arr_size-1); 26 | getchar(); 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /29.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find union of 2 | // two sorted arrays 3 | #include 4 | using namespace std; 5 | 6 | /* Function prints union of arr1[] and arr2[] 7 | m is the number of elements in arr1[] 8 | n is the number of elements in arr2[] */ 9 | void printUnion(int arr1[], int arr2[], int m, int n) 10 | { 11 | int i = 0, j = 0; 12 | while (i < m && j < n) { 13 | if (arr1[i] < arr2[j]) 14 | cout << arr1[i++] << " "; 15 | 16 | else if (arr2[j] < arr1[i]) 17 | cout << arr2[j++] << " "; 18 | 19 | else { 20 | cout << arr2[j++] << " "; 21 | i++; 22 | } 23 | } 24 | 25 | /* Print remaining elements of the larger array */ 26 | while (i < m) 27 | cout << arr1[i++] << " "; 28 | 29 | while (j < n) 30 | cout << arr2[j++] << " "; 31 | } 32 | 33 | /* Driver program to test above function */ 34 | int main() 35 | { 36 | int arr1[] = { 1, 2, 4, 5, 6 }; 37 | int arr2[] = { 2, 3, 5, 7 }; 38 | 39 | int m = sizeof(arr1) / sizeof(arr1[0]); 40 | int n = sizeof(arr2) / sizeof(arr2[0]); 41 | 42 | // Function calling 43 | printUnion(arr1, arr2, m, n); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /3.cpp: -------------------------------------------------------------------------------- 1 | // Recursive C++ program 2 | // to search x in array 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Recursive function to 8 | // search x in arr[l..r] 9 | int recSearch(int arr[], int l, 10 | int r, int x) 11 | { 12 | if (r < l) 13 | return -1; 14 | if (arr[l] == x) 15 | return l; 16 | if (arr[r] == x) 17 | return r; 18 | return recSearch(arr, l + 1, 19 | r - 1, x); 20 | } 21 | 22 | // Driver Code 23 | int main() 24 | { 25 | int arr[] = {12, 34, 54, 2, 3}, i; 26 | int n = sizeof(arr) / sizeof(arr[0]); 27 | int x = 3; 28 | int index = recSearch(arr, 0, n - 1, x); 29 | if (index != -1) 30 | cout << "Element " << x 31 | << " is present at index " 32 | << index; 33 | else 34 | cout << "Element" << x 35 | << " is not present" ; 36 | return 0; 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /30.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of above approach 2 | #include 3 | using namespace std; 4 | 5 | /* Function to get index of ceiling of x in arr[low..high] */ 6 | int ceilSearch(int arr[], int low, int high, int x) 7 | { 8 | 9 | int i; 10 | 11 | /* If x is smaller than or equal to first element, 12 | then return the first element */ 13 | if(x <= arr[low]) 14 | return low; 15 | 16 | /* Otherwise, linearly search for ceil value */ 17 | for(i = low; i < high; i++) 18 | { 19 | if(arr[i] == x) 20 | return i; 21 | 22 | /* if x lies between arr[i] and arr[i+1] including 23 | arr[i+1], then return arr[i+1] */ 24 | if(arr[i] < x && arr[i+1] >= x) 25 | return i+1; 26 | } 27 | 28 | /* If we reach here then x is greater than the last element 29 | of the array, return -1 in this case */ 30 | return -1; 31 | } 32 | 33 | 34 | /* Driver code*/ 35 | int main() 36 | { 37 | int arr[] = {1, 2, 8, 10, 10, 12, 19}; 38 | int n = sizeof(arr)/sizeof(arr[0]); 39 | int x = 3; 40 | int index = ceilSearch(arr, 0, n-1, x); 41 | if(index == -1) 42 | cout << "Ceiling of " << x << " doesn't exist in array "; 43 | else 44 | cout << "ceiling of " << x << " is " << arr[index]; 45 | 46 | return 0; 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /31.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of above approach 2 | #include 3 | using namespace std; 4 | 5 | /* Function to print product array 6 | for a given array arr[] of size n */ 7 | void productArray(int arr[], int n) 8 | { 9 | 10 | // Base case 11 | if (n == 1) { 12 | cout << 0; 13 | return; 14 | } 15 | /* Allocate memory for temporary 16 | arrays left[] and right[] */ 17 | int* left = new int[sizeof(int) * n]; 18 | int* right = new int[sizeof(int) * n]; 19 | 20 | /* Allocate memory for the product array */ 21 | int* prod = new int[sizeof(int) * n]; 22 | 23 | int i, j; 24 | 25 | /* Left most element of left 26 | array is always 1 */ 27 | left[0] = 1; 28 | 29 | /* Rightmost most element of right 30 | array is always 1 */ 31 | right[n - 1] = 1; 32 | 33 | /* Construct the left array */ 34 | for (i = 1; i < n; i++) 35 | left[i] = arr[i - 1] * left[i - 1]; 36 | 37 | /* Construct the right array */ 38 | for (j = n - 2; j >= 0; j--) 39 | right[j] = arr[j + 1] * right[j + 1]; 40 | 41 | /* Construct the product array using 42 | left[] and right[] */ 43 | for (i = 0; i < n; i++) 44 | prod[i] = left[i] * right[i]; 45 | 46 | /* print the constructed prod array */ 47 | for (i = 0; i < n; i++) 48 | cout << prod[i] << " "; 49 | 50 | return; 51 | } 52 | 53 | /* Driver code*/ 54 | int main() 55 | { 56 | int arr[] = { 10, 3, 5, 6, 2 }; 57 | int n = sizeof(arr) / sizeof(arr[0]); 58 | cout << "The product array is: \n"; 59 | productArray(arr, n); 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /32.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to segregate even and odd elements of array 2 | #include 3 | using namespace std; 4 | 5 | /* Function to swap *a and *b */ 6 | void swap(int *a, int *b); 7 | 8 | void segregateEvenOdd(int arr[], int size) 9 | { 10 | /* Initialize left and right indexes */ 11 | int left = 0, right = size-1; 12 | while (left < right) 13 | { 14 | /* Increment left index while we see 0 at left */ 15 | while (arr[left] % 2 == 0 && left < right) 16 | left++; 17 | 18 | /* Decrement right index while we see 1 at right */ 19 | while (arr[right] % 2 == 1 && left < right) 20 | right--; 21 | 22 | if (left < right) 23 | { 24 | /* Swap arr[left] and arr[right]*/ 25 | swap(&arr[left], &arr[right]); 26 | left++; 27 | right--; 28 | } 29 | } 30 | } 31 | 32 | /* UTILITY FUNCTIONS */ 33 | void swap(int *a, int *b) 34 | { 35 | int temp = *a; 36 | *a = *b; 37 | *b = temp; 38 | } 39 | 40 | /* Driver code */ 41 | int main() 42 | { 43 | int arr[] = {12, 34, 45, 9, 8, 90, 3}; 44 | int arr_size = sizeof(arr)/sizeof(arr[0]); 45 | int i = 0; 46 | 47 | segregateEvenOdd(arr, arr_size); 48 | 49 | cout <<"Array after segregation "; 50 | for (i = 0; i < arr_size; i++) 51 | cout << arr[i] << " "; 52 | 53 | return 0; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /33.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Find the two repeating 2 | // elements in a given array 3 | #include 4 | using namespace std; 5 | 6 | void printRepeating(int arr[], int size) 7 | { 8 | int i, j; 9 | printf(" Repeating elements are "); 10 | for(i = 0; i < size; i++) 11 | for(j = i + 1; j < size; j++) 12 | if(arr[i] == arr[j]) 13 | cout << arr[i] << " "; 14 | } 15 | 16 | // Driver Code 17 | int main() 18 | { 19 | int arr[] = {4, 2, 4, 5, 2, 3, 1}; 20 | int arr_size = sizeof(arr)/sizeof(arr[0]); 21 | printRepeating(arr, arr_size); 22 | } 23 | 24 | 25 | -------------------------------------------------------------------------------- /333.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print postorder traversal from preorder and inorder traversals 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to search x in arr[] of size n 6 | int search(int arr[], int x, int n) 7 | { 8 | for (int i = 0; i < n; i++) 9 | if (arr[i] == x) 10 | return i; 11 | return -1; 12 | } 13 | 14 | // Prints postorder traversal from given inorder and preorder traversals 15 | void printPostOrder(int in[], int pre[], int n) 16 | { 17 | // The first element in pre[] is always root, search it 18 | // in in[] to find left and right subtrees 19 | int root = search(in, pre[0], n); 20 | 21 | // If left subtree is not empty, print left subtree 22 | if (root != 0) 23 | printPostOrder(in, pre + 1, root); 24 | 25 | // If right subtree is not empty, print right subtree 26 | if (root != n - 1) 27 | printPostOrder(in + root + 1, pre + root + 1, n - root - 1); 28 | 29 | // Print root 30 | cout << pre[0] << " "; 31 | } 32 | 33 | // Driver program to test above functions 34 | int main() 35 | { 36 | int in[] = { 4, 2, 5, 1, 3, 6 }; 37 | int pre[] = { 1, 2, 4, 5, 3, 6 }; 38 | int n = sizeof(in) / sizeof(in[0]); 39 | cout << "Postorder traversal " << endl; 40 | printPostOrder(in, pre, n); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /34.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to sort an array 2 | // with 0, 1 and 2 in a single pass 3 | #include 4 | using namespace std; 5 | 6 | // Function to sort the input array, 7 | // the array is assumed 8 | // to have values in {0, 1, 2} 9 | void sort012(int a[], int arr_size) 10 | { 11 | int lo = 0; 12 | int hi = arr_size - 1; 13 | int mid = 0; 14 | 15 | // Iterate till all the elements 16 | // are sorted 17 | while (mid <= hi) { 18 | switch (a[mid]) { 19 | 20 | // If the element is 0 21 | case 0: 22 | swap(a[lo++], a[mid++]); 23 | break; 24 | 25 | // If the element is 1 . 26 | case 1: 27 | mid++; 28 | break; 29 | 30 | // If the element is 2 31 | case 2: 32 | swap(a[mid], a[hi--]); 33 | break; 34 | } 35 | } 36 | } 37 | 38 | // Function to print array arr[] 39 | void printArray(int arr[], int arr_size) 40 | { 41 | // Iterate and print every element 42 | for (int i = 0; i < arr_size; i++) 43 | cout << arr[i] << " "; 44 | } 45 | 46 | // Driver Code 47 | int main() 48 | { 49 | int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; 50 | int n = sizeof(arr) / sizeof(arr[0]); 51 | 52 | sort012(arr, n); 53 | 54 | cout << "array after segregation "; 55 | 56 | printArray(arr, n); 57 | 58 | return 0; 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /35.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find the Minimum length Unsorted Subarray, 2 | // sorting which makes the complete array sorted 3 | #include 4 | using namespace std; 5 | 6 | void printUnsorted(int arr[], int n) 7 | { 8 | int s = 0, e = n-1, i, max, min; 9 | 10 | // step 1(a) of above algo 11 | for (s = 0; s < n-1; s++) 12 | { 13 | if (arr[s] > arr[s+1]) 14 | break; 15 | } 16 | if (s == n-1) 17 | { 18 | cout << "The complete array is sorted"; 19 | return; 20 | } 21 | 22 | // step 1(b) of above algo 23 | for(e = n - 1; e > 0; e--) 24 | { 25 | if(arr[e] < arr[e-1]) 26 | break; 27 | } 28 | 29 | // step 2(a) of above algo 30 | max = arr[s]; min = arr[s]; 31 | for(i = s + 1; i <= e; i++) 32 | { 33 | if(arr[i] > max) 34 | max = arr[i]; 35 | if(arr[i] < min) 36 | min = arr[i]; 37 | } 38 | 39 | // step 2(b) of above algo 40 | for( i = 0; i < s; i++) 41 | { 42 | if(arr[i] > min) 43 | { 44 | s = i; 45 | break; 46 | } 47 | } 48 | 49 | // step 2(c) of above algo 50 | for( i = n -1; i >= e+1; i--) 51 | { 52 | if(arr[i] < max) 53 | { 54 | e = i; 55 | break; 56 | } 57 | } 58 | 59 | // step 3 of above algo 60 | cout << "The unsorted subarray which" 61 | << " makes the given array" << endl 62 | << "sorted lies between the indees " 63 | << s << " and " << e; 64 | return; 65 | } 66 | 67 | int main() 68 | { 69 | int arr[] = {10, 12, 20, 30, 25, 70 | 40, 32, 31, 35, 50, 60}; 71 | int arr_size = sizeof(arr)/sizeof(arr[0]); 72 | printUnsorted(arr, arr_size); 73 | getchar(); 74 | return 0; 75 | } 76 | 77 | -------------------------------------------------------------------------------- /356.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print DFS traversal from 2 | // a given vertex in a given graph 3 | #include 4 | using namespace std; 5 | 6 | // Graph class represents a directed graph 7 | // using adjacency list representation 8 | class Graph 9 | { 10 | public: 11 | map visited; 12 | map> adj; 13 | 14 | // function to add an edge to graph 15 | void addEdge(int v, int w); 16 | 17 | // DFS traversal of the vertices 18 | // reachable from v 19 | void DFS(int v); 20 | }; 21 | 22 | void Graph::addEdge(int v, int w) 23 | { 24 | adj[v].push_back(w); // Add w to v’s list. 25 | } 26 | 27 | void Graph::DFS(int v) 28 | { 29 | // Mark the current node as visited and 30 | // print it 31 | visited[v] = true; 32 | cout << v << " "; 33 | 34 | // Recur for all the vertices adjacent 35 | // to this vertex 36 | list::iterator i; 37 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 38 | if (!visited[*i]) 39 | DFS(*i); 40 | } 41 | 42 | // Driver code 43 | int main() 44 | { 45 | // Create a graph given in the above diagram 46 | Graph g; 47 | g.addEdge(0, 1); 48 | g.addEdge(0, 9); 49 | g.addEdge(1, 2); 50 | g.addEdge(2, 0); 51 | g.addEdge(2, 3); 52 | g.addEdge(9, 3); 53 | 54 | cout << "Following is Depth First Traversal" 55 | " (starting from vertex 2) \n"; 56 | g.DFS(2); 57 | 58 | return 0; 59 | } 60 | 61 | 62 | -------------------------------------------------------------------------------- /36.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to find 2 | // duplicates in O(n) time 3 | #include 4 | using namespace std; 5 | 6 | // Function to print duplicates 7 | void printRepeating(int arr[], int size) 8 | { 9 | int i; 10 | cout << "The repeating elements are:" << endl; 11 | for (i = 0; i < size; i++) { 12 | if (arr[abs(arr[i])] >= 0) 13 | arr[abs(arr[i])] = -arr[abs(arr[i])]; 14 | else 15 | cout << abs(arr[i]) << " "; 16 | } 17 | } 18 | 19 | // Driver Code 20 | int main() 21 | { 22 | int arr[] = { 1, 2, 3, 1, 3, 6, 6 }; 23 | int arr_size = sizeof(arr) / sizeof(arr[0]); 24 | printRepeating(arr, arr_size); 25 | return 0; 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /364.cpp: -------------------------------------------------------------------------------- 1 | // A simple representation of graph using STL 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to add an edge in an 6 | // undirected graph. 7 | void addEdge(vector adj[], int u, int v) 8 | { 9 | adj[u].push_back(v); 10 | adj[v].push_back(u); 11 | } 12 | 13 | // A utility function to print the adjacency list 14 | // representation of graph 15 | void printGraph(vector adj[], int V) 16 | { 17 | for (int v = 0; v < V; ++v) 18 | { 19 | cout << "\n Adjacency list of vertex " 20 | << v << "\n head "; 21 | for (auto x : adj[v]) 22 | cout << "-> " << x; 23 | printf("\n"); 24 | } 25 | } 26 | 27 | // Driver code 28 | int main() 29 | { 30 | int V = 5; 31 | vector adj[V]; 32 | addEdge(adj, 0, 1); 33 | addEdge(adj, 0, 4); 34 | addEdge(adj, 1, 2); 35 | addEdge(adj, 1, 3); 36 | addEdge(adj, 1, 4); 37 | addEdge(adj, 2, 3); 38 | addEdge(adj, 3, 4); 39 | printGraph(adj, V); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /37.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find equilibrium 2 | // index of an array 3 | #include 4 | using namespace std; 5 | 6 | int equilibrium(int arr[], int n) 7 | { 8 | int i, j; 9 | int leftsum, rightsum; 10 | 11 | /* Check for indexes one by one until 12 | an equilibrium index is found */ 13 | for (i = 0; i < n; ++i) 14 | { 15 | 16 | /* get left sum */ 17 | leftsum = 0; 18 | for (j = 0; j < i; j++) 19 | leftsum += arr[j]; 20 | 21 | /* get right sum */ 22 | rightsum = 0; 23 | for (j = i + 1; j < n; j++) 24 | rightsum += arr[j]; 25 | 26 | /* if leftsum and rightsum 27 | are same, then we are done */ 28 | if (leftsum == rightsum) 29 | return i; 30 | } 31 | 32 | /* return -1 if no equilibrium 33 | index is found */ 34 | return -1; 35 | } 36 | 37 | // Driver code 38 | int main() 39 | { 40 | int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; 41 | int arr_size = sizeof(arr) / sizeof(arr[0]); 42 | cout << equilibrium(arr, arr_size); 43 | return 0; 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /389.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find 2 | // smallest power of 2 3 | // greater than or equal to n 4 | #include 5 | using namespace std; 6 | 7 | unsigned int nextPowerOf2(unsigned int n) 8 | { 9 | unsigned count = 0; 10 | 11 | // First n in the below condition 12 | // is for the case where n is 0 13 | if (n && !(n & (n - 1))) 14 | return n; 15 | 16 | while( n != 0) 17 | { 18 | n >>= 1; 19 | count += 1; 20 | } 21 | 22 | return 1 << count; 23 | } 24 | 25 | // Driver Code 26 | int main() 27 | { 28 | unsigned int n = 0; 29 | cout << nextPowerOf2(n); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /39.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to search an element in row-wise 2 | // and column-wise sorted matrix 3 | #include 4 | 5 | using namespace std; 6 | 7 | /* Searches the element x in mat[][]. If the 8 | element is found, then prints its position 9 | and returns true, otherwise prints "not found" 10 | and returns false */ 11 | int search(int mat[4][4], int n, int x) 12 | { 13 | if (n == 0) 14 | return -1; 15 | 16 | //traverse through the matrix 17 | for(int i = 0; i < n; i++) 18 | { 19 | for(int j = 0; j < n; j++) 20 | //if the element is found 21 | if(mat[i][j] == x) 22 | { 23 | cout<<"Element found at ("<< 24 | i << ", " << j << ")\n"; 25 | return 1; 26 | } 27 | } 28 | 29 | cout << "\n Element not found"; 30 | return 0; 31 | } 32 | 33 | // Driver code 34 | int main() 35 | { 36 | int mat[4][4] = { { 10, 20, 30, 40 }, 37 | { 15, 25, 35, 45 }, 38 | { 27, 29, 37, 48 }, 39 | { 32, 33, 39, 50 } }; 40 | search(mat, 4, 29); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /390.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to check if n is a multiple of 3 2 | #include 3 | using namespace std; 4 | 5 | /* Function to check if n is a multiple of 3*/ 6 | int isMultipleOf3(int n) 7 | { 8 | int odd_count = 0; 9 | int even_count = 0; 10 | 11 | /* Make no positive if +n is multiple of 3 12 | then is -n. We are doing this to avoid 13 | stack overflow in recursion*/ 14 | if (n < 0) 15 | n = -n; 16 | if (n == 0) 17 | return 1; 18 | if (n == 1) 19 | return 0; 20 | 21 | while (n) { 22 | /* If odd bit is set then 23 | increment odd counter */ 24 | if (n & 1) 25 | odd_count++; 26 | 27 | /* If even bit is set then 28 | increment even counter */ 29 | if (n & 2) 30 | even_count++; 31 | n = n >> 2; 32 | } 33 | 34 | return isMultipleOf3(abs(odd_count - even_count)); 35 | } 36 | 37 | /* Program to test function isMultipleOf3 */ 38 | int main() 39 | { 40 | int num = 24; 41 | if (isMultipleOf3(num)) 42 | printf("%d is multiple of 3", num); 43 | else 44 | printf("%d is not a multiple of 3", num); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /391.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find parity 2 | // of an integer 3 | # include 4 | # define bool int 5 | using namespace std; 6 | 7 | // Function to get parity of number n. It returns 1 8 | // if n has odd parity, and returns 0 if n has even 9 | // parity 10 | bool getParity(unsigned int n) 11 | { 12 | bool parity = 0; 13 | while (n) 14 | { 15 | parity = !parity; 16 | n = n & (n - 1); 17 | } 18 | return parity; 19 | } 20 | 21 | /* Driver program to test getParity() */ 22 | int main() 23 | { 24 | unsigned int n = 7; 25 | cout<<"Parity of no "< 4 | using namespace std; 5 | 6 | // Function to check if x is power of 2 7 | bool isPowerOfTwo(int n) 8 | { 9 | if(n==0) 10 | return false; 11 | 12 | return (ceil(log2(n)) == floor(log2(n))); 13 | } 14 | 15 | // Driver program 16 | int main() 17 | { 18 | isPowerOfTwo(31)? cout<<"Yes"< 4 | #include 5 | using namespace std; 6 | 7 | class gfg 8 | { 9 | 10 | public: 11 | unsigned int getFirstSetBitPos(int n) 12 | { 13 | return log2(n & -n) + 1; 14 | } 15 | }; 16 | 17 | // Driver code 18 | int main() 19 | { 20 | gfg g; 21 | int n = 12; 22 | cout << g.getFirstSetBitPos(n); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /394.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* Takes pointer to result and two numbers as 5 | arguments. If there is no overflow, the function 6 | places the resultant = sum a+b in “result” and 7 | returns 0, otherwise it returns -1 */ 8 | int addOvf(int* result, int a, int b) 9 | { 10 | *result = a + b; 11 | if(a > 0 && b > 0 && *result < 0) 12 | return -1; 13 | if(a < 0 && b < 0 && *result > 0) 14 | return -1; 15 | return 0; 16 | } 17 | 18 | // Driver code 19 | int main() 20 | { 21 | int *res = new int[(sizeof(int))]; 22 | int x = 2147483640; 23 | int y = 10; 24 | 25 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | unsigned int i = 1; 6 | char *c = (char*)&i; 7 | if (*c) 8 | cout<<"Little endian"; 9 | else 10 | cout<<"Big endian"; 11 | return 0; 12 | } 13 | 14 | 15 | -------------------------------------------------------------------------------- /396.cpp: -------------------------------------------------------------------------------- 1 | /* Function to reverse bits of num */ 2 | unsigned int reverseBits(unsigned int num) 3 | { 4 | unsigned int NO_OF_BITS = sizeof(num) * 8; 5 | unsigned int reverse_num = 0, i, temp; 6 | 7 | for (i = 0; i < NO_OF_BITS; i++) 8 | { 9 | temp = (num & (1 << i)); 10 | if(temp) 11 | reverse_num |= (1 << ((NO_OF_BITS - 1) - i)); 12 | } 13 | 14 | return reverse_num; 15 | } 16 | 17 | /* Driver function to test above function */ 18 | int main() 19 | { 20 | unsigned int x = 2; 21 | printf("%u", reverseBits(x)); 22 | getchar(); 23 | } 24 | -------------------------------------------------------------------------------- /397.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Count set 2 | // bits in an integer 3 | #include 4 | using namespace std; 5 | 6 | /* Function to get no of set bits in binary 7 | representation of positive integer n */ 8 | unsigned int countSetBits(unsigned int n) 9 | { 10 | unsigned int count = 0; 11 | while (n) { 12 | count += n & 1; 13 | n >>= 1; 14 | } 15 | return count; 16 | } 17 | 18 | /* Program to test function countSetBits */ 19 | int main() 20 | { 21 | int i = 9; 22 | cout << countSetBits(i); 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /398.cpp: -------------------------------------------------------------------------------- 1 | // Count number of bits to be flipped 2 | // to convert A into B 3 | #include 4 | using namespace std; 5 | 6 | // Function that count set bits 7 | int countSetBits(int n) 8 | { 9 | int count = 0; 10 | while (n > 0) 11 | { 12 | count++; 13 | n &= (n-1); 14 | } 15 | return count; 16 | } 17 | 18 | // Function that return count of 19 | // flipped number 20 | int FlippedCount(int a, int b) 21 | { 22 | // Return count of set bits in 23 | // a XOR b 24 | return countSetBits(a^b); 25 | } 26 | 27 | // Driver code 28 | int main() 29 | { 30 | int a = 10; 31 | int b = 20; 32 | cout << FlippedCount(a, b)< 3 | using namespace std; 4 | 5 | /* This function sets the values of 6 | *x and *y to non-repeating elements 7 | in an array arr[] of size n*/ 8 | void get2NonRepeatingNos(int arr[], int n, 9 | int *x, int *y) 10 | { 11 | /* Will hold Xor of all elements */ 12 | int Xor = arr[0]; 13 | 14 | /* Will have only single set bit of Xor */ 15 | int set_bit_no; 16 | int i; 17 | *x = 0; 18 | *y = 0; 19 | 20 | /* Get the Xor of all elements */ 21 | for(i = 1; i < n; i++) 22 | Xor ^= arr[i]; 23 | 24 | /* Get the rightmost set bit in set_bit_no */ 25 | set_bit_no = Xor & ~(Xor-1); 26 | 27 | /* Now divide elements in two sets by 28 | comparing rightmost set bit of Xor with bit 29 | at same position in each element. */ 30 | for(i = 0; i < n; i++) 31 | { 32 | 33 | /*Xor of first set */ 34 | if(arr[i] & set_bit_no) 35 | *x = *x ^ arr[i]; 36 | /*Xor of second set*/ 37 | else 38 | { 39 | *y = *y ^ arr[i]; 40 | } 41 | } 42 | } 43 | 44 | /* Driver code */ 45 | int main() 46 | { 47 | int arr[] = {2, 3, 7, 9, 11, 2, 3, 11}; 48 | int n = sizeof(arr)/sizeof(*arr); 49 | int *x = new int[(sizeof(int))]; 50 | int *y = new int[(sizeof(int))]; 51 | get2NonRepeatingNos(arr, n, x, y); 52 | cout<<"The non-repeating elements are "<<*x<<" and "<<*y; 53 | } 54 | 55 | -------------------------------------------------------------------------------- /4.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check if given array 2 | // has 2 elements whose sum is equal 3 | // to the given value 4 | 5 | #include 6 | using namespace std; 7 | 8 | // Function to check if array has 2 elements 9 | // whose sum is equal to the given value 10 | bool hasArrayTwoCandidates(int A[], int arr_size, 11 | int sum) 12 | { 13 | int l, r; 14 | 15 | /* Sort the elements */ 16 | sort(A, A + arr_size); 17 | 18 | /* Now look for the two candidates in 19 | the sorted array*/ 20 | l = 0; 21 | r = arr_size - 1; 22 | while (l < r) { 23 | if (A[l] + A[r] == sum) 24 | return 1; 25 | else if (A[l] + A[r] < sum) 26 | l++; 27 | else // A[i] + A[j] > sum 28 | r--; 29 | } 30 | return 0; 31 | } 32 | 33 | /* Driver program to test above function */ 34 | int main() 35 | { 36 | int A[] = { 3, 2, 65, 6, 23, -8 }; 37 | int n = 16; 38 | int arr_size = sizeof(A) / sizeof(A[0]); 39 | 40 | // Function calling 41 | if (hasArrayTwoCandidates(A, arr_size, n)) 42 | cout << "Array has two elements" 43 | " with given sum"; 44 | else 45 | cout << "Array doesn't have two" 46 | " elements with given sum"; 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /40.cpp: -------------------------------------------------------------------------------- 1 | // Simple C++ program to print 2 | // next greater elements in a 3 | // given array 4 | #include 5 | using namespace std; 6 | 7 | /* prints element and NGE pair 8 | for all elements of arr[] of size n */ 9 | void printNGE(int arr[], int n) 10 | { 11 | int next, i, j; 12 | for (i = 0; i < n; i++) 13 | { 14 | next = -1; 15 | for (j = i + 1; j < n; j++) 16 | { 17 | if (arr[i] < arr[j]) 18 | { 19 | next = arr[j]; 20 | break; 21 | } 22 | } 23 | cout << arr[i] << " -- " 24 | << next << endl; 25 | } 26 | } 27 | 28 | // Driver Code 29 | int main() 30 | { 31 | int arr[] = {11, 13, 21, 3}; 32 | int n = sizeof(arr)/sizeof(arr[0]); 33 | printNGE(arr, n); 34 | return 0; 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /400.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to rotate bits 2 | // of number 3 | #include 4 | 5 | using namespace std; 6 | #define INT_BITS 32 7 | class gfg 8 | { 9 | 10 | /*Function to left rotate n by d bits*/ 11 | public: 12 | int leftRotate(int n, unsigned int d) 13 | { 14 | 15 | /* In n<>(INT_BITS - d) */ 19 | return (n << d)|(n >> (INT_BITS - d)); 20 | } 21 | 22 | /*Function to right rotate n by d bits*/ 23 | int rightRotate(int n, unsigned int d) 24 | { 25 | /* In n>>d, first d bits are 0. 26 | To put last 3 bits of at 27 | first, do bitwise or of n>>d 28 | with n <<(INT_BITS - d) */ 29 | return (n >> d)|(n << (INT_BITS - d)); 30 | } 31 | }; 32 | 33 | /* Driver code*/ 34 | int main() 35 | { 36 | gfg g; 37 | int n = 16; 38 | int d = 2; 39 | cout << "Left Rotation of " << n << 40 | " by " << d << " is "; 41 | cout << g.leftRotate(n, d); 42 | cout << "\nRight Rotation of " << n << 43 | " by " << d << " is "; 44 | cout << g.rightRotate(n, d); 45 | getchar(); 46 | } 47 | 48 | -------------------------------------------------------------------------------- /401.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Compute the minimum 2 | // or maximum of two integers without 3 | // branching 4 | #include 5 | using namespace std; 6 | 7 | class gfg 8 | { 9 | 10 | /*Function to find minimum of x and y*/ 11 | public: 12 | int min(int x, int y) 13 | { 14 | return y ^ ((x ^ y) & -(x < y)); 15 | } 16 | 17 | /*Function to find maximum of x and y*/ 18 | int max(int x, int y) 19 | { 20 | return x ^ ((x ^ y) & -(x < y)); 21 | } 22 | }; 23 | 24 | /* Driver code */ 25 | int main() 26 | { 27 | gfg g; 28 | int x = 15; 29 | int y = 6; 30 | cout << "Minimum of " << x << 31 | " and " << y << " is "; 32 | cout << g. min(x, y); 33 | cout << "\nMaximum of " << x << 34 | " and " << y << " is "; 35 | cout << g.max(x, y); 36 | getchar(); 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /402.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // This function will return n % d. 4 | // d must be one of: 1, 2, 4, 8, 16, 32, … 5 | unsigned int getModulo(unsigned int n, 6 | unsigned int d) 7 | { 8 | return ( n & (d - 1) ); 9 | } 10 | 11 | // Driver Code 12 | int main() 13 | { 14 | unsigned int n = 6; 15 | 16 | // d must be a power of 2 17 | unsigned int d = 4; 18 | printf("%u moduo %u is %u", n, d, getModulo(n, d)); 19 | 20 | getchar(); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /403.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define CHARBIT 8 4 | 5 | /* This function will return absolute value of n*/ 6 | unsigned int getAbs(int n) 7 | { 8 | int const mask = n >> (sizeof(int) * CHARBIT - 1); 9 | return ((n + mask) ^ mask); 10 | } 11 | 12 | /* Driver program to test above function */ 13 | int main() 14 | { 15 | int n = -6; 16 | cout << "Absoute value of " << n << " is " << getAbs(n); 17 | return 0; 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /404.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find whether a given 2 | // number is a power of 4 or not 3 | #include 4 | 5 | using namespace std; 6 | #define bool int 7 | 8 | class GFG 9 | { 10 | 11 | /* Function to check if x is power of 4*/ 12 | public : bool isPowerOfFour(int n) 13 | { 14 | if(n == 0) 15 | return 0; 16 | while(n != 1) 17 | { 18 | if(n % 4 != 0) 19 | return 0; 20 | n = n / 4; 21 | } 22 | return 1; 23 | } 24 | }; 25 | 26 | /*Driver code*/ 27 | int main() 28 | { 29 | GFG g; 30 | int test_no = 64; 31 | if(g.isPowerOfFour(test_no)) 32 | cout << test_no << " is a power of 4"; 33 | else 34 | cout << test_no << "is not a power of 4"; 35 | getchar(); 36 | } 37 | 38 | -------------------------------------------------------------------------------- /405.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // unsets the rightmost set bit 5 | // of n and returns the result 6 | int fun(unsigned int n) 7 | { 8 | return n & (n - 1); 9 | } 10 | 11 | // Driver Code 12 | int main() 13 | { 14 | int n = 7; 15 | cout<<"The number after unsetting the"; 16 | cout<<" rightmost set bit "< 4 | 5 | int multiplyWith3Point5(int x) 6 | { 7 | return (x<<1) + x + (x>>1); 8 | } 9 | 10 | /* Driver program to test above functions*/ 11 | int main() 12 | { 13 | int x = 4; 14 | printf("%d", multiplyWith3Point5(x)); 15 | getchar(); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /407.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to add add 2 | // one to a given number 3 | #include 4 | using namespace std; 5 | 6 | int addOne(int x) 7 | { 8 | int m = 1; 9 | 10 | // Flip all the set bits 11 | // until we find a 0 12 | while( x & m ) 13 | { 14 | x = x ^ m; 15 | m <<= 1; 16 | } 17 | 18 | // flip the rightmost 0 bit 19 | x = x ^ m; 20 | return x; 21 | } 22 | 23 | /* Driver program to test above functions*/ 24 | int main() 25 | { 26 | cout< 2 | 3 | using namespace std; 4 | 5 | typedef unsigned int uint_t; 6 | 7 | // this function returns next higher number with same number of set bits as x. 8 | uint_t snoob(uint_t x) 9 | { 10 | 11 | uint_t rightOne; 12 | uint_t nextHigherOneBit; 13 | uint_t rightOnesPattern; 14 | 15 | uint_t next = 0; 16 | 17 | if(x) 18 | { 19 | 20 | // right most set bit 21 | rightOne = x & -(signed)x; 22 | 23 | // reset the pattern and set next higher bit 24 | // left part of x will be here 25 | nextHigherOneBit = x + rightOne; 26 | 27 | // nextHigherOneBit is now part [D] of the above explanation. 28 | 29 | // isolate the pattern 30 | rightOnesPattern = x ^ nextHigherOneBit; 31 | 32 | // right adjust pattern 33 | rightOnesPattern = (rightOnesPattern)/rightOne; 34 | 35 | // correction factor 36 | rightOnesPattern >>= 2; 37 | 38 | // rightOnesPattern is now part [A] of the above explanation. 39 | 40 | // integrate new pattern (Add [D] and [A]) 41 | next = nextHigherOneBit | rightOnesPattern; 42 | } 43 | 44 | return next; 45 | } 46 | 47 | int main() 48 | { 49 | int x = 156; 50 | cout<<"Next higher number with same number of set bits is "< 2 | using namespace std; 3 | void changeToZero(int a[2]) 4 | { 5 | a[ a[1] ] = a[ !a[1] ]; 6 | } 7 | 8 | // Driver code 9 | int main() 10 | { 11 | int a[] = {1, 0}; 12 | changeToZero(a); 13 | 14 | cout<<"arr[0] = "< 4 | using namespace std; 5 | 6 | int Add(int x, int y) 7 | { 8 | // Iterate till there is no carry 9 | while (y != 0) 10 | { 11 | // carry now contains common 12 | //set bits of x and y 13 | int carry = x & y; 14 | 15 | // Sum of bits of x and y where at 16 | //least one of the bits is not set 17 | x = x ^ y; 18 | 19 | // Carry is shifted by one so that adding 20 | // it to x gives the required sum 21 | y = carry << 1; 22 | } 23 | return x; 24 | } 25 | 26 | // Driver code 27 | int main() 28 | { 29 | cout << Add(15, 32); 30 | return 0; 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /413.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to swap bits 2 | // in a given number 3 | #include 4 | using namespace std; 5 | 6 | int swapBits(unsigned int x, unsigned int p1, 7 | unsigned int p2, unsigned int n) 8 | { 9 | /* Move all bits of first set to rightmost side */ 10 | unsigned int set1 = (x >> p1) & ((1U << n) - 1); 11 | 12 | /* Move all bits of second set to rightmost side */ 13 | unsigned int set2 = (x >> p2) & ((1U << n) - 1); 14 | 15 | /* Xor the two sets */ 16 | unsigned int Xor = (set1 ^ set2); 17 | 18 | /* Put the Xor bits back to their original positions */ 19 | Xor = (Xor << p1) | (Xor << p2); 20 | 21 | /* Xor the 'Xor' with the original number so that the 22 | two sets are swapped */ 23 | unsigned int result = x ^ Xor; 24 | 25 | return result; 26 | } 27 | 28 | /* Driver code*/ 29 | int main() 30 | { 31 | int res = swapBits(28, 0, 3, 2); 32 | cout << "Result = " << res; 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /414.cpp: -------------------------------------------------------------------------------- 1 | // A simple program to count set bits 2 | // in all numbers from 1 to n. 3 | #include 4 | 5 | // A utility function to count set bits 6 | // in a number x 7 | unsigned int countSetBitsUtil(unsigned int x); 8 | 9 | // Returns count of set bits present in all 10 | // numbers from 1 to n 11 | unsigned int countSetBits(unsigned int n) 12 | { 13 | int bitCount = 0; // initialize the result 14 | 15 | for (int i = 1; i <= n; i++) 16 | bitCount += countSetBitsUtil(i); 17 | 18 | return bitCount; 19 | } 20 | 21 | // A utility function to count set bits 22 | // in a number x 23 | unsigned int countSetBitsUtil(unsigned int x) 24 | { 25 | if (x <= 0) 26 | return 0; 27 | return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2); 28 | } 29 | 30 | // Driver program to test above functions 31 | int main() 32 | { 33 | int n = 4; 34 | printf("Total set bit count is %d", countSetBits(n)); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /415.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to Detect 2 | // if two integers have opposite signs. 3 | #include 4 | #include 5 | 6 | bool oppositeSigns(int x, int y) 7 | { 8 | return ((x ^ y) < 0); 9 | } 10 | 11 | int main() 12 | { 13 | int x = 100, y = -100; 14 | if (oppositeSigns(x, y) == true) 15 | printf ("Signs are opposite"); 16 | else 17 | printf ("Signs are not opposite"); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /417.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for the binary 2 | // representation of a given number 3 | #include 4 | using namespace std; 5 | 6 | void bin(long n) 7 | { 8 | long i; 9 | cout << "0"; 10 | for (i = 1 << 30; i > 0; i = i / 2) 11 | { 12 | if((n & i) != 0) 13 | { 14 | cout << "1"; 15 | } 16 | else 17 | { 18 | cout << "0"; 19 | } 20 | } 21 | } 22 | 23 | // Driver Code 24 | int main(void) 25 | { 26 | bin(7); 27 | cout << endl; 28 | bin(4); 29 | } 30 | 31 | -------------------------------------------------------------------------------- /418.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | /* implementation of strcmp that ignores cases */ 4 | int ic_strcmp(string s1, string s2) 5 | { 6 | int i; 7 | for (i = 0; s1[i] && s2[i]; ++i) 8 | { 9 | /* If characters are same or inverting the 10 | 6th bit makes them same */ 11 | if (s1[i] == s2[i] || (s1[i] ^ 32) == s2[i]) 12 | continue; 13 | else 14 | break; 15 | } 16 | 17 | /* Compare the last (or first mismatching in 18 | case of not same) characters */ 19 | if (s1[i] == s2[i]) 20 | return 0; 21 | 22 | // Set the 6th bit in both, then compare 23 | if ((s1[i] | 32) < (s2[i] | 32)) 24 | return -1; 25 | return 1; 26 | } 27 | 28 | // Driver program to test above function 29 | int main() 30 | { 31 | cout<<"ret: "< 4 | using namespace std; 5 | 6 | int findFirstMissing(int array[], 7 | int start, int end) 8 | { 9 | if (start > end) 10 | return end + 1; 11 | 12 | if (start != array[start]) 13 | return start; 14 | 15 | int mid = (start + end) / 2; 16 | 17 | // Left half has all elements 18 | // from 0 to mid 19 | if (array[mid] == mid) 20 | return findFirstMissing(array, 21 | mid+1, end); 22 | 23 | return findFirstMissing(array, start, mid); 24 | } 25 | 26 | // Driver code 27 | int main() 28 | { 29 | int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; 30 | int n = sizeof(arr)/sizeof(arr[0]); 31 | cout << "Smallest missing element is " << 32 | findFirstMissing(arr, 0, n-1) << endl; 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /420.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to swap even and 2 | // odd bits of a given number 3 | #include 4 | using namespace std; 5 | 6 | // Function to swap even 7 | // and odd bits 8 | unsigned int swapBits(unsigned int x) 9 | { 10 | // Get all even bits of x 11 | unsigned int even_bits = x & 0xAAAAAAAA; 12 | 13 | // Get all odd bits of x 14 | unsigned int odd_bits = x & 0x55555555; 15 | 16 | even_bits >>= 1; // Right shift even bits 17 | odd_bits <<= 1; // Left shift odd bits 18 | 19 | return (even_bits | odd_bits); // Combine even and odd bits 20 | } 21 | 22 | // Driver code 23 | int main() 24 | { 25 | unsigned int x = 23; // 00010111 26 | 27 | // Output is 43 (00101011) 28 | cout< 3 | using namespace std; 4 | 5 | // A utility function to check whether n is a power of 2 or not. 6 | // See http://goo.gl/17Arj 7 | int isPowerOfTwo(unsigned n) 8 | { 9 | return n && (!(n & (n - 1))); 10 | } 11 | 12 | // Returns position of the only set bit in 'n' 13 | int findPosition(unsigned n) 14 | { 15 | if (!isPowerOfTwo(n)) 16 | return -1; 17 | 18 | unsigned i = 1, pos = 1; 19 | 20 | // Iterate through bits of n till we find a set bit 21 | // i&n will be non-zero only when 'i' and 'n' have a set bit 22 | // at same position 23 | while (!(i & n)) { 24 | // Unset current bit and set the next bit in 'i' 25 | i = i << 1; 26 | 27 | // increment position 28 | ++pos; 29 | } 30 | 31 | return pos; 32 | } 33 | 34 | // Driver program to test above function 35 | int main(void) 36 | { 37 | int n = 16; 38 | int pos = findPosition(n); 39 | (pos == -1) ? cout << "n = " << n << ", Invalid number" << endl : cout << "n = " << n << ", Position " << pos << endl; 40 | 41 | n = 12; 42 | pos = findPosition(n); 43 | (pos == -1) ? cout << "n = " << n << ", Invalid number" << endl : cout << "n = " << n << ", Position " << pos << endl; 44 | 45 | n = 128; 46 | pos = findPosition(n); 47 | (pos == -1) ? cout << "n = " << n << ", Invalid number" << endl : cout << "n = " << n << ", Position " << pos << endl; 48 | 49 | return 0; 50 | } 51 | 52 | -------------------------------------------------------------------------------- /423.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to swap two numbers without 2 | // using temporary variable 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int x = 10, y = 5; 9 | 10 | // Code to swap 'x' and 'y' 11 | x = x + y; // x now becomes 15 12 | y = x - y; // y becomes 10 13 | x = x - y; // x becomes 5 14 | cout << "After Swapping: x =" << x << ", y=" << y; 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /424.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check if a number 2 | // is multiple of 9 using bitwise operators 3 | #include 4 | using namespace std; 5 | 6 | // Bitwise operator based function to check divisibility by 9 7 | bool isDivBy9(int n) 8 | { 9 | // Base cases 10 | if (n == 0 || n == 9) 11 | return true; 12 | if (n < 9) 13 | return false; 14 | 15 | // If n is greater than 9, then recur for [floor(n/9) - n%8] 16 | return isDivBy9((int)(n >> 3) - (int)(n & 7)); 17 | } 18 | 19 | // Driver program to test above function 20 | int main() 21 | { 22 | // Let us print all multiples of 9 from 0 to 100 23 | // using above method 24 | for (int i = 0; i < 100; i++) 25 | if (isDivBy9(i)) 26 | cout << i << " "; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /425.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to check if n is a multiple of 3 2 | #include 3 | using namespace std; 4 | 5 | /* Function to check if n is a multiple of 3*/ 6 | int isMultipleOf3(int n) 7 | { 8 | int odd_count = 0; 9 | int even_count = 0; 10 | 11 | /* Make no positive if +n is multiple of 3 12 | then is -n. We are doing this to avoid 13 | stack overflow in recursion*/ 14 | if (n < 0) 15 | n = -n; 16 | if (n == 0) 17 | return 1; 18 | if (n == 1) 19 | return 0; 20 | 21 | while (n) { 22 | /* If odd bit is set then 23 | increment odd counter */ 24 | if (n & 1) 25 | odd_count++; 26 | 27 | /* If even bit is set then 28 | increment even counter */ 29 | if (n & 2) 30 | even_count++; 31 | n = n >> 2; 32 | } 33 | 34 | return isMultipleOf3(abs(odd_count - even_count)); 35 | } 36 | 37 | /* Program to test function isMultipleOf3 */ 38 | int main() 39 | { 40 | int num = 24; 41 | if (isMultipleOf3(num)) 42 | printf("%d is multiple of 3", num); 43 | else 44 | printf("%d is not a multiple of 3", num); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /426.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print 2 | // first n Fibonacci numbers 3 | #include 4 | using namespace std; 5 | 6 | // Function to print 7 | // first n Fibonacci Numbers 8 | void printFibonacciNumbers(int n) 9 | { 10 | int f1 = 0, f2 = 1, i; 11 | 12 | if (n < 1) 13 | return; 14 | cout << f1 << " "; 15 | for (i = 1; i < n; i++) { 16 | cout << f2 << " "; 17 | int next = f1 + f2; 18 | f1 = f2; 19 | f2 = next; 20 | } 21 | } 22 | 23 | // Driver Code 24 | int main() 25 | { 26 | printFibonacciNumbers(7); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /427.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to find the area 2 | // of triangle 3 | #include 4 | using namespace std; 5 | 6 | float findArea(float a, float b, float c) 7 | { 8 | // Length of sides must be positive 9 | // and sum of any two sides 10 | // must be smaller than third side. 11 | if (a < 0 || b < 0 || c < 0 || 12 | (a + b <= c) || a + c <= b || 13 | b + c <= a) 14 | { 15 | cout << "Not a valid trianglen"; 16 | exit(0); 17 | } 18 | float s = (a + b + c) / 2; 19 | return sqrt(s * (s - a) * 20 | (s - b) * (s - c)); 21 | } 22 | 23 | // Driver Code 24 | int main() 25 | { 26 | float a = 3.0; 27 | float b = 4.0; 28 | float c = 5.0; 29 | 30 | cout << "Area is " << findArea(a, b, c); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /428.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find sum of series 2 | #include 3 | using namespace std; 4 | 5 | // Function to return sum of 6 | // 1/1 + 1/2 + 1/3 + ..+ 1/n 7 | class gfg 8 | { 9 | 10 | public : double sum(int n) 11 | { 12 | double i, s = 0.0; 13 | for (i = 1; i <= n; i++) 14 | s = s + 1/i; 15 | return s; 16 | } 17 | }; 18 | 19 | // Driver code 20 | int main() 21 | { 22 | gfg g; 23 | int n = 5; 24 | cout << "Sum is " << g.sum(n); 25 | return 0; 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /429.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Lucky Numbers 2 | #include 3 | using namespace std; 4 | #define bool int 5 | 6 | /* Returns 1 if n is a lucky no. 7 | otherwise returns 0*/ 8 | bool isLucky(int n) 9 | { 10 | static int counter = 2; 11 | 12 | /*variable next_position is just for 13 | readability of the program we can 14 | remove it and use n only */ 15 | int next_position = n; 16 | if(counter > n) 17 | return 1; 18 | if(n % counter == 0) 19 | return 0; 20 | 21 | /*calculate next position of input no*/ 22 | next_position -= next_position / counter; 23 | 24 | counter++; 25 | return isLucky(next_position); 26 | } 27 | 28 | // Driver Code 29 | int main() 30 | { 31 | int x = 5; 32 | if( isLucky(x) ) 33 | cout << x << " is a lucky no."; 34 | else 35 | cout << x << " is not a lucky no."; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /43.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to count occurrences of an element 2 | #include 3 | using namespace std; 4 | 5 | // Returns number of times x occurs in arr[0..n-1] 6 | int countOccurrences(int arr[], int n, int x) 7 | { 8 | int res = 0; 9 | for (int i=0; i 2 | using namespace std; 3 | class gfg { 4 | /*Returns the square root of n. Note that the function */ 5 | public: 6 | float squareRoot(float n) 7 | { 8 | /*We are using n itself as initial approximation 9 | This can definitely be improved */ 10 | float x = n; 11 | float y = 1; 12 | float e = 0.000001; /* e decides the accuracy level*/ 13 | while (x - y > e) { 14 | x = (x + y) / 2; 15 | y = n / x; 16 | } 17 | return x; 18 | } 19 | }; 20 | 21 | /* Driver program to test above function*/ 22 | int main() 23 | { 24 | gfg g; 25 | int n = 50; 26 | cout << "Square root of " << n << " is " << g.squareRoot(n); 27 | getchar(); 28 | } 29 | -------------------------------------------------------------------------------- /432.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Multiply two integers without 2 | // using multiplication, division and bitwise 3 | // operators, and no loops 4 | #include 5 | 6 | using namespace std; 7 | class GFG 8 | { 9 | 10 | /* function to multiply two numbers x and y*/ 11 | public : int multiply(int x, int y) 12 | { 13 | /* 0 multiplied with anything gives 0 */ 14 | if(y == 0) 15 | return 0; 16 | 17 | /* Add x one by one */ 18 | if(y > 0 ) 19 | return (x + multiply(x, y-1)); 20 | 21 | /* the case where y is negative */ 22 | if(y < 0 ) 23 | return -multiply(x, -y); 24 | } 25 | }; 26 | 27 | // Driver code 28 | int main() 29 | { 30 | GFG g; 31 | cout << endl << g.multiply(5, -11); 32 | getchar(); 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /433.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Print all 2 | // combinations of points that 3 | // can compose a given number 4 | #define MAX_POINT 3 5 | #define ARR_SIZE 100 6 | #include 7 | using namespace std; 8 | 9 | /* Utility function to print array arr[] */ 10 | void printArray(int arr[], int arr_size); 11 | 12 | /* The function prints all combinations of numbers 1, 2, ...MAX_POINT 13 | that sum up to n. 14 | i is used in recursion keep track of index in arr[] where next 15 | element is to be added. Initital value of i must be passed as 0 */ 16 | void printCompositions(int n, int i) 17 | { 18 | 19 | /* array must be static as we want to keep track 20 | of values stored in arr[] using current calls of 21 | printCompositions() in function call stack*/ 22 | static int arr[ARR_SIZE]; 23 | 24 | if (n == 0) 25 | { 26 | printArray(arr, i); 27 | } 28 | else if(n > 0) 29 | { 30 | int k; 31 | for (k = 1; k <= MAX_POINT; k++) 32 | { 33 | arr[i]= k; 34 | printCompositions(n-k, i+1); 35 | } 36 | } 37 | } 38 | 39 | /* UTILITY FUNCTIONS */ 40 | /* Utility function to print array arr[] */ 41 | void printArray(int arr[], int arr_size) 42 | { 43 | int i; 44 | for (i = 0; i < arr_size; i++) 45 | cout< 3 | using namespace std; 4 | 5 | /* Works only if a >= 0 and b >= 0 */ 6 | int pow(int a, int b) 7 | { 8 | if (b == 0) 9 | return 1; 10 | int answer = a; 11 | int increment = a; 12 | int i, j; 13 | for(i = 1; i < b; i++) 14 | { 15 | for(j = 1; j < a; j++) 16 | { 17 | answer += increment; 18 | } 19 | increment = answer; 20 | } 21 | return answer; 22 | } 23 | 24 | // Driver Code 25 | int main() 26 | { 27 | cout << pow(5, 3); 28 | return 0; 29 | } 30 | 31 | 32 | -------------------------------------------------------------------------------- /435.cpp: -------------------------------------------------------------------------------- 1 | //Fibonacci Series using Recursion 2 | #include 3 | using namespace std; 4 | 5 | int fib(int n) 6 | { 7 | if (n <= 1) 8 | return n; 9 | return fib(n-1) + fib(n-2); 10 | } 11 | 12 | int main () 13 | { 14 | int n = 9; 15 | cout << fib(n); 16 | getchar(); 17 | return 0; 18 | } 19 | 20 | -------------------------------------------------------------------------------- /436.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Returns the new average after including x 4 | float getAvg(float prev_avg, int x, int n) 5 | { 6 | return (prev_avg * n + x) / (n + 1); 7 | } 8 | 9 | // Prints average of a stream of numbers 10 | void streamAvg(float arr[], int n) 11 | { 12 | float avg = 0; 13 | for (int i = 0; i < n; i++) { 14 | avg = getAvg(avg, arr[i], i); 15 | printf("Average of %d numbers is %f \n", i + 1, avg); 16 | } 17 | return; 18 | } 19 | 20 | // Driver program to test above functions 21 | int main() 22 | { 23 | float arr[] = { 10, 20, 30, 40, 50, 60 }; 24 | int n = sizeof(arr) / sizeof(arr[0]); 25 | streamAvg(arr, n); 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /437.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* A utility function to calculate area of triangle formed by (x1, y1), 5 | (x2, y2) and (x3, y3) */ 6 | float area(int x1, int y1, int x2, int y2, int x3, int y3) 7 | { 8 | return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0); 9 | } 10 | 11 | /* A function to check whether point P(x, y) lies inside the triangle formed 12 | by A(x1, y1), B(x2, y2) and C(x3, y3) */ 13 | bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y) 14 | { 15 | /* Calculate area of triangle ABC */ 16 | float A = area (x1, y1, x2, y2, x3, y3); 17 | 18 | /* Calculate area of triangle PBC */ 19 | float A1 = area (x, y, x2, y2, x3, y3); 20 | 21 | /* Calculate area of triangle PAC */ 22 | float A2 = area (x1, y1, x, y, x3, y3); 23 | 24 | /* Calculate area of triangle PAB */ 25 | float A3 = area (x1, y1, x2, y2, x, y); 26 | 27 | /* Check if sum of A1, A2 and A3 is same as A */ 28 | return (A == A1 + A2 + A3); 29 | } 30 | 31 | /* Driver program to test above function */ 32 | int main() 33 | { 34 | /* Let us check whether the point P(10, 15) lies inside the triangle 35 | formed by A(0, 0), B(20, 0) and C(10, 30) */ 36 | if (isInside(0, 0, 20, 0, 10, 30, 10, 15)) 37 | printf ("Inside"); 38 | else 39 | printf ("Not Inside"); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /438.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* returns count of numbers which are 5 | in range from 1 to n and don't contain 3 6 | as a digit */ 7 | int count(int n) 8 | { 9 | // Base cases (Assuming n is not negative) 10 | if (n < 3) 11 | return n; 12 | if (n >= 3 && n < 10) 13 | return n-1; 14 | 15 | // Calculate 10^(d-1) (10 raise to the power d-1) where d is 16 | // number of digits in n. po will be 100 for n = 578 17 | int po = 1; 18 | while (n/po > 9) 19 | po = po*10; 20 | 21 | // find the most significant digit (msd is 5 for 578) 22 | int msd = n/po; 23 | 24 | if (msd != 3) 25 | // For 578, total will be 4*count(10^2 - 1) + 4 + count(78) 26 | return count(msd)*count(po - 1) + count(msd) + count(n%po); 27 | else 28 | // For 35, total will be equal to count(29) 29 | return count(msd*po - 1); 30 | } 31 | 32 | // Driver code 33 | int main() 34 | { 35 | cout << count(578) << " "; 36 | return 0; 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /440.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print all primes 2 | // smaller than or equal to 3 | // n using Sieve of Eratosthenes 4 | #include 5 | using namespace std; 6 | 7 | void SieveOfEratosthenes(int n) 8 | { 9 | // Create a boolean array 10 | // "prime[0..n]" and initialize 11 | // all entries it as true. 12 | // A value in prime[i] will 13 | // finally be false if i is 14 | // Not a prime, else true. 15 | bool prime[n + 1]; 16 | memset(prime, true, sizeof(prime)); 17 | 18 | for (int p = 2; p * p <= n; p++) 19 | { 20 | // If prime[p] is not changed, 21 | // then it is a prime 22 | if (prime[p] == true) 23 | { 24 | // Update all multiples 25 | // of p greater than or 26 | // equal to the square of it 27 | // numbers which are multiple 28 | // of p and are less than p^2 29 | // are already been marked. 30 | for (int i = p * p; i <= n; i += p) 31 | prime[i] = false; 32 | } 33 | } 34 | 35 | // Print all prime numbers 36 | for (int p = 2; p <= n; p++) 37 | if (prime[p]) 38 | cout << p << " "; 39 | } 40 | 41 | // Driver Code 42 | int main() 43 | { 44 | int n = 30; 45 | cout << "Following are the prime numbers smaller " 46 | << " than or equal to " << n << endl; 47 | SieveOfEratosthenes(n); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /441.cpp: -------------------------------------------------------------------------------- 1 | /* A program to find day of a given date */ 2 | #include 3 | using namespace std; 4 | 5 | int dayofweek(int d, int m, int y) 6 | { 7 | static int t[] = { 0, 3, 2, 5, 0, 3, 8 | 5, 1, 4, 6, 2, 4 }; 9 | y -= m < 3; 10 | return ( y + y / 4 - y / 100 + 11 | y / 400 + t[m - 1] + d) % 7; 12 | } 13 | 14 | // Driver Code 15 | int main() 16 | { 17 | int day = dayofweek(30, 8, 2010); 18 | cout << day; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /443.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Generate integer from 2 | // 1 to 5 with equal probability 3 | #include 4 | 5 | // given method that returns 1 to 5 with equal probability 6 | int foo() 7 | { 8 | // some code here 9 | } 10 | 11 | int my_rand() // returns 1 to 7 with equal probability 12 | { 13 | int i; 14 | i = 5*foo() + foo() - 5; 15 | if (i < 22) 16 | return i%7 + 1; 17 | return my_rand(); 18 | } 19 | // Driver code 20 | int main() 21 | { 22 | printf ("%d ", my_rand()); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /445.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int foo() // given method that returns 0 5 | // with 60% probability and 1 with 40% 6 | { 7 | // some code here 8 | } 9 | 10 | // returns both 0 and 1 with 50% probability 11 | int my_fun() 12 | { 13 | int val1 = foo(); 14 | int val2 = foo(); 15 | if (val1 == 0 && val2 == 1) 16 | return 0; // Will reach here with 17 | // 0.24 probability 18 | if (val1 == 1 && val2 == 0) 19 | return 1; // Will reach here with 20 | // 0.24 probability 21 | return my_fun(); // will reach here with 22 | // (1 - 0.24 - 0.24) probability 23 | } 24 | 25 | // Driver Code 26 | int main() 27 | { 28 | cout << my_fun(); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /446.cpp: -------------------------------------------------------------------------------- 1 | // A Program to check whether a number is divisible by 7 2 | #include 3 | using namespace std; 4 | 5 | int isDivisibleBy7( int num ) 6 | { 7 | // If number is negative, make it positive 8 | if( num < 0 ) 9 | return isDivisibleBy7( -num ); 10 | 11 | // Base cases 12 | if( num == 0 || num == 7 ) 13 | return 1; 14 | if( num < 10 ) 15 | return 0; 16 | 17 | // Recur for ( num / 10 - 2 * num % 10 ) 18 | return isDivisibleBy7( num / 10 - 2 * 19 | ( num - num / 10 * 10 ) ); 20 | } 21 | 22 | // Driver code 23 | int main() 24 | { 25 | int num = 616; 26 | if( isDivisibleBy7(num ) ) 27 | cout << "Divisible" ; 28 | else 29 | cout << "Not Divisible" ; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /447.cpp: -------------------------------------------------------------------------------- 1 | // Program to calculate C(n, k) 2 | #include 3 | using namespace std; 4 | 5 | // Returns value of Binomial Coefficient C(n, k) 6 | int binomialCoeff(int n, int k) 7 | { 8 | int res = 1; 9 | 10 | // Since C(n, k) = C(n, n-k) 11 | if (k > n - k) 12 | k = n - k; 13 | 14 | // Calculate value of 15 | // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] 16 | for (int i = 0; i < k; ++i) { 17 | res *= (n - i); 18 | res /= (i + 1); 19 | } 20 | 21 | return res; 22 | } 23 | 24 | // Driver Code 25 | int main() 26 | { 27 | int n = 8, k = 2; 28 | cout << "Value of C(" << n << ", " 29 | << k << ") is " << binomialCoeff(n, k); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /449.cpp: -------------------------------------------------------------------------------- 1 | // C++ code for Pascal's Triangle 2 | #include 3 | 4 | // See https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/ 5 | // for details of this function 6 | int binomialCoeff(int n, int k); 7 | 8 | // Function to print first 9 | // n lines of Pascal's 10 | // Triangle 11 | void printPascal(int n) 12 | { 13 | // Iterate through every line and 14 | // print entries in it 15 | for (int line = 0; line < n; line++) 16 | { 17 | // Every line has number of 18 | // integers equal to line 19 | // number 20 | for (int i = 0; i <= line; i++) 21 | printf("%d ", 22 | binomialCoeff(line, i)); 23 | printf("\n"); 24 | } 25 | } 26 | 27 | // See https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/ 28 | // for details of this function 29 | int binomialCoeff(int n, int k) 30 | { 31 | int res = 1; 32 | if (k > n - k) 33 | k = n - k; 34 | for (int i = 0; i < k; ++i) 35 | { 36 | res *= (n - i); 37 | res /= (i + 1); 38 | } 39 | 40 | return res; 41 | } 42 | 43 | // Driver program 44 | int main() 45 | { 46 | int n = 7; 47 | printPascal(n); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /45.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement recursive Binary Search 2 | #include 3 | using namespace std; 4 | 5 | // A recursive binary search function. It returns 6 | // location of x in given array arr[l..r] is present, 7 | // otherwise -1 8 | int binarySearch(int arr[], int l, int r, int x) 9 | { 10 | if (r >= l) { 11 | int mid = l + (r - l) / 2; 12 | 13 | // If the element is present at the middle 14 | // itself 15 | if (arr[mid] == x) 16 | return mid; 17 | 18 | // If element is smaller than mid, then 19 | // it can only be present in left subarray 20 | if (arr[mid] > x) 21 | return binarySearch(arr, l, mid - 1, x); 22 | 23 | // Else the element can only be present 24 | // in right subarray 25 | return binarySearch(arr, mid + 1, r, x); 26 | } 27 | 28 | // We reach here when element is not 29 | // present in array 30 | return -1; 31 | } 32 | 33 | int main(void) 34 | { 35 | int arr[] = { 2, 3, 4, 10, 40 }; 36 | int x = 10; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | int result = binarySearch(arr, 0, n - 1, x); 39 | (result == -1) ? cout << "Element is not present in array" 40 | : cout << "Element is present at index " << result; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /450.cpp: -------------------------------------------------------------------------------- 1 | // An efficient C++ program to randomly select 2 | // a number from stream of numbers. 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // A function to randomly select a item 8 | // from stream[0], stream[1], .. stream[i-1] 9 | int selectRandom(int x) 10 | { 11 | static int res; // The resultant random number 12 | static int count = 0; // Count of numbers visited 13 | // so far in stream 14 | 15 | count++; // increment count of numbers seen so far 16 | 17 | // If this is the first element from stream, 18 | // return it 19 | if (count == 1) 20 | res = x; 21 | else 22 | { 23 | // Generate a random number from 0 to count - 1 24 | int i = rand() % count; 25 | 26 | // Replace the prev random number with 27 | // new number with 1/count probability 28 | if (i == count - 1) 29 | res = x; 30 | } 31 | return res; 32 | } 33 | 34 | // Driver Code 35 | int main() 36 | { 37 | int stream[] = {1, 2, 3, 4}; 38 | int n = sizeof(stream) / sizeof(stream[0]); 39 | 40 | // Use a different seed value for every run. 41 | srand(time(NULL)); 42 | for (int i = 0; i < n; ++i) 43 | cout << "Random number from first " << i + 1 44 | << " numbers is " << selectRandom(stream[i]) << endl; 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /451.cpp: -------------------------------------------------------------------------------- 1 | // C++ Efficient program to calculate 2 | // e raise to the power x 3 | #include 4 | using namespace std; 5 | 6 | // Returns approximate value of e^x 7 | // using sum of first n terms of Taylor Series 8 | float exponential(int n, float x) 9 | { 10 | float sum = 1.0f; // initialize sum of series 11 | 12 | for (int i = n - 1; i > 0; --i ) 13 | sum = 1 + x * sum / i; 14 | 15 | return sum; 16 | } 17 | 18 | // Driver code 19 | int main() 20 | { 21 | int n = 10; 22 | float x = 1.0f; 23 | cout << "e^x = " << fixed << setprecision(5) << exponential(n, x); 24 | return 0; 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /453.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print all prime factors 2 | #include 3 | using namespace std; 4 | 5 | // A function to print all prime 6 | // factors of a given number n 7 | void primeFactors(int n) 8 | { 9 | // Print the number of 2s that divide n 10 | while (n % 2 == 0) 11 | { 12 | cout << 2 << " "; 13 | n = n/2; 14 | } 15 | 16 | // n must be odd at this point. So we can skip 17 | // one element (Note i = i +2) 18 | for (int i = 3; i <= sqrt(n); i = i + 2) 19 | { 20 | // While i divides n, print i and divide n 21 | while (n % i == 0) 22 | { 23 | cout << i << " "; 24 | n = n/i; 25 | } 26 | } 27 | 28 | // This condition is to handle the case when n 29 | // is a prime number greater than 2 30 | if (n > 2) 31 | cout << n << " "; 32 | } 33 | 34 | /* Driver code */ 35 | int main() 36 | { 37 | int n = 315; 38 | primeFactors(n); 39 | return 0; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /459.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check if x is a perfect square 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // A utility function that returns true if x is perfect square 7 | bool isPerfectSquare(int x) 8 | { 9 | int s = sqrt(x); 10 | return (s*s == x); 11 | } 12 | 13 | // Returns true if n is a Fibinacci Number, else false 14 | bool isFibonacci(int n) 15 | { 16 | // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both 17 | // is a perferct square 18 | return isPerfectSquare(5*n*n + 4) || 19 | isPerfectSquare(5*n*n - 4); 20 | } 21 | 22 | // A utility function to test above functions 23 | int main() 24 | { 25 | for (int i = 1; i <= 10; i++) 26 | isFibonacci(i)? cout << i << " is a Fibonacci Number \n": 27 | cout << i << " is a not Fibonacci Number \n" ; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /46.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of selection sort 2 | #include 3 | using namespace std; 4 | 5 | void swap(int *xp, int *yp) 6 | { 7 | int temp = *xp; 8 | *xp = *yp; 9 | *yp = temp; 10 | } 11 | 12 | void selectionSort(int arr[], int n) 13 | { 14 | int i, j, min_idx; 15 | 16 | // One by one move boundary of unsorted subarray 17 | for (i = 0; i < n-1; i++) 18 | { 19 | // Find the minimum element in unsorted array 20 | min_idx = i; 21 | for (j = i+1; j < n; j++) 22 | if (arr[j] < arr[min_idx]) 23 | min_idx = j; 24 | 25 | // Swap the found minimum element with the first element 26 | swap(&arr[min_idx], &arr[i]); 27 | } 28 | } 29 | 30 | /* Function to print an array */ 31 | void printArray(int arr[], int size) 32 | { 33 | int i; 34 | for (i=0; i < size; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver program to test above functions 40 | int main() 41 | { 42 | int arr[] = {64, 25, 12, 22, 11}; 43 | int n = sizeof(arr)/sizeof(arr[0]); 44 | selectionSort(arr, n); 45 | cout << "Sorted array: \n"; 46 | printArray(arr, n); 47 | return 0; 48 | } 49 | 50 | 51 | -------------------------------------------------------------------------------- /460.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A method to multiply two numbers using Russian Peasant method 5 | unsigned int russianPeasant(unsigned int a, unsigned int b) 6 | { 7 | int res = 0; // initialize result 8 | 9 | // While second number doesn't become 1 10 | while (b > 0) 11 | { 12 | // If second number becomes odd, add the first number to result 13 | if (b & 1) 14 | res = res + a; 15 | 16 | // Double the first number and halve the second number 17 | a = a << 1; 18 | b = b >> 1; 19 | } 20 | return res; 21 | } 22 | 23 | // Driver program to test above function 24 | int main() 25 | { 26 | cout << russianPeasant(18, 1) << endl; 27 | cout << russianPeasant(20, 12) << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /461.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to demonstrate to draw 2 | // circle without floating 3 | // point arithmetic 4 | #include 5 | 6 | void drawCircle(int r) 7 | { 8 | // Consider a rectangle of size N*N 9 | int N = 2*r+1; 10 | 11 | int x, y; // Coordinates inside the rectangle 12 | 13 | // Draw a square of size N*N. 14 | for (int i = 0; i < N; i++) 15 | { 16 | for (int j = 0; j < N; j++) 17 | { 18 | // Start from the left most corner point 19 | x = i-r; 20 | y = j-r; 21 | 22 | // If this point is inside the circle, print it 23 | if (x*x + y*y <= r*r+1 ) 24 | printf("."); 25 | else // If outside the circle, print space 26 | printf(" "); 27 | printf(" "); 28 | } 29 | printf("\n"); 30 | } 31 | } 32 | 33 | // Driver Program to test above function 34 | int main() 35 | { 36 | drawCircle(8); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /462.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A function to check if n is palindrome 5 | int isPalindrome(int n) 6 | { 7 | // Find reverse of n 8 | int rev = 0; 9 | for (int i = n; i > 0; i /= 10) 10 | rev = rev*10 + i%10; 11 | 12 | // If n and rev are same, then n is palindrome 13 | return (n==rev); 14 | } 15 | 16 | // prints palindrome between min and max 17 | void countPal(int min, int max) 18 | { 19 | for (int i = min; i <= max; i++) 20 | if (isPalindrome(i)) 21 | cout << i << " "; 22 | } 23 | 24 | // Driver program to test above function 25 | int main() 26 | { 27 | countPal(100, 2000); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /463.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print largest contiguous array sum 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int maxSubArraySum(int a[], int size) 7 | { 8 | int max_so_far = INT_MIN, max_ending_here = 0; 9 | 10 | for (int i = 0; i < size; i++) 11 | { 12 | max_ending_here = max_ending_here + a[i]; 13 | if (max_so_far < max_ending_here) 14 | max_so_far = max_ending_here; 15 | 16 | if (max_ending_here < 0) 17 | max_ending_here = 0; 18 | } 19 | return max_so_far; 20 | } 21 | 22 | /*Driver program to test maxSubArraySum*/ 23 | int main() 24 | { 25 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 26 | int n = sizeof(a)/sizeof(a[0]); 27 | int max_sum = maxSubArraySum(a, n); 28 | cout << "Maximum contiguous sum is " << max_sum; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /464.cpp: -------------------------------------------------------------------------------- 1 | // CPP program to find nth ugly number 2 | #include 3 | #include 4 | 5 | // This function divides a by greatest divisible 6 | // power of b 7 | int maxDivide(int a, int b) 8 | { 9 | while (a % b == 0) 10 | a = a / b; 11 | return a; 12 | } 13 | 14 | // Function to check if a number is ugly or not 15 | int isUgly(int no) 16 | { 17 | no = maxDivide(no, 2); 18 | no = maxDivide(no, 3); 19 | no = maxDivide(no, 5); 20 | 21 | return (no == 1) ? 1 : 0; 22 | } 23 | 24 | // Function to get the nth ugly number 25 | int getNthUglyNo(int n) 26 | { 27 | 28 | int i = 1; 29 | 30 | // ugly number count 31 | int count = 1; 32 | 33 | // Check for all integers untill ugly count 34 | // becomes n 35 | while (n > count) { 36 | i++; 37 | if (isUgly(i)) 38 | count++; 39 | } 40 | return i; 41 | } 42 | 43 | // Driver Code 44 | int main() 45 | { 46 | // Function call 47 | unsigned no = getNthUglyNo(150); 48 | printf("150th ugly no. is %d ", no); 49 | getchar(); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /466.cpp: -------------------------------------------------------------------------------- 1 | /* C++ program for Memoized version 2 | for nth Fibonacci number */ 3 | #include 4 | using namespace std; 5 | #define NIL -1 6 | #define MAX 100 7 | 8 | int lookup[MAX]; 9 | 10 | /* Function to initialize NIL 11 | values in lookup table */ 12 | void _initialize() 13 | { 14 | int i; 15 | for (i = 0; i < MAX; i++) 16 | lookup[i] = NIL; 17 | } 18 | 19 | /* function for nth Fibonacci number */ 20 | int fib(int n) 21 | { 22 | if (lookup[n] == NIL) 23 | { 24 | if (n <= 1) 25 | lookup[n] = n; 26 | else 27 | lookup[n] = fib(n - 1) + fib(n - 2); 28 | } 29 | 30 | return lookup[n]; 31 | } 32 | 33 | // Driver code 34 | int main () 35 | { 36 | int n = 40; 37 | _initialize(); 38 | cout << "Fibonacci number is " << fib(n); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /468.cpp: -------------------------------------------------------------------------------- 1 | /* A Naive recursive implementation of LCS problem */ 2 | #include 3 | using namespace std; 4 | 5 | int max(int a, int b); 6 | 7 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 8 | int lcs( char *X, char *Y, int m, int n ) 9 | { 10 | if (m == 0 || n == 0) 11 | return 0; 12 | if (X[m-1] == Y[n-1]) 13 | return 1 + lcs(X, Y, m-1, n-1); 14 | else 15 | return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 16 | } 17 | 18 | /* Utility function to get max of 2 integers */ 19 | int max(int a, int b) 20 | { 21 | return (a > b)? a : b; 22 | } 23 | 24 | /* Driver code */ 25 | int main() 26 | { 27 | char X[] = "AGGTAB"; 28 | char Y[] = "GXTXAYB"; 29 | 30 | int m = strlen(X); 31 | int n = strlen(Y); 32 | 33 | cout<<"Length of LCS is "<< lcs( X, Y, m, n ) ; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /469.cpp: -------------------------------------------------------------------------------- 1 | // A Naive recursive C++ program to find minimum number 2 | // operations to convert str1 to str2 3 | #include 4 | using namespace std; 5 | 6 | // Utility function to find minimum of three numbers 7 | int min(int x, int y, int z) { return min(min(x, y), z); } 8 | 9 | int editDist(string str1, string str2, int m, int n) 10 | { 11 | // If first string is empty, the only option is to 12 | // insert all characters of second string into first 13 | if (m == 0) 14 | return n; 15 | 16 | // If second string is empty, the only option is to 17 | // remove all characters of first string 18 | if (n == 0) 19 | return m; 20 | 21 | // If last characters of two strings are same, nothing 22 | // much to do. Ignore last characters and get count for 23 | // remaining strings. 24 | if (str1[m - 1] == str2[n - 1]) 25 | return editDist(str1, str2, m - 1, n - 1); 26 | 27 | // If last characters are not same, consider all three 28 | // operations on last character of first string, 29 | // recursively compute minimum cost for all three 30 | // operations and take minimum of three values. 31 | return 1 32 | + min(editDist(str1, str2, m, n - 1), // Insert 33 | editDist(str1, str2, m - 1, n), // Remove 34 | editDist(str1, str2, m - 1, 35 | n - 1) // Replace 36 | ); 37 | } 38 | 39 | // Driver code 40 | int main() 41 | { 42 | // your code goes here 43 | string str1 = "sunday"; 44 | string str2 = "saturday"; 45 | 46 | cout << editDist(str1, str2, str1.length(), 47 | str2.length()); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /47.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation of Bubble sort 2 | #include 3 | using namespace std; 4 | 5 | void swap(int *xp, int *yp) 6 | { 7 | int temp = *xp; 8 | *xp = *yp; 9 | *yp = temp; 10 | } 11 | 12 | // A function to implement bubble sort 13 | void bubbleSort(int arr[], int n) 14 | { 15 | int i, j; 16 | for (i = 0; i < n-1; i++) 17 | 18 | // Last i elements are already in place 19 | for (j = 0; j < n-i-1; j++) 20 | if (arr[j] > arr[j+1]) 21 | swap(&arr[j], &arr[j+1]); 22 | } 23 | 24 | /* Function to print an array */ 25 | void printArray(int arr[], int size) 26 | { 27 | int i; 28 | for (i = 0; i < size; i++) 29 | cout << arr[i] << " "; 30 | cout << endl; 31 | } 32 | 33 | // Driver code 34 | int main() 35 | { 36 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 37 | int n = sizeof(arr)/sizeof(arr[0]); 38 | bubbleSort(arr, n); 39 | cout<<"Sorted array: \n"; 40 | printArray(arr, n); 41 | return 0; 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /470.cpp: -------------------------------------------------------------------------------- 1 | // A Naive recursive implementation 2 | // of MCP(Minimum Cost Path) problem 3 | #include 4 | using namespace std; 5 | 6 | #define R 3 7 | #define C 3 8 | 9 | int min(int x, int y, int z); 10 | 11 | // Returns cost of minimum cost path 12 | // from (0,0) to (m, n) in mat[R][C] 13 | int minCost(int cost[R][C], int m, int n) 14 | { 15 | if (n < 0 || m < 0) 16 | return INT_MAX; 17 | else if (m == 0 && n == 0) 18 | return cost[m][n]; 19 | else 20 | return cost[m][n] + 21 | min(minCost(cost, m - 1, n - 1), 22 | minCost(cost, m - 1, n), 23 | minCost(cost, m, n - 1)); 24 | } 25 | 26 | // A utility function that returns 27 | // minimum of 3 integers 28 | int min(int x, int y, int z) 29 | { 30 | if (x < y) 31 | return (x < z) ? x : z; 32 | else 33 | return (y < z) ? y : z; 34 | } 35 | 36 | // Driver code 37 | int main() 38 | { 39 | int cost[R][C] = { { 1, 2, 3 }, 40 | { 4, 8, 2 }, 41 | { 1, 5, 3 } }; 42 | 43 | cout << minCost(cost, 2, 2) << endl; 44 | 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /471.cpp: -------------------------------------------------------------------------------- 1 | // Recursive C program for 2 | // coin change problem. 3 | #include 4 | 5 | // Returns the count of ways we can 6 | // sum S[0...m-1] coins to get sum n 7 | int count( int S[], int m, int n ) 8 | { 9 | // If n is 0 then there is 1 solution 10 | // (do not include any coin) 11 | if (n == 0) 12 | return 1; 13 | 14 | // If n is less than 0 then no 15 | // solution exists 16 | if (n < 0) 17 | return 0; 18 | 19 | // If there are no coins and n 20 | // is greater than 0, then no 21 | // solution exist 22 | if (m <=0 && n >= 1) 23 | return 0; 24 | 25 | // count is sum of solutions (i) 26 | // including S[m-1] (ii) excluding S[m-1] 27 | return count( S, m - 1, n ) + count( S, m, n-S[m-1] ); 28 | } 29 | 30 | // Driver program to test above function 31 | int main() 32 | { 33 | int i, j; 34 | int arr[] = {1, 2, 3}; 35 | int m = sizeof(arr)/sizeof(arr[0]); 36 | printf("%d ", count(arr, m, 4)); 37 | getchar(); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /472.cpp: -------------------------------------------------------------------------------- 1 | /* A naive recursive implementation that simply 2 | follows the above optimal substructure property */ 3 | #include 4 | using namespace std; 5 | 6 | // Matrix Ai has dimension p[i-1] x p[i] 7 | // for i = 1..n 8 | int MatrixChainOrder(int p[], int i, int j) 9 | { 10 | if (i == j) 11 | return 0; 12 | int k; 13 | int min = INT_MAX; 14 | int count; 15 | 16 | // place parenthesis at different places 17 | // between first and last matrix, recursively 18 | // calculate count of multiplications for 19 | // each parenthesis placement and return the 20 | // minimum count 21 | for (k = i; k < j; k++) 22 | { 23 | count = MatrixChainOrder(p, i, k) 24 | + MatrixChainOrder(p, k + 1, j) 25 | + p[i - 1] * p[k] * p[j]; 26 | 27 | if (count < min) 28 | min = count; 29 | } 30 | 31 | // Return minimum count 32 | return min; 33 | } 34 | 35 | // Driver Code 36 | int main() 37 | { 38 | int arr[] = { 1, 2, 3, 4, 3 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | cout << "Minimum number of multiplications is " 42 | << MatrixChainOrder(arr, 1, n - 1); 43 | } 44 | -------------------------------------------------------------------------------- /473.cpp: -------------------------------------------------------------------------------- 1 | // A naive recursive C++ implementation 2 | #include 3 | using namespace std; 4 | 5 | // Returns value of Binomial Coefficient C(n, k) 6 | int binomialCoeff(int n, int k) 7 | { 8 | // Base Cases 9 | if (k > n) 10 | return 0; 11 | if (k == 0 || k == n) 12 | return 1; 13 | 14 | // Recur 15 | return binomialCoeff(n - 1, k - 1) 16 | + binomialCoeff(n - 1, k); 17 | } 18 | 19 | /* Driver code*/ 20 | int main() 21 | { 22 | int n = 5, k = 2; 23 | cout << "Value of C(" << n << ", " << k << ") is " 24 | << binomialCoeff(n, k); 25 | return 0; 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /474.cpp: -------------------------------------------------------------------------------- 1 | /* A Naive recursive implementation of 2 | 0-1 Knapsack problem */ 3 | #include 4 | using namespace std; 5 | 6 | // A utility function that returns 7 | // maximum of two integers 8 | int max(int a, int b) { return (a > b) ? a : b; } 9 | 10 | // Returns the maximum value that 11 | // can be put in a knapsack of capacity W 12 | int knapSack(int W, int wt[], int val[], int n) 13 | { 14 | 15 | // Base Case 16 | if (n == 0 || W == 0) 17 | return 0; 18 | 19 | // If weight of the nth item is more 20 | // than Knapsack capacity W, then 21 | // this item cannot be included 22 | // in the optimal solution 23 | if (wt[n - 1] > W) 24 | return knapSack(W, wt, val, n - 1); 25 | 26 | // Return the maximum of two cases: 27 | // (1) nth item included 28 | // (2) not included 29 | else 30 | return max( 31 | val[n - 1] 32 | + knapSack(W - wt[n - 1], 33 | wt, val, n - 1), 34 | knapSack(W, wt, val, n - 1)); 35 | } 36 | 37 | // Driver code 38 | int main() 39 | { 40 | int val[] = { 60, 100, 120 }; 41 | int wt[] = { 10, 20, 30 }; 42 | int W = 50; 43 | int n = sizeof(val) / sizeof(val[0]); 44 | cout << knapSack(W, wt, val, n); 45 | return 0; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /475.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A utility function to get 5 | // maximum of two integers 6 | int max(int a, int b) 7 | { 8 | return (a > b) ? a : b; 9 | } 10 | 11 | // Function to get minimum 12 | // number of trials needed in worst 13 | // case with n eggs and k floors 14 | int eggDrop(int n, int k) 15 | { 16 | // If there are no floors, 17 | // then no trials needed. 18 | // OR if there is one floor, 19 | // one trial needed. 20 | if (k == 1 || k == 0) 21 | return k; 22 | 23 | // We need k trials for one 24 | // egg and k floors 25 | if (n == 1) 26 | return k; 27 | 28 | int min = INT_MAX, x, res; 29 | 30 | // Consider all droppings from 31 | // 1st floor to kth floor and 32 | // return the minimum of these 33 | // values plus 1. 34 | for (x = 1; x <= k; x++) { 35 | res = max( 36 | eggDrop(n - 1, x - 1), 37 | eggDrop(n, k - x)); 38 | if (res < min) 39 | min = res; 40 | } 41 | 42 | return min + 1; 43 | } 44 | 45 | // Driver program to test 46 | // to pront printDups 47 | int main() 48 | { 49 | int n = 2, k = 10; 50 | cout << "Minimum number of trials " 51 | "in worst case with " 52 | << n << " eggs and " << k 53 | << " floors is " 54 | << eggDrop(n, k) << endl; 55 | return 0; 56 | } 57 | 58 | -------------------------------------------------------------------------------- /476.cpp: -------------------------------------------------------------------------------- 1 | // C++ program of above approach 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to get max of two integers 6 | int max (int x, int y) { return (x > y)? x : y; } 7 | 8 | // Returns the length of the longest palindromic subsequence in seq 9 | int lps(char *seq, int i, int j) 10 | { 11 | // Base Case 1: If there is only 1 character 12 | if (i == j) 13 | return 1; 14 | 15 | // Base Case 2: If there are only 2 16 | // characters and both are same 17 | if (seq[i] == seq[j] && i + 1 == j) 18 | return 2; 19 | 20 | // If the first and last characters match 21 | if (seq[i] == seq[j]) 22 | return lps (seq, i+1, j-1) + 2; 23 | 24 | // If the first and last characters do not match 25 | return max( lps(seq, i, j-1), lps(seq, i+1, j) ); 26 | } 27 | 28 | /* Driver program to test above functions */ 29 | int main() 30 | { 31 | char seq[] = "GEEKSFORGEEKS"; 32 | int n = strlen(seq); 33 | cout << "The length of the LPS is " 34 | << lps(seq, 0, n-1); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /477.cpp: -------------------------------------------------------------------------------- 1 | // A Naive recursive solution for Rod cutting problem 2 | #include 3 | #include 4 | 5 | // A utility function to get the maximum of two integers 6 | int max(int a, int b) { return (a > b)? a : b;} 7 | 8 | /* Returns the best obtainable price for a rod of length n and 9 | price[] as prices of different pieces */ 10 | int cutRod(int price[], int n) 11 | { 12 | if (n <= 0) 13 | return 0; 14 | int max_val = INT_MIN; 15 | 16 | // Recursively cut the rod in different pieces and compare different 17 | // configurations 18 | for (int i = 0; i 4 | using namespace std; 5 | 6 | bool isPalindrome(string String, int i, int j) 7 | { 8 | while(i < j) 9 | { 10 | if(String[i] != String[j]) 11 | return false; 12 | i++; 13 | j--; 14 | } 15 | return true; 16 | } 17 | int minPalPartion(string String, int i, int j) 18 | { 19 | if( i >= j || isPalindrome(String, i, j) ) 20 | return 0; 21 | int ans = INT_MAX, count; 22 | for(int k = i; k < j; k++) 23 | { 24 | count = minPalPartion(String, i, k) + 25 | minPalPartion(String, k + 1, j) + 1; 26 | 27 | ans = min(ans, count); 28 | } 29 | return ans; 30 | } 31 | 32 | // Driver code 33 | int main() { 34 | string str = "ababbbabbababa"; 35 | cout << "Min cuts needed for " << 36 | "Palindrome Partitioning is " << 37 | minPalPartion(str, 0, str.length() - 1) << endl; 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /48.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | #include 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | // A utility function to print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /482.cpp: -------------------------------------------------------------------------------- 1 | // A recursive solution for subset sum problem 2 | #include 3 | 4 | // Returns true if there is a subset 5 | // of set[] with sum equal to given sum 6 | bool isSubsetSum(int set[], int n, int sum) 7 | { 8 | // Base Cases 9 | if (sum == 0) 10 | return true; 11 | if (n == 0) 12 | return false; 13 | 14 | // If last element is greater than sum, 15 | // then ignore it 16 | if (set[n - 1] > sum) 17 | return isSubsetSum(set, n - 1, sum); 18 | 19 | /* else, check if sum can be obtained by any 20 | of the following: 21 | (a) including the last element 22 | (b) excluding the last element */ 23 | return isSubsetSum(set, n - 1, sum) 24 | || isSubsetSum(set, n - 1, sum - set[n - 1]); 25 | } 26 | 27 | // Driver code 28 | int main() 29 | { 30 | int set[] = { 3, 34, 4, 12, 5, 2 }; 31 | int sum = 9; 32 | int n = sizeof(set) / sizeof(set[0]); 33 | if (isSubsetSum(set, n, sum) == true) 34 | printf("Found a subset with given sum"); 35 | else 36 | printf("No subset with given sum"); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /483.cpp: -------------------------------------------------------------------------------- 1 | // A Naive recursive program to find minimum 2 | // number insertions needed to make a string 3 | // palindrome 4 | #include 5 | using namespace std; 6 | 7 | 8 | // Recursive function to find 9 | // minimum number of insertions 10 | int findMinInsertions(char str[], int l, int h) 11 | { 12 | // Base Cases 13 | if (l > h) return INT_MAX; 14 | if (l == h) return 0; 15 | if (l == h - 1) return (str[l] == str[h])? 0 : 1; 16 | 17 | // Check if the first and last characters are 18 | // same. On the basis of the comparison result, 19 | // decide which subrpoblem(s) to call 20 | return (str[l] == str[h])? 21 | findMinInsertions(str, l + 1, h - 1): 22 | (min(findMinInsertions(str, l, h - 1), 23 | findMinInsertions(str, l + 1, h)) + 1); 24 | } 25 | 26 | // Driver code 27 | int main() 28 | { 29 | char str[] = "geeks"; 30 | cout << findMinInsertions(str, 0, strlen(str) - 1); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /487.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to find minimum possible 2 | // time by the car chassis to complete 3 | #include 4 | using namespace std; 5 | #define NUM_LINE 2 6 | #define NUM_STATION 4 7 | 8 | // Utility function to find a minimum of two numbers 9 | int min(int a, int b) 10 | { 11 | return a < b ? a : b; 12 | } 13 | 14 | int carAssembly(int a[][NUM_STATION], 15 | int t[][NUM_STATION], 16 | int *e, int *x) 17 | { 18 | int T1[NUM_STATION], T2[NUM_STATION], i; 19 | 20 | // time taken to leave first station in line 1 21 | T1[0] = e[0] + a[0][0]; 22 | 23 | // time taken to leave first station in line 2 24 | T2[0] = e[1] + a[1][0]; 25 | 26 | // Fill tables T1[] and T2[] using the 27 | // above given recursive relations 28 | for (i = 1; i < NUM_STATION; ++i) 29 | { 30 | T1[i] = min(T1[i - 1] + a[0][i], 31 | T2[i - 1] + t[1][i] + a[0][i]); 32 | T2[i] = min(T2[i - 1] + a[1][i], 33 | T1[i - 1] + t[0][i] + a[1][i]); 34 | } 35 | 36 | // Consider exit times and retutn minimum 37 | return min(T1[NUM_STATION - 1] + x[0], 38 | T2[NUM_STATION - 1] + x[1]); 39 | } 40 | 41 | // Driver Code 42 | int main() 43 | { 44 | int a[][NUM_STATION] = {{4, 5, 3, 2}, 45 | {2, 10, 1, 4}}; 46 | int t[][NUM_STATION] = {{0, 7, 4, 5}, 47 | {0, 9, 2, 8}}; 48 | int e[] = {10, 12}, x[] = {18, 7}; 49 | 50 | cout << carAssembly(a, t, e, x); 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /489.cpp: -------------------------------------------------------------------------------- 1 | // A Naive Recursive method to find maximum product 2 | #include 3 | using namespace std; 4 | 5 | // Utility function to get the maximum of two and three integers 6 | int max(int a, int b) { return (a > b)? a : b;} 7 | int max(int a, int b, int c) { return max(a, max(b, c));} 8 | 9 | // The main function that returns maximum product obtainable 10 | // from a rope of length n 11 | int maxProd(int n) 12 | { 13 | // Base cases 14 | if (n == 0 || n == 1) return 0; 15 | 16 | // Make a cut at different places and take the maximum of all 17 | int max_val = 0; 18 | for (int i = 1; i < n; i++) 19 | max_val = max(max_val, i*(n-i), maxProd(n-i)*i); 20 | 21 | // Return the maximum of all values 22 | return max_val; 23 | } 24 | 25 | /* Driver program to test above functions */ 26 | int main() 27 | { 28 | cout << "Maximum Product is " << maxProd(10); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /490.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for activity selection problem. 2 | // The following implementation assumes that the activities 3 | // are already sorted according to their finish time 4 | #include 5 | using namespace std; 6 | 7 | // Prints a maximum set of activities that can be done by a single 8 | // person, one at a time. 9 | // n --> Total number of activities 10 | // s[] --> An array that contains start time of all activities 11 | // f[] --> An array that contains finish time of all activities 12 | void printMaxActivities(int s[], int f[], int n) 13 | { 14 | int i, j; 15 | 16 | cout <<"Following activities are selected "<< endl; 17 | 18 | // The first activity always gets selected 19 | i = 0; 20 | cout <<" "<< i; 21 | 22 | // Consider rest of the activities 23 | for (j = 1; j < n; j++) 24 | { 25 | // If this activity has start time greater than or 26 | // equal to the finish time of previously selected 27 | // activity, then select it 28 | if (s[j] >= f[i]) 29 | { 30 | cout <<" " << j; 31 | i = j; 32 | } 33 | } 34 | } 35 | 36 | // driver program to test above function 37 | int main() 38 | { 39 | int s[] = {1, 3, 0, 5, 8, 5}; 40 | int f[] = {2, 4, 6, 7, 9, 9}; 41 | int n = sizeof(s)/sizeof(s[0]); 42 | printMaxActivities(s, f, n); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /499.cpp: -------------------------------------------------------------------------------- 1 | // C++ recursive function to 2 | // solve tower of hanoi puzzle 3 | #include 4 | using namespace std; 5 | 6 | void towerOfHanoi(int n, char from_rod, 7 | char to_rod, char aux_rod) 8 | { 9 | if (n == 1) 10 | { 11 | cout << "Move disk 1 from rod " << from_rod << 12 | " to rod " << to_rod< 4 | using namespace std; 5 | 6 | // Function to find Majority element 7 | // in an array 8 | void findMajority(int arr[], int n) 9 | { 10 | int maxCount = 0; 11 | int index = -1; // sentinels 12 | for (int i = 0; i < n; i++) { 13 | int count = 0; 14 | for (int j = 0; j < n; j++) { 15 | if (arr[i] == arr[j]) 16 | count++; 17 | } 18 | 19 | // update maxCount if count of 20 | // current element is greater 21 | if (count > maxCount) { 22 | maxCount = count; 23 | index = i; 24 | } 25 | } 26 | 27 | // if maxCount is greater than n/2 28 | // return the corresponding element 29 | if (maxCount > n / 2) 30 | cout << arr[index] << endl; 31 | 32 | else 33 | cout << "No Majority Element" << endl; 34 | } 35 | 36 | // Driver code 37 | int main() 38 | { 39 | int arr[] = { 1, 1, 2, 1, 3, 5, 1 }; 40 | int n = sizeof(arr) / sizeof(arr[0]); 41 | 42 | // Function calling 43 | findMajority(arr, n); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /500.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | struct dirent *de; // Pointer for directory entry 7 | 8 | // opendir() returns a pointer of DIR type. 9 | DIR *dr = opendir("."); 10 | 11 | if (dr == NULL) // opendir returns NULL if couldn't open directory 12 | { 13 | printf("Could not open current directory" ); 14 | return 0; 15 | } 16 | 17 | // Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html 18 | // for readdir() 19 | while ((de = readdir(dr)) != NULL) 20 | printf("%s\n", de->d_name); 21 | 22 | closedir(dr); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /52.cpp: -------------------------------------------------------------------------------- 1 | // CPP program for the above approach 2 | #include 3 | using namespace std; 4 | 5 | /* For a given array arr[], 6 | returns the maximum j – i such 7 | that arr[j] > arr[i] */ 8 | int maxIndexDiff(int arr[], int n) 9 | { 10 | int maxDiff = -1; 11 | int i, j; 12 | 13 | for (i = 0; i < n; ++i) { 14 | for (j = n - 1; j > i; --j) { 15 | if (arr[j] > arr[i] && maxDiff < (j - i)) 16 | maxDiff = j - i; 17 | } 18 | } 19 | 20 | return maxDiff; 21 | } 22 | 23 | int main() 24 | { 25 | int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 }; 26 | int n = sizeof(arr) / sizeof(arr[0]); 27 | int maxDiff = maxIndexDiff(arr, n); 28 | cout << "\n" << maxDiff; 29 | return 0; 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /53.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to find the maximum for 2 | // each and every contiguous subarray of size k. 3 | #include 4 | using namespace std; 5 | 6 | // Method to find the maximum for each 7 | // and every contiguous subarray of size k. 8 | void printKMax(int arr[], int n, int k) 9 | { 10 | int j, max; 11 | 12 | for (int i = 0; i <= n - k; i++) 13 | { 14 | max = arr[i]; 15 | 16 | for (j = 1; j < k; j++) 17 | { 18 | if (arr[i + j] > max) 19 | max = arr[i + j]; 20 | } 21 | cout << max << " "; 22 | } 23 | } 24 | 25 | // Driver code 26 | int main() 27 | { 28 | int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | int k = 3; 31 | printKMax(arr, n, k); 32 | return 0; 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /54.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find whether an array 2 | // is subset of another array 3 | #include 4 | 5 | /* Return 1 if arr2[] is a subset of 6 | arr1[] */ 7 | bool isSubset(int arr1[], int arr2[], 8 | int m, int n) 9 | { 10 | int i = 0; 11 | int j = 0; 12 | for (i = 0; i < n; i++) { 13 | for (j = 0; j < m; j++) { 14 | if (arr2[i] == arr1[j]) 15 | break; 16 | } 17 | 18 | /* If the above inner loop was 19 | not broken at all then arr2[i] 20 | is not present in arr1[] */ 21 | if (j == m) 22 | return 0; 23 | } 24 | 25 | /* If we reach here then all 26 | elements of arr2[] are present 27 | in arr1[] */ 28 | return 1; 29 | } 30 | 31 | // Driver code 32 | int main() 33 | { 34 | int arr1[] = { 11, 1, 13, 21, 3, 7 }; 35 | int arr2[] = { 11, 3, 7, 1 }; 36 | 37 | int m = sizeof(arr1) / sizeof(arr1[0]); 38 | int n = sizeof(arr2) / sizeof(arr2[0]); 39 | 40 | if (isSubset(arr1, arr2, m, n)) 41 | printf("arr2[] is subset of arr1[] "); 42 | else 43 | printf("arr2[] is not a subset of arr1[]"); 44 | 45 | getchar(); 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /55.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Find the minimum 2 | // distance between two numbers 3 | #include 4 | using namespace std; 5 | 6 | int minDist(int arr[], int n, int x, int y) 7 | { 8 | int i, j; 9 | int min_dist = INT_MAX; 10 | for (i = 0; i < n; i++) 11 | { 12 | for (j = i+1; j < n; j++) 13 | { 14 | if( (x == arr[i] && y == arr[j] || 15 | y == arr[i] && x == arr[j]) && 16 | min_dist > abs(i-j)) 17 | { 18 | min_dist = abs(i-j); 19 | } 20 | } 21 | } 22 | return min_dist; 23 | } 24 | 25 | /* Driver code */ 26 | int main() 27 | { 28 | int arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}; 29 | int n = sizeof(arr)/sizeof(arr[0]); 30 | int x = 3; 31 | int y = 6; 32 | 33 | cout << "Minimum distance between " << x << 34 | " and " << y << " is " << 35 | minDist(arr, n, x, y) << endl; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /56.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to Find the repeating 2 | // and missing elements 3 | 4 | #include 5 | using namespace std; 6 | 7 | void printTwoElements(int arr[], int size) 8 | { 9 | int i; 10 | cout << " The repeating element is "; 11 | 12 | for (i = 0; i < size; i++) { 13 | if (arr[abs(arr[i]) - 1] > 0) 14 | arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]; 15 | else 16 | cout << abs(arr[i]) << "\n"; 17 | } 18 | 19 | cout << "and the missing element is "; 20 | for (i = 0; i < size; i++) { 21 | if (arr[i] > 0) 22 | cout << (i + 1); 23 | } 24 | } 25 | 26 | /* Driver code */ 27 | int main() 28 | { 29 | int arr[] = { 7, 3, 4, 5, 5, 6, 2 }; 30 | int n = sizeof(arr) / sizeof(arr[0]); 31 | printTwoElements(arr, n); 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /57.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector spiralOrder(vector> &matrix) 5 | { 6 | vector ans; 7 | 8 | if (matrix.size() == 0) 9 | return ans; 10 | 11 | int R = matrix.size(), C = matrix[0].size(); 12 | bool seen[R][C]; 13 | int dr[] = { 0, 1, 0, -1 }; 14 | int dc[] = { 1, 0, -1, 0 }; 15 | int r = 0, c = 0, di = 0; 16 | 17 | // Iterate from 0 to R * C - 1 18 | for (int i = 0; i < R * C; i++) { 19 | ans.push_back(matrix[r]); 20 | seen[r] = true; 21 | int cr = r + dr[di]; 22 | int cc = c + dc[di]; 23 | 24 | if (0 <= cr && cr < R && 0 <= cc && cc < C 25 | && !seen[cr][cc]) 26 | { 27 | r = cr; 28 | c = cc; 29 | } 30 | else 31 | { 32 | di = (di + 1) % 4; 33 | r += dr[di]; 34 | c += dc[di]; 35 | } 36 | } 37 | return ans; 38 | } 39 | 40 | // Driver code 41 | int main() 42 | { 43 | vector> a { { 1, 2, 3, 4 }, 44 | { 5, 6, 7, 8 }, 45 | { 9, 10, 11, 12 }, 46 | { 13, 14, 15, 16 } }; 47 | 48 | for(int x:spiralOrder(a)) 49 | { 50 | cout << x << " "; 51 | } 52 | return 0; 53 | } 54 | 55 | 56 | -------------------------------------------------------------------------------- /6.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find the element 2 | // occurring odd number of times 3 | #include 4 | using namespace std; 5 | 6 | // Function to find the element 7 | // occurring odd number of times 8 | int getOddOccurrence(int arr[], int arr_size) 9 | { 10 | for (int i = 0; i < arr_size; i++) { 11 | 12 | int count = 0; 13 | 14 | for (int j = 0; j < arr_size; j++) 15 | { 16 | if (arr[i] == arr[j]) 17 | count++; 18 | } 19 | if (count % 2 != 0) 20 | return arr[i]; 21 | } 22 | return -1; 23 | } 24 | 25 | // driver code 26 | int main() 27 | { 28 | int arr[] = { 2, 3, 5, 4, 5, 2, 29 | 4, 3, 5, 2, 4, 4, 2 }; 30 | int n = sizeof(arr) / sizeof(arr[0]); 31 | 32 | // Function calling 33 | cout << getOddOccurrence(arr, n); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /60.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to check fixed point 2 | // in an array using linear search 3 | #include 4 | using namespace std; 5 | 6 | int linearSearch(int arr[], int n) 7 | { 8 | int i; 9 | for(i = 0; i < n; i++) 10 | { 11 | if(arr[i] == i) 12 | return i; 13 | } 14 | 15 | /* If no fixed point present then return -1 */ 16 | return -1; 17 | } 18 | 19 | /* Driver code */ 20 | int main() 21 | { 22 | int arr[] = {-10, -1, 0, 3, 10, 11, 30, 50, 100}; 23 | int n = sizeof(arr)/sizeof(arr[0]); 24 | cout << "Fixed Point is " << linearSearch(arr, n); 25 | return 0; 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /61.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find length of 2 | // the longest bitonic subarray 3 | #include 4 | using namespace std; 5 | 6 | int bitonic(int arr[], int n) 7 | { 8 | // Length of increasing subarray 9 | // ending at all indexes 10 | int inc[n]; 11 | 12 | // Length of decreasing subarray 13 | // starting at all indexes 14 | int dec[n]; 15 | int i, max; 16 | 17 | // length of increasing sequence 18 | // ending at first index is 1 19 | inc[0] = 1; 20 | 21 | // length of increasing sequence 22 | // starting at first index is 1 23 | dec[n-1] = 1; 24 | 25 | // Step 1) Construct increasing sequence array 26 | for (i = 1; i < n; i++) 27 | inc[i] = (arr[i] >= arr[i-1])? inc[i-1] + 1: 1; 28 | 29 | // Step 2) Construct decreasing sequence array 30 | for (i = n-2; i >= 0; i--) 31 | dec[i] = (arr[i] >= arr[i+1])? dec[i+1] + 1: 1; 32 | 33 | // Step 3) Find the length of 34 | // maximum length bitonic sequence 35 | max = inc[0] + dec[0] - 1; 36 | for (i = 1; i < n; i++) 37 | if (inc[i] + dec[i] - 1 > max) 38 | max = inc[i] + dec[i] - 1; 39 | 40 | return max; 41 | } 42 | 43 | /* Driver code */ 44 | int main() 45 | { 46 | int arr[] = {12, 4, 78, 90, 45, 23}; 47 | int n = sizeof(arr)/sizeof(arr[0]); 48 | cout << "nLength of max length Bitnoic Subarray is " << bitonic(arr, n); 49 | return 0; 50 | } 51 | 52 | 53 | -------------------------------------------------------------------------------- /62.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find maximum 2 | // element 3 | #include 4 | using namespace std; 5 | 6 | // function to find the maximum element 7 | int findMaximum(int arr[], int low, int high) 8 | { 9 | int max = arr[low]; 10 | int i; 11 | for (i = low + 1; i <= high; i++) 12 | { 13 | if (arr[i] > max) 14 | max = arr[i]; 15 | 16 | // break when once an element is smaller than 17 | // the max then it will go on decreasing 18 | // and no need to check after that 19 | else 20 | break; 21 | } 22 | return max; 23 | } 24 | 25 | /* Driver code*/ 26 | int main() 27 | { 28 | int arr[] = {1, 30, 40, 50, 60, 70, 23, 20}; 29 | int n = sizeof(arr)/sizeof(arr[0]); 30 | cout << "The maximum element is " << findMaximum(arr, 0, n-1); 31 | return 0; 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /63.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void constructLowerArray(int arr[], int *countSmaller, 5 | int n) 6 | { 7 | int i, j; 8 | 9 | // Initialize all the counts in 10 | // countSmaller array as 0 11 | for(i = 0; i < n; i++) 12 | countSmaller[i] = 0; 13 | 14 | for(i = 0; i < n; i++) 15 | { 16 | for(j = i + 1; j < n; j++) 17 | { 18 | if (arr[j] < arr[i]) 19 | countSmaller[i]++; 20 | } 21 | } 22 | } 23 | 24 | // Utility function that prints 25 | // out an array on a line 26 | void printArray(int arr[], int size) 27 | { 28 | int i; 29 | for(i = 0; i < size; i++) 30 | cout << arr[i] << " "; 31 | 32 | cout << "\n"; 33 | } 34 | 35 | // Driver code 36 | int main() 37 | { 38 | int arr[] = { 12, 10, 5, 4, 2, 39 | 20, 6, 1, 0, 2 }; 40 | int n = sizeof(arr) / sizeof(arr[0]); 41 | int *low = (int *)malloc(sizeof(int)*n); 42 | 43 | constructLowerArray(arr, low, n); 44 | printArray(low, n); 45 | 46 | return 0; 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /64.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find Minimum 2 | // number of jumps to reach end 3 | #include 4 | using namespace std; 5 | 6 | // Function to return the minimum number 7 | // of jumps to reach arr[h] from arr[l] 8 | int minJumps(int arr[], int n) 9 | { 10 | 11 | // Base case: when source and 12 | // destination are same 13 | if (n == 1) 14 | return 0; 15 | 16 | // Traverse through all the points 17 | // reachable from arr[l] 18 | // Recursively, get the minimum number 19 | // of jumps needed to reach arr[h] from 20 | // these reachable points 21 | int res = INT_MAX; 22 | for (int i = n - 2; i >= 0; i--) { 23 | if (i + arr[i] >= n - 1) { 24 | int sub_res = minJumps(arr, i + 1); 25 | if (sub_res != INT_MAX) 26 | res = min(res, sub_res + 1); 27 | } 28 | } 29 | 30 | return res; 31 | } 32 | 33 | // Driver Code 34 | int main() 35 | { 36 | int arr[] = { 1, 3, 6, 3, 2, 37 | 3, 6, 8, 9, 5 }; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | cout << "Minimum number of jumps to"; 40 | cout << " reach the end is " << minJumps(arr, n); 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /66.cpp: -------------------------------------------------------------------------------- 1 | /* A simple program to print subarray 2 | with sum as given sum */ 3 | #include 4 | using namespace std; 5 | 6 | /* Returns true if the there is a subarray 7 | of arr[] with sum equal to 'sum' otherwise 8 | returns false. Also, prints the result */ 9 | int subArraySum(int arr[], int n, int sum) 10 | { 11 | int curr_sum, i, j; 12 | 13 | // Pick a starting point 14 | for (i = 0; i < n; i++) { 15 | curr_sum = arr[i]; 16 | 17 | // try all subarrays starting with 'i' 18 | for (j = i + 1; j <= n; j++) { 19 | if (curr_sum == sum) { 20 | cout << "Sum found between indexes " 21 | << i << " and " << j - 1; 22 | return 1; 23 | } 24 | if (curr_sum > sum || j == n) 25 | break; 26 | curr_sum = curr_sum + arr[j]; 27 | } 28 | } 29 | 30 | cout << "No subarray found"; 31 | return 0; 32 | } 33 | 34 | // Driver Code 35 | int main() 36 | { 37 | int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | int sum = 23; 40 | subArraySum(arr, n, sum); 41 | return 0; 42 | } 43 | 44 | 45 | -------------------------------------------------------------------------------- /67.cpp: -------------------------------------------------------------------------------- 1 | /* Dynamic Programming implementation 2 | of Maximum Sum Increasing Subsequence 3 | (MSIS) problem */ 4 | #include 5 | using namespace std; 6 | 7 | /* maxSumIS() returns the maximum 8 | sum of increasing subsequence 9 | in arr[] of size n */ 10 | int maxSumIS(int arr[], int n) 11 | { 12 | int i, j, max = 0; 13 | int msis[n]; 14 | 15 | /* Initialize msis values 16 | for all indexes */ 17 | for ( i = 0; i < n; i++ ) 18 | msis[i] = arr[i]; 19 | 20 | /* Compute maximum sum values 21 | in bottom up manner */ 22 | for ( i = 1; i < n; i++ ) 23 | for ( j = 0; j < i; j++ ) 24 | if (arr[i] > arr[j] && 25 | msis[i] < msis[j] + arr[i]) 26 | msis[i] = msis[j] + arr[i]; 27 | 28 | /* Pick maximum of 29 | all msis values */ 30 | for ( i = 0; i < n; i++ ) 31 | if ( max < msis[i] ) 32 | max = msis[i]; 33 | 34 | return max; 35 | } 36 | 37 | // Driver Code 38 | int main() 39 | { 40 | int arr[] = {1, 101, 2, 3, 100, 4, 5}; 41 | int n = sizeof(arr)/sizeof(arr[0]); 42 | cout << "Sum of maximum sum increasing " 43 | "subsequence is " << maxSumIS( arr, n ) << endl; 44 | return 0; 45 | } 46 | 47 | 48 | -------------------------------------------------------------------------------- /68.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Binary search (note boundaries in the caller) 5 | int CeilIndex(std::vector& v, int l, int r, int key) 6 | { 7 | while (r - l > 1) { 8 | int m = l + (r - l) / 2; 9 | if (v[m] >= key) 10 | r = m; 11 | else 12 | l = m; 13 | } 14 | 15 | return r; 16 | } 17 | 18 | int LongestIncreasingSubsequenceLength(std::vector& v) 19 | { 20 | if (v.size() == 0) 21 | return 0; 22 | 23 | std::vector tail(v.size(), 0); 24 | int length = 1; // always points empty slot in tail 25 | 26 | tail[0] = v[0]; 27 | for (size_t i = 1; i < v.size(); i++) { 28 | 29 | // new smallest value 30 | if (v[i] < tail[0]) 31 | tail[0] = v[i]; 32 | 33 | // v[i] extends largest subsequence 34 | else if (v[i] > tail[length - 1]) 35 | tail[length++] = v[i]; 36 | 37 | // v[i] will become end candidate of an existing 38 | // subsequence or Throw away larger elements in all 39 | // LIS, to make room for upcoming grater elements 40 | // than v[i] (and also, v[i] would have already 41 | // appeared in one of LIS, identify the location 42 | // and replace it) 43 | else 44 | tail[CeilIndex(tail, -1, length - 1, v[i])] = v[i]; 45 | } 46 | 47 | return length; 48 | } 49 | 50 | int main() 51 | { 52 | std::vector v{ 2, 5, 3, 7, 11, 8, 10, 13, 6 }; 53 | std::cout << "Length of Longest Increasing Subsequence is " 54 | << LongestIncreasingSubsequenceLength(v) << '\n'; 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /69.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // returns true if there is triplet with sum equal 5 | // to 'sum' present in A[]. Also, prints the triplet 6 | bool find3Numbers(int A[], int arr_size, int sum) 7 | { 8 | int l, r; 9 | 10 | // Fix the first element as A[i] 11 | for (int i = 0; i < arr_size - 2; i++) 12 | { 13 | 14 | // Fix the second element as A[j] 15 | for (int j = i + 1; j < arr_size - 1; j++) 16 | { 17 | 18 | // Now look for the third number 19 | for (int k = j + 1; k < arr_size; k++) 20 | { 21 | if (A[i] + A[j] + A[k] == sum) 22 | { 23 | cout << "Triplet is " << A[i] << 24 | ", " << A[j] << ", " << A[k]; 25 | return true; 26 | } 27 | } 28 | } 29 | } 30 | 31 | // If we reach here, then no triplet was found 32 | return false; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int A[] = { 1, 4, 45, 6, 10, 8 }; 39 | int sum = 22; 40 | int arr_size = sizeof(A) / sizeof(A[0]); 41 | find3Numbers(A, arr_size, sum); 42 | return 0; 43 | } 44 | 45 | -------------------------------------------------------------------------------- /7.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find angle between hour and minute hands 2 | #include 3 | using namespace std; 4 | 5 | // Utility function to find minimum of two integers 6 | int min(int x, int y) 7 | { 8 | return (x < y)? x: y; 9 | 10 | } 11 | 12 | int calcAngle(double h, double m) 13 | { 14 | // validate the input 15 | if (h <0 || m < 0 || h >12 || m > 60) 16 | printf("Wrong input"); 17 | 18 | if (h == 12) h = 0; 19 | if (m == 60) 20 | { 21 | m = 0; 22 | h += 1; 23 | if(h>12) 24 | h = h-12; 25 | } 26 | 27 | // Calculate the angles moved 28 | // by hour and minute hands 29 | // with reference to 12:00 30 | float hour_angle = 0.5 * (h * 60 + m); 31 | float minute_angle = 6 * m; 32 | 33 | // Find the difference between two angles 34 | float angle = abs(hour_angle - minute_angle); 35 | 36 | // Return the smaller angle of two possible angles 37 | angle = min(360 - angle, angle); 38 | 39 | return angle; 40 | } 41 | 42 | // Driver Code 43 | int main() 44 | { 45 | cout << calcAngle(9, 60) << endl; 46 | cout << calcAngle(3, 30) << endl; 47 | return 0; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /72.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find celebrity 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Max # of persons in the party 7 | #define N 8 8 | 9 | // Person with 2 is celebrity 10 | bool MATRIX[N][N] = {{0, 0, 1, 0}, 11 | {0, 0, 1, 0}, 12 | {0, 0, 0, 0}, 13 | {0, 0, 1, 0}}; 14 | 15 | bool knows(int a, int b) 16 | { 17 | return MATRIX[a][b]; 18 | } 19 | 20 | // Returns -1 if celebrity 21 | // is not present. If present, 22 | // returns id (value from 0 to n-1). 23 | int findCelebrity(int n) 24 | { 25 | //the graph needs not be constructed 26 | //as the edges can be found by 27 | //using knows function 28 | 29 | //degree array; 30 | int indegree[n]={0},outdegree[n]={0}; 31 | 32 | //query for all edges 33 | for(int i=0; i 4 | 5 | using namespace std; 6 | 7 | // This function Prints the starting and ending 8 | // indexes of the largest subarray with equal 9 | // number of 0s and 1s. Also returns the size 10 | // of such subarray. 11 | 12 | int findSubArray(int arr[], int n) 13 | { 14 | int sum = 0; 15 | int maxsize = -1, startindex; 16 | 17 | // Pick a starting point as i 18 | for (int i = 0; i < n - 1; i++) { 19 | sum = (arr[i] == 0) ? -1 : 1; 20 | 21 | // Consider all subarrays starting from i 22 | for (int j = i + 1; j < n; j++) { 23 | (arr[j] == 0) ? (sum += -1) : (sum += 1); 24 | 25 | // If this is a 0 sum subarray, then 26 | // compare it with maximum size subarray 27 | // calculated so far 28 | if (sum == 0 && maxsize < j - i + 1) { 29 | maxsize = j - i + 1; 30 | startindex = i; 31 | } 32 | } 33 | } 34 | if (maxsize == -1) 35 | cout << "No such subarray"; 36 | else 37 | cout << startindex << " to " 38 | << startindex + maxsize - 1; 39 | 40 | return maxsize; 41 | } 42 | 43 | /* Driver code*/ 44 | int main() 45 | { 46 | int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; 47 | int size = sizeof(arr) / sizeof(arr[0]); 48 | 49 | findSubArray(arr, size); 50 | return 0; 51 | } 52 | 53 | -------------------------------------------------------------------------------- /77.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find Maximum Product Subarray 2 | #include 3 | using namespace std; 4 | 5 | /* Returns the product of max product subarray.*/ 6 | int maxSubarrayProduct(int arr[], int n) 7 | { 8 | // Initializing result 9 | int result = arr[0]; 10 | 11 | for (int i = 0; i < n; i++) 12 | { 13 | int mul = arr[i]; 14 | // traversing in current subarray 15 | for (int j = i + 1; j < n; j++) 16 | { 17 | // updating result every time 18 | // to keep an eye over the maximum product 19 | result = max(result, mul); 20 | mul *= arr[j]; 21 | } 22 | // updating the result for (n-1)th index. 23 | result = max(result, mul); 24 | } 25 | return result; 26 | } 27 | 28 | // Driver code 29 | int main() 30 | { 31 | int arr[] = { 1, -2, -3, 0, 7, -8, -2 }; 32 | int n = sizeof(arr) / sizeof(arr[0]); 33 | cout << "Maximum Sub array product is " 34 | << maxSubarrayProduct(arr, n); 35 | return 0; 36 | } 37 | 38 | 39 | -------------------------------------------------------------------------------- /78.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find a pair with the given difference 2 | #include 3 | using namespace std; 4 | 5 | // The function assumes that the array is sorted 6 | bool findPair(int arr[], int size, int n) 7 | { 8 | // Initialize positions of two elements 9 | int i = 0; 10 | int j = 1; 11 | 12 | // Search for a pair 13 | while (i < size && j < size) 14 | { 15 | if (i != j && arr[j] - arr[i] == n) 16 | { 17 | cout << "Pair Found: (" << arr[i] << 18 | ", " << arr[j] << ")"; 19 | return true; 20 | } 21 | else if (arr[j]-arr[i] < n) 22 | j++; 23 | else 24 | i++; 25 | } 26 | 27 | cout << "No such pair"; 28 | return false; 29 | } 30 | 31 | // Driver program to test above function 32 | int main() 33 | { 34 | int arr[] = {1, 8, 30, 40, 100}; 35 | int size = sizeof(arr)/sizeof(arr[0]); 36 | int n = 60; 37 | findPair(arr, size, n); 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /79.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to replace every element with the greatest 2 | // element on right side 3 | #include 4 | using namespace std; 5 | 6 | /* Function to replace every element with the 7 | next greatest element */ 8 | void nextGreatest(int arr[], int size) 9 | { 10 | 11 | // Initialize the next greatest element 12 | int max_from_right = arr[size-1]; 13 | 14 | // The next greatest element for the rightmost element 15 | // is always -1 16 | arr[size-1] = -1; 17 | 18 | // Replace all other elements with the next greatest 19 | for(int i = size-2; i >= 0; i--) 20 | { 21 | // Store the current element (needed later for updating 22 | // the next greatest element) 23 | int temp = arr[i]; 24 | 25 | // Replace current element with the next greatest 26 | arr[i] = max_from_right; 27 | 28 | // Update the greatest element, if needed 29 | if(max_from_right < temp) 30 | max_from_right = temp; 31 | } 32 | } 33 | 34 | /* A utility Function that prints an array */ 35 | void printArray(int arr[], int size) 36 | { 37 | int i; 38 | for (i = 0; i < size; i++) 39 | cout << arr[i] << " "; 40 | cout << endl; 41 | } 42 | 43 | /* Driver program to test above function */ 44 | int main() 45 | { 46 | int arr[] = {16, 17, 4, 3, 5, 2}; 47 | int size = sizeof(arr)/sizeof(arr[0]); 48 | nextGreatest (arr, size); 49 | cout << "The modified array is: \n"; 50 | printArray (arr, size); 51 | return (0); 52 | } 53 | 54 | -------------------------------------------------------------------------------- /8.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print largest contiguous array sum 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int maxSubArraySum(int a[], int size) 7 | { 8 | int max_so_far = INT_MIN, max_ending_here = 0; 9 | 10 | for (int i = 0; i < size; i++) 11 | { 12 | max_ending_here = max_ending_here + a[i]; 13 | if (max_so_far < max_ending_here) 14 | max_so_far = max_ending_here; 15 | 16 | if (max_ending_here < 0) 17 | max_ending_here = 0; 18 | } 19 | return max_so_far; 20 | } 21 | 22 | /*Driver program to test maxSubArraySum*/ 23 | int main() 24 | { 25 | int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; 26 | int n = sizeof(a)/sizeof(a[0]); 27 | int max_sum = maxSubArraySum(a, n); 28 | cout << "Maximum contiguous sum is " << max_sum; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /80.cpp: -------------------------------------------------------------------------------- 1 | // CPP program for above approach 2 | #include 3 | using namespace std; 4 | 5 | // Structure for a Pair 6 | class Pair 7 | { 8 | public: 9 | int a; 10 | int b; 11 | }; 12 | 13 | // This function assumes that arr[] 14 | // is sorted in increasing order 15 | // according the first 16 | // (or smaller) values in Pairs. 17 | int maxChainLength( Pair arr[], int n) 18 | { 19 | int i, j, max = 0; 20 | int *mcl = new int[sizeof( int ) * n ]; 21 | 22 | /* Initialize MCL (max chain length) 23 | values for all indexes */ 24 | for ( i = 0; i < n; i++ ) 25 | mcl[i] = 1; 26 | 27 | /* Compute optimized chain 28 | length values in bottom up manner */ 29 | for ( i = 1; i < n; i++ ) 30 | for ( j = 0; j < i; j++ ) 31 | if ( arr[i].a > arr[j].b && 32 | mcl[i] < mcl[j] + 1) 33 | mcl[i] = mcl[j] + 1; 34 | 35 | // mcl[i] now stores the maximum 36 | // chain length ending with Pair i 37 | 38 | /* Pick maximum of all MCL values */ 39 | for ( i = 0; i < n; i++ ) 40 | if ( max < mcl[i] ) 41 | max = mcl[i]; 42 | 43 | /* Free memory to avoid memory leak */ 44 | 45 | return max; 46 | } 47 | 48 | 49 | /* Driver code */ 50 | int main() 51 | { 52 | Pair arr[] = { {5, 24}, {15, 25}, 53 | {27, 40}, {50, 60} }; 54 | int n = sizeof(arr)/sizeof(arr[0]); 55 | cout << "Length of maximum size chain is " 56 | << maxChainLength( arr, n ); 57 | return 0; 58 | } 59 | 60 | -------------------------------------------------------------------------------- /81.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for naive solution to 2 | // print all combination of 4 elements 3 | // in A[] with sum equal to X 4 | #include 5 | using namespace std; 6 | 7 | /* A naive solution to print all combination 8 | of 4 elements in A[]with sum equal to X */ 9 | void findFourElements(int A[], int n, int X) 10 | { 11 | 12 | // Fix the first element and find other three 13 | for (int i = 0; i < n - 3; i++) 14 | { 15 | // Fix the second element and find other two 16 | for (int j = i + 1; j < n - 2; j++) 17 | { 18 | 19 | // Fix the third element and find the fourth 20 | for (int k = j + 1; k < n - 1; k++) 21 | { 22 | // find the fourth 23 | for (int l = k + 1; l < n; l++) 24 | if (A[i] + A[j] + A[k] + A[l] == X) 25 | cout << A[i] <<", " << A[j] 26 | << ", " << A[k] << ", " << A[l]; 27 | } 28 | } 29 | } 30 | } 31 | 32 | // Driver Code 33 | int main() 34 | { 35 | int A[] = {10, 20, 30, 40, 1, 2}; 36 | int n = sizeof(A) / sizeof(A[0]); 37 | int X = 91; 38 | findFourElements (A, n, X); 39 | return 0; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /83.cpp: -------------------------------------------------------------------------------- 1 | // A STL based C++ program to sort a nearly sorted array. 2 | #include 3 | using namespace std; 4 | 5 | // Given an array of size n, where every element 6 | // is k away from its target position, sorts the 7 | // array in O(n logk) time. 8 | int sortK(int arr[], int n, int k) 9 | { 10 | // Insert first k+1 items in a priority queue (or min 11 | // heap) 12 | //(A O(k) operation). We assume, k < n. 13 | priority_queue, greater > pq(arr, arr + k + 1); 14 | 15 | // i is index for remaining elements in arr[] and index 16 | // is target index of for current minimum element in 17 | // Min Heap 'pq'. 18 | int index = 0; 19 | for (int i = k + 1; i < n; i++) { 20 | arr[index++] = pq.top(); 21 | pq.pop(); 22 | pq.push(arr[i]); 23 | } 24 | 25 | while (pq.empty() == false) { 26 | arr[index++] = pq.top(); 27 | pq.pop(); 28 | } 29 | } 30 | 31 | // A utility function to print array elements 32 | void printArray(int arr[], int size) 33 | { 34 | for (int i = 0; i < size; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver program to test above functions 40 | int main() 41 | { 42 | int k = 3; 43 | int arr[] = { 2, 6, 3, 12, 56, 8 }; 44 | int n = sizeof(arr) / sizeof(arr[0]); 45 | sortK(arr, n, k); 46 | 47 | cout << "Following is sorted array" << endl; 48 | printArray(arr, n); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /88.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to shuffle a given array 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // A utility function to swap to integers 8 | void swap (int *a, int *b) 9 | { 10 | int temp = *a; 11 | *a = *b; 12 | *b = temp; 13 | } 14 | 15 | // A utility function to print an array 16 | void printArray (int arr[], int n) 17 | { 18 | for (int i = 0; i < n; i++) 19 | cout << arr[i] << " "; 20 | cout << "\n"; 21 | } 22 | 23 | // A function to generate a random 24 | // permutation of arr[] 25 | void randomize (int arr[], int n) 26 | { 27 | // Use a different seed value so that 28 | // we don't get same result each time 29 | // we run this program 30 | srand (time(NULL)); 31 | 32 | // Start from the last element and swap 33 | // one by one. We don't need to run for 34 | // the first element that's why i > 0 35 | for (int i = n - 1; i > 0; i--) 36 | { 37 | // Pick a random index from 0 to i 38 | int j = rand() % (i + 1); 39 | 40 | // Swap arr[i] with the element 41 | // at random index 42 | swap(&arr[i], &arr[j]); 43 | } 44 | } 45 | 46 | // Driver Code 47 | int main() 48 | { 49 | int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; 50 | int n = sizeof(arr) / sizeof(arr[0]); 51 | randomize (arr, n); 52 | printArray(arr, n); 53 | 54 | return 0; 55 | } 56 | 57 | -------------------------------------------------------------------------------- /89.cpp: -------------------------------------------------------------------------------- 1 | // C++ code to count the number of 2 | // possible triangles using brute 3 | // force approach 4 | #include 5 | using namespace std; 6 | 7 | // Function to count all possible 8 | // triangles with arr[] elements 9 | int findNumberOfTriangles(int arr[], int n) 10 | { 11 | // Count of triangles 12 | int count = 0; 13 | 14 | // The three loops select three 15 | // different values from array 16 | for (int i = 0; i < n; i++) { 17 | for (int j = i + 1; j < n; j++) { 18 | 19 | // The innermost loop checks for 20 | // the triangle property 21 | for (int k = j + 1; k < n; k++) 22 | 23 | // Sum of two sides is greater 24 | // than the third 25 | if ( 26 | arr[i] + arr[j] > arr[k] 27 | && arr[i] + arr[k] > arr[j] 28 | && arr[k] + arr[j] > arr[i]) 29 | count++; 30 | } 31 | } 32 | return count; 33 | } 34 | 35 | // Driver code 36 | int main() 37 | { 38 | int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; 39 | int size = sizeof(arr) / sizeof(arr[0]); 40 | 41 | cout 42 | << "Total number of triangles possible is " 43 | << findNumberOfTriangles(arr, size); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /9.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to get the missing number 5 | int getMissingNo(int a[], int n) 6 | { 7 | 8 | int total = (n + 1) * (n + 2) / 2; 9 | for (int i = 0; i < n; i++) 10 | total -= a[i]; 11 | return total; 12 | } 13 | 14 | // Driver Code 15 | int main() 16 | { 17 | int arr[] = { 1, 2, 4, 5, 6 }; 18 | int n = sizeof(arr) / sizeof(arr[0]); 19 | int miss = getMissingNo(arr, n); 20 | cout << miss; 21 | } 22 | -------------------------------------------------------------------------------- /90.cpp: -------------------------------------------------------------------------------- 1 | // CPP code for recursive function of Quicksort 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Function to swap numbers 7 | void swap(int* a, int* b) 8 | { 9 | int temp = *a; 10 | *a = *b; 11 | *b = temp; 12 | } 13 | 14 | /* This function takes last element as pivot, 15 | places the pivot element at its correct 16 | position in sorted array, and places 17 | all smaller (smaller than pivot) to left 18 | of pivot and all greater elements to 19 | right of pivot */ 20 | int partition(int arr[], int l, int h) 21 | { 22 | int x = arr[h]; 23 | int i = (l - 1); 24 | 25 | for (int j = l; j <= h - 1; j++) { 26 | if (arr[j] <= x) { 27 | i++; 28 | swap(&arr[i], &arr[j]); 29 | } 30 | } 31 | swap(&arr[i + 1], &arr[h]); 32 | return (i + 1); 33 | } 34 | 35 | /* A[] --> Array to be sorted, 36 | l --> Starting index, 37 | h --> Ending index */ 38 | void quickSort(int A[], int l, int h) 39 | { 40 | if (l < h) { 41 | /* Partitioning index */ 42 | int p = partition(A, l, h); 43 | quickSort(A, l, p - 1); 44 | quickSort(A, p + 1, h); 45 | } 46 | } 47 | 48 | // Driver code 49 | int main() 50 | { 51 | 52 | int n = 5; 53 | int arr[n] = { 4, 2, 6, 9, 2 }; 54 | 55 | quickSort(arr, 0, n - 1); 56 | 57 | for (int i = 0; i < n; i++) { 58 | cout << arr[i] << " "; 59 | } 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /95.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of numbers, 2 | // program to arrange the numbers 3 | // to form the largest number 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | // A comparison function which 11 | // is used by sort() in 12 | // printLargest() 13 | int myCompare(string X, string Y) 14 | { 15 | // first append Y at the end of X 16 | string XY = X.append(Y); 17 | 18 | // then append X at the end of Y 19 | string YX = Y.append(X); 20 | 21 | // Now see which of the two 22 | // formed numbers is greater 23 | return XY.compare(YX) > 0 ? 1 : 0; 24 | } 25 | 26 | // The main function that prints 27 | // the arrangement with the 28 | // largest value. The function 29 | // accepts a vector of strings 30 | void printLargest(vector arr) 31 | { 32 | 33 | // Sort the numbers using 34 | // library sort function. The 35 | // function uses our comparison 36 | // function myCompare() to 37 | // compare two strings. See 38 | // http://www.cplusplus.com/reference/ 39 | // algorithm/sort/ 40 | // for details 41 | sort(arr.begin(), arr.end(), myCompare); 42 | 43 | for (int i = 0; i < arr.size(); i++) 44 | cout << arr[i]; 45 | } 46 | 47 | // Driver code 48 | int main() 49 | { 50 | vector arr; 51 | 52 | // output should be 6054854654 53 | arr.push_back("54"); 54 | arr.push_back("546"); 55 | arr.push_back("548"); 56 | arr.push_back("60"); 57 | printLargest(arr); 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⭐⭐⭐500-CPP⭐⭐⭐ 2 | A collection of 500 C++ Programs 3 | 4 |
5 | 6 | [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity) 7 | [![ForTheBadge built-with-love](http://ForTheBadge.com/images/badges/built-with-love.svg)](https://GitHub.com/Naereen/) 8 | [![ForTheBadge built-with-swag](http://ForTheBadge.com/images/badges/built-with-swag.svg)](https://GitHub.com/Naereen/) 9 | [![ForTheBadge built-by-developers](http://ForTheBadge.com/images/badges/built-by-developers.svg)](https://GitHub.com/Naereen/) 10 | 11 | 12 | 13 | --------------------------------------------------------------------------------