Repository: apna-college/Cpp-DSAClasses Branch: main Commit: df2f65cb2bfa Files: 26 Total size: 55.1 KB Directory structure: gitextract_eps2mzau/ ├── .gitignore ├── 04_Conditional_Statements/ │ └── conditionals.cpp ├── 05_Loops/ │ ├── homework.cpp │ └── loops.cpp ├── 06_Patterns/ │ └── patterns.cpp ├── 07_Functions/ │ └── functions.cpp ├── 08_Binary_Numbers/ │ └── binary.cpp ├── 09_Pointers/ │ └── pointers.cpp ├── 10_Array_1/ │ └── arrays.cpp ├── 11_Arrays_2/ │ └── arrays2.cpp ├── 12_Basic_Sorting_Algos/ │ └── sorting.cpp ├── 13_2DArray/ │ └── 2DArrays.cpp ├── 14_String/ │ └── strings.cpp ├── 15_Vector/ │ └── vectors.cpp ├── 16_Bit_Manipulation/ │ └── bit_manip.cpp ├── 17_OOPS1/ │ └── oops1.cpp ├── 18_OOPS2/ │ └── oops2.cpp ├── 19_Recursion1/ │ └── recursion1.cpp ├── 20_Recursion2/ │ └── rec2.cpp ├── 21_Divide_and_Conquer/ │ └── divideAndConquer.cpp ├── 24_Backtracking/ │ └── backtracking.cpp ├── 25_LinkedList1/ │ └── ll1.cpp ├── 26_LinkedList2/ │ ├── doubly_linkedlist.cpp │ ├── linkedlist.cpp │ └── list_using_stl.cpp └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store ================================================ FILE: 04_Conditional_Statements/conditionals.cpp ================================================ #include #include using namespace std; int main() { //Print the largest of 2 numbers int a = 3, b = 5; if(a >= b) { cout << "a is larger" << endl; } else { cout << "b is larger" << endl; } //Print if a number is Odd or Even int num = 5; if(num % 2 == 0) { cout << "Number is Even" << endl; } else { cout << "Number is Odd" << endl; } //Income Tax Calculator int income = 7; //in Lakhs float tax; if(income < 5) { tax = 0; } else if(income <= 10) { tax = 0.2 * income; } else { tax = 0.3 * income; } cout << "Tax = " << (tax * 100000) << endl; //Print Largest of 3 Numbers int x = 2, y = 3, z = 5; if(x >= y && x >= z) { cout << "x is largest" << endl; } else if(y >= z) { cout << "y is largest" << endl; } else { cout << "z is largest" << endl; } //Odd or Even using Ternary Operator int num = 25; bool isEven = num % 2 == 0 ? true : false; //Calculator using Switch Statement int op = '*'; int num1 = 4; int num2 = 5; switch(op) { case '+' : cout << "a + b = " << (num1 + num2) << endl; break; case '-' : cout << "a - b = " << (num1 - num2) << endl; break; case '*' : cout << "a * b = " << (num1 * num2) << endl; break; case '/' : cout << "a / b = " << (num1 / num2) << endl; break; default : cout << "Invalid Operator" << endl; } return 0; } ================================================ FILE: 05_Loops/homework.cpp ================================================ #include using namespace std; int main() { //Qs : Factorial of a number n int n = 6; int fact = 1; for(int i=1; i<=n; i++) { fact *= i; } cout << "factorial of " << n << " = " << fact << "\n"; //Qs : Multiplication Table of n n = 8; for(int i=1; i<=10; i++) { cout << (n * i) << " "; } cout << endl; //Qs : Check for Armstrong Number n = 371; int num = n; int cubeSum = 0; while(num > 0) { int lastDig = num % 10; cubeSum += lastDig * lastDig * lastDig; num /= 10; } if(n == cubeSum) { cout << "Armstrong number\n"; } else { cout << "NOT an Armstrong number\n"; } //Qs : Print Primes from 2 to N int N = 15; for(int i=2; i<=N; i++) { int curr = i; //current number to check for bool isPrime = true; for(int j=2; j*j<=i; j++) { if(curr % j == 0) { isPrime = false; } } if(isPrime) { cout << curr << " "; } } cout << endl; //Qs : Print N Fibonacci Numbers n = 10; int first = 0, sec = 1; cout << first << " " << sec << " "; for(int i=2; i #include using namespace std; int main() { int n = 10; //Print numbers from 1 to n // for(int i=1; i<=n; i++) { // cout << i << " "; // } // cout << endl; //Print numbers from n to 1 (reverse order) // for(int i=n; i>0; i--) { // cout << i << " "; // } // cout << endl; //Print Sum of first N natural numbers // int sum = 0; // for(int i=1; i<=n; i++) { // sum += i; // } // cout << "Sum from 1 to n = " << sum << endl; //Square Pattern using For Loop // for(int i=1; i<=4; i++) { // cout << "****" << endl; // } //Sum of Digits of a Number // int digitSum = 0; // int num = 12345; // while(num > 0) { // digitSum += num % 10; // num /= 10; // } // cout << "sum of digits = " << digitSum << endl; //Sum of Odd Digits of a Number // int oddDigSum = 0; // int num = 12345; // while(num > 0) { // int lastDig = num % 10; // if(lastDig % 2 != 0) { // oddDigSum += lastDig; // } // num /= 10; // } // cout << "sum of odd digits = " << oddDigSum << endl; //Print a number's Digits in Reverse // int num = 12345; // // while(num > 0) { // cout << num % 10 << " "; // num /= 10; // } // cout << endl; //Reverse the given number & print the result // int num = 12345; // int res = 0; // while(num > 0) { // int lastDig = num % 10; // res = res * 10 + lastDig; // num /= 10; // } // cout << res << endl; //Check if a number is Prime or not int num = 49; bool isPrime = true; //Solution 1 for(int i=2; i isPrime = true; for(int i=2; i<=sqrt(num); i++) { if(num % i == 0) { isPrime = false; break; } } cout << isPrime << endl; return 0; } ================================================ FILE: 06_Patterns/patterns.cpp ================================================ #include using namespace std; int main() { int n = 4; //Number Square Pattern for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { cout << i; } cout << endl; } // Star Pattern for(int i=1; i<=n; i++) { for(int j=1; j<=i; j++) { cout << "*"; } cout << endl; } //Inverted Star Pattern for(int i=1; i<=n; i++) { for(int j=1; j<=n-i+1; j++) { cout << "*"; } cout << endl; } // Half Pyramid Pattern for(int i=1; i<=n; i++) { for(int j=1; j<=i; j++) { cout << j; } cout << endl; } // Character Pyramid Pattern char ch = 'A'; for(int i=1; i<=n; i++) { for(int j=1; j<=i; j++) { cout << ch++; } cout << endl; } //Hollow Rectangle Pattern for(int i=1; i<=n; i++) { cout << "*"; for(int j=1; j<=n-1; j++) { if(i == 1 || i == n) { cout << "*"; } else { cout << " "; } } cout<< "*" << endl; } //Inverted & Rotated Half Pyramid for(int i=1; i<=n; i++) { //spaces for(int j=1; j<=n-i; j++) { cout << " "; } //stars for(int j=1; j<=i; j++) { cout << "*"; } cout << endl; } //Floyd's Triange Pattern int num = 1; for(int i=1; i<=5; i++) { for(int j=1; j<=i; j++) { cout << num++ << " "; } cout << endl; } //Diamond Pattern for(int i=1; i<=n; i++) { for(int j=1; j<=n-i; j++) { cout << " "; } for(int j=1; j<=2*i-1; j++) { cout << "*"; } cout << endl; } for(int i=n; i>0; i--) { for(int j=1; j<=n-i; j++) { cout << " "; } for(int j=1; j<=2*i-1; j++) { cout << "*"; } cout << endl; } //Butterfly Pattern for(int i=1; i<=n; i++) { for(int j=1; j<=i; j++) { cout << "*"; } for(int j=1; j<=2*(n-i); j++) { cout << " "; } for(int j=1; j<=i; j++) { cout << "*"; } cout << endl; } for(int i=n; i>0; i--) { for(int j=1; j<=i; j++) { cout << "*"; } for(int j=1; j<=2*(n-i); j++) { cout << " "; } for(int j=1; j<=i; j++) { cout << "*"; } cout << endl; } return 0; } ================================================ FILE: 07_Functions/functions.cpp ================================================ #include using namespace std; //Simple Function void sayHello() { cout << "Hello from Apna College\n"; } //Sum of 2 numbers int sum(int a, int b) { return a + b; } //Sum of 2 float - Function Overloading float sum(float x, float y) { return x + y; } //Product of 2 numbers int prod(int a, int b) { return a + b; } //Is Number Odd or Even void evenOrOdd(int n) { if(n % 2 == 0) { cout << "Even\n"; } else { cout << "Odd\n"; } } //Factorial of n int factorial(int n) { int fact = 1; for(int i=2; i<=n; i++) { fact = fact * i; } return fact; } //Prime or Not bool isPrime(int n) { if(n == 0 || n == 1) { return false; } for (int i = 2; i*i <= n; i++) { if(n % i == 0) { return false; } } return true; } //Binomial Coefficient nCr int binCoeff(int n, int r) { return factorial(n) / (factorial(n-r) * factorial(r)); } //All primes in range [2, n] void allPrimes(int n) { for(int i=2; i<=n; i++) { if(isPrime(i)) { cout << i << " "; } } cout << endl; } int main() { sayHello(); cout << sum(1, 2) << endl; cout << sum(1.0f, 2.0f) << endl; cout << prod(1, 2) << endl; evenOrOdd(25); cout << factorial(5) << endl; cout << isPrime(5) << endl; cout << binCoeff(4, 2) << endl; allPrimes(15); return 0; } ================================================ FILE: 08_Binary_Numbers/binary.cpp ================================================ #include using namespace std; //Convert Binary to Decimal void binToDecimal(int n) { int res = 0; int p = 1; while(n > 0) { int lastDig = n % 10; res += lastDig * p; p = p * 2; n = n / 10; } cout << "Decimal form = " << res << "\n"; } //Convert Decimal to Binary void decToBinary(int n) { int res = 0; int p = 1; while(n > 0) { int rem = n % 2; res += rem * p; p = p * 10; n = n / 2; } cout << "Binary form = " << res << "\n"; } int main() { binToDecimal(101); decToBinary(5); return 0; } ================================================ FILE: 09_Pointers/pointers.cpp ================================================ #include using namespace std; void passValue(int param) { param = 1000; } //using Pointers void passReference(int *param) { *param = 1000; } //using Reference Variable void passReference2(int ¶m) { param = 5000; } int main() { int a = 10; int *ptr = &a; int **ptr2 = &ptr; cout << &a << " = " << ptr << endl; cout << &ptr << " = " << ptr2 << endl; //Dereference Operator cout << a << " = " << *ptr << " = " << *(&a) << endl; *ptr = 20; cout << a << endl; //should be 20 now //Null Pointer float* nptr = NULL; cout << nptr << endl; //cout << *nptr; // Gives Segmentation Fault //Pass by value int x = 0; passValue(x); cout << x << endl; //Pass by reference passReference(&x); cout << x << endl; //Reference Variable int i = 5; int &j = i; j++; cout << i << endl; passReference2(x); cout << x << endl; } ================================================ FILE: 10_Array_1/arrays.cpp ================================================ #include using namespace std; void printArr(int *arr, int n) { for(int i=0; i max) { max = arr[i]; } } cout << "max = " << max << endl; } //copy & paste method void reverseArr1(int *arr, int n) { int newArr[n]; for(int i=0; i arr[mid]) { //search in 2nd half start = mid + 1; } else { //search in 1st half end = mid - 1; } } return -1; } //Print all Subarrays of an Array void printSubarrays(int *arr, int n) { for(int start=0; start using namespace std; //max sum subarray (brute force - O(N^3)) int maxSumSubarray(int *arr, int n) { int maxSum = INT_MIN; for(int start=0; start=0; i--) { maxRight[i] = max(maxTillNow, heights[i+1]); maxTillNow = max(maxTillNow, heights[i]); } int water = 0; for(int i=0; i 0) { water += ht; } } cout << "water trapped = " << water << "\n"; return water; } //Buy & Sell Stocks int maxProfit(int *prices, int n) { int bestBuy[100000] = {0}; bestBuy[0] = INT_MAX; for(int i=1; i using namespace std; //Print Array void printArr(int arr[], int n) { for(int i=0; i arr[j+1]) { swap(arr[j], arr[j+1]); } } } printArr(arr, n); } void selectionSort(int arr[], int n) { for(int i=0; i= 0 && arr[prev] > curr) { arr[prev+1] = arr[prev]; prev--; } //swap swap(arr[prev+1], curr); } printArr(arr, n); } void countSort(int arr[], int n) { int range = INT_MIN; for(int i=0; i 0) { arr[i] = i; freqArr[i]--; } } printArr(arr, n); } void sortChars(char arr[], int n) { for(int i=1; i= 0 && arr[prev] < curr) { arr[prev+1] = arr[prev]; prev--; } swap(arr[prev+1], curr); } printArr(arr, n); } int main() { int arr[5] = {5, 4, 1, 3, 2}; //bubbleSort(arr, 5); //selectionSort(arr, 5); //insertionSort(arr, 5); int arr2[8] = {1, 4, 1, 3, 2, 4, 3, 7}; //countSort(arr2, 8); sort(arr2, arr2+8); printArr(arr2, 8); char ch[] = { 'f', 'b', 'a', 'e', 'c', 'd'}; sortChars(ch, 6); return 0; } ================================================ FILE: 13_2DArray/2DArrays.cpp ================================================ #include using namespace std; void printSpiral(int matrix[][4], int n, int m) { int scol = 0, srow = 0; int ecol = m-1, erow = n-1; while(srow <= erow && scol <= ecol) { //top for(int j=scol; j<=ecol; j++) { cout << matrix[srow][j] << " "; } //right for(int i=srow+1; i<=erow; i++) { cout << matrix[i][ecol] << " "; } //bottom for(int j=ecol-1; j>=scol; j--) { if(srow == erow) { break; } cout << matrix[erow][j] << " "; } //left for(int i=erow-1; i>=srow+1; i--) { if(scol == ecol) { break; } cout << matrix[i][scol] << " "; } srow++; scol++; erow--; ecol--; } cout << endl; } void diagonalSum(int mat[][4], int n) { int sum = 0; //O(n^2) for(int i=0; i sum = " << sum << endl; //O(n) sum = 0; for(int i=0; i sum = " << sum << endl; } bool search(int mat[][4], int n, int m, int key) { int i=0, j=m-1; while(i < n && j >= 0) { if(mat[i][j] == key) { cout << "found at (" << i << "," << j << ")\n"; return true; } else if(mat[i][j] > key) { //go left j--; } else { //go right i++; } } cout << "key NOT found\n"; return false; } void func(int (*ptr)[4]) { cout << ptr << endl; cout << ptr+1 << endl; //address(pointer) of row cout << "0th row address" << ptr << endl; cout << "1st row address" << (ptr+1) << endl; //actual row cout << "0th row start" << *ptr << endl; cout << "1st row start" << *(ptr+1) << endl; //to get j=2 column in i=0 row cout << "(0, 2) = " << *(*ptr+2) << endl; //to get j=2 column in i=1 row cout << "(1, 2) = " << *(*(ptr+1)+2) << endl; } int main() { int matrix[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int matrix2[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; printSpiral(matrix, 4, 4); //Expected : 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 printSpiral(matrix2, 3, 4); diagonalSum(matrix, 4); int mat[4][4] = {{10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; search(mat, 4, 4, 33); search(mat, 4, 4, 100); //Pointers & 2D Arrays func(matrix); return 0; } ================================================ FILE: 14_String/strings.cpp ================================================ #include #include #include using namespace std; //Convert to UpperCase void toUpper(char str[], int n) { for(int i=0; i= 'A' && str[i] <= 'Z') { continue; } else { int diff = str[i] - 'a'; str[i] = 'A' + diff; } } } //Reverse of a char Array void reverse(char str[], int n) { int st = 0, end = n-1; while(st < end) { swap(str[st++], str[end--]); } } //Valid Palindrome bool isValid(char str[], int n) { int st = 0, end = n-1; while(st < end) { if(str[st++] != str[end--]) { cout << "not valid"; return false; } } cout << "valid"; return true; } //Valid Anagram bool isAnagram(string s, string t) { if(s.length() != t.length()) { return false; } int count[26] = {0}; for(int i=0; i functions /*strcpy(word, "c++"); cout << "now your word is : " << word << endl; strcat(word, " is my favorite"); cout << word << endl; cout << strcmp("hello", "hello") << endl; cout << strcmp("abc", "xyz") << endl;*/ //C++ Strings string str; getline(cin, str); cout << str << endl; //String Member Functions cout << str.length() << endl; cout << str.at(0) << endl; cout << str.substr(2, 3) << endl; cout << str.find("college") << endl; cout << str.find("xyz") << endl; return 0; } ================================================ FILE: 15_Vector/vectors.cpp ================================================ #include #include using namespace std; // Pair Sum vector twoSum(vector& nums, int target) { int st = 0, end = nums.size()-1; vector ans; while(st < end) { int sum = nums[st] + nums[end]; if(sum == target) { ans.push_back(st+1); ans.push_back(end+1); break; } else if(sum > target) { end--; } else { st++; } } return ans; } int main() { //Dynamic Allocation & Deallocation //Example - 1 int *ptr = new int; *ptr = 100; cout << *ptr << endl; delete ptr; //1D Dynamic Array int size; cout << "enter size of array : "; cin >> size; int *arr = new int[size]; for(int i=0; i> rows; cout << "enter cols : "; cin >> cols; int **matrix = new int*[rows]; for(int i=0; i vec1; vector vec2 = {1, 2, 3, 4}; vector vec3(5, -1); vector vec = {1, 2, 3, 4}; cout << vec.size() << endl; cout << vec.capacity() << endl; //print elements for(int i=0; i> matrix = {{1}, {2, 3}, {4, 5, 6}}; for(int i=0; i #include using namespace std; bool isPowerOf2(int num) { if((num & (num-1)) == 0) { return true; } else { return false; } } void updateIthBit(int num, int i, int val) { num = num & ~(1 << i); int mask = val << i; num = num | mask; cout << num << endl; } void clearLastIBits(int num, int i) { int mask = (~0) << i; num = num & mask; cout << num << endl; } void clearBitsInRange(int num, int i, int j) { int a = (~0) >> (j+1); int b = (1 << i) - 1; int mask = a | b; num = num & mask; cout << num << endl; } int countSetBits(int num) { int count = 0; while(num > 0) { if(num & 1) { count++; } num = num >> 1; } cout << count << endl; return count; } //calculate x^n int fastExponentiation(int x, int n) { int ans = 1; while(n > 0) { int lastBit = n & 1; if(lastBit) ans = ans * x; x = x*x; n = n >> 1; } cout << ans << endl; return ans; } int main() { /* Binary Operators - AND, OR, XOR */ int x = 3, y = 5; cout << (x & y) << endl; cout << (x | y) << endl; cout << (x ^ y) << endl; //Binary NOT cout << ~0 << endl; cout << ~6 << endl; //Binary Shift cout << (7 << 2) << endl;// same as (7 * 2^2) cout << (7 >> 2) << endl;// same as (7 / 2^2) //Practice Qs cout << ~4 << endl; cout << (8 >> 1) << endl; //Odd or Even int num = 7; bool isOdd = num & 1; cout << (isOdd ? "odd" : "even") << endl; //Get ith bit num = 6; int i = 2; int mask = 1 << i; if(num & mask) { cout << "bit is 1\n"; } else { cout << "bit is 0\n"; } //Set ith bit num = 6; i = 3; mask = 1 << i; num = num | mask; cout << num << endl; //14 is expected; //Clear ith Bit num = 6; i = 1; mask = ~(1 << i); num = num & mask; cout << num << endl; //4 is expected; //Power of 2 cout << isPowerOf2(8) << endl; cout << isPowerOf2(7) << endl; //Update ith Bit updateIthBit(7, 2, 0); updateIthBit(7, 3, 1); //Clear last i bits clearLastIBits(15, 2); //Count Set Bits; countSetBits(10); countSetBits(7); //Fast Exponentiation fastExponentiation(3, 4); return 0; } ================================================ FILE: 17_OOPS1/oops1.cpp ================================================ #include #include using namespace std; class Student { private: float cgpa; public: string name; //Setter void setCgpa(float newCgpa) { if(newCgpa < 0) { cout << "Invalid Data\n"; return; } cgpa = newCgpa; } //Getter float getCgpa() { return cgpa; } void getPercentage() { cout << (cgpa * 10) << "% \n"; } }; class Car { string name; int price; public: int *mileage; //Contructor Car() { cout << "Creating & Initializing a new car..\n"; } //Parameterized Contructor Car(string name, int price) { cout << "Creating & Initializing a new car..\n"; this->name = name; this->price = price; mileage = new int; *mileage = 12; } //Custom Copy Constructor Car(Car &original) { cout << "copying..\n"; name = original.name; price = original.price; mileage = new int; *mileage = *original.mileage; } //Getter string getName() { return name; } int getPrice() { return price; } int getMileage() { return *mileage; } //Setter // void setMileage(int mileage) { // mileage = &mileage; // } ~Car() { cout << "object deletion..\n"; if(mileage != NULL) { delete mileage; mileage = NULL; } } }; //Inheritance class Animal { string color; public: void eat() { cout << "eats\n"; } void breathe() { cout << "breathes\n"; } }; class Fish : public Animal { int fins; public: void swim() { cout << "swims\n"; } }; int main() { // Student s1; // cout << sizeof(s1) << endl; // s1.name = "shradha"; // cout << s1.name << endl; // //Setter // s1.setCgpa(9.0); // //Getter // cout << s1.getCgpa() << endl; // s1.getPercentage(); //Contructors // Car c1("maruti 800", 4); // cout << c1.getName() << endl; // cout << c1.getMileage() << endl; //Default Copy Constructor // Car c2(c1); // cout << "**************\n"; // cout << c1.getName() << endl; // cout << c1.getPrice() << endl; // cout << c2.getMileage() << endl; // *c2.mileage = 15; // cout << c2.getMileage() << endl; // cout << c1.getMileage() << endl; //Inheritance Fish f1; f1.eat(); f1.swim(); return 0; } ================================================ FILE: 18_OOPS2/oops2.cpp ================================================ #include #include using namespace std; //Function Overloading class Print { public: void show(int x) { cout << "int : " << x << endl; } void show(string str) { cout << "string : " << str << endl; } }; //Operator Overloading class Complex { int real; int img; public: Complex(int r, int i) { real = r; img = i; } void showNum() { cout << real << " + " << img << "i\n"; } Complex operator - (Complex &obj) { int resReal = this->real - obj.real; int resImg = this->img - obj.img; Complex res(resReal, resImg); return res; } Complex operator + (Complex &obj) { int resReal = this->real + obj.real; int resImg = this->img + obj.img; Complex res(resReal, resImg); return res; } }; //Function Overriding & Virtual Function class Parent { public: void show() { cout << "parent show\n"; } virtual void hello() { cout << "hello from parent\n"; } }; class Child : public Parent { public: void show() { cout << "child show\n"; } void hello() { cout << "hello from child\n"; } }; //Abstract Classes & Pure Virtual Functions class Shape { //This is an abstract class public: virtual void draw() = 0; //Pure Virtual Function }; class Square : public Shape { public: void draw() { cout << "drawing a rectangle\n"; } }; class Circle : public Shape { public: void draw() { cout << "drawing a circle\n"; } }; //Static void counter() { static int count = 0; count++; cout << "count : " << count << endl; } class Example { public: Example() { cout << "constructor\n"; } ~Example() { cout << "destructor\n"; } }; //Friend Class & Function class A { string secret = "private secret"; friend class B; friend void shareSecret(A &obj); }; class B { public: void showSecret(A &obj) { cout << obj.secret << endl; } }; void shareSecret(A &obj) { cout << obj.secret << endl; } int main() { Print p1; p1.show(50); p1.show("apnacollege"); Complex num1(1, 2); Complex num2(3, 4); Complex res = num1 + num2; res.showNum(); Child c1; c1.show(); Child c2; Parent *par1; par1 = &c2; //Binding at runtime par1->hello(); Circle cir1; Square squ1; cir1.draw(); squ1.draw(); counter(); counter(); counter(); //Static object int x = 0; if(x == 0) { static Example eg1; } cout << "exiting main function.\n"; A a1; B b1; b1.showSecret(a1); shareSecret(a1); return 0; } ================================================ FILE: 19_Recursion1/recursion1.cpp ================================================ #include #include #include using namespace std; //Simple Recursive Function with Stack Overflow void func() { cout << "function call\n"; func(); } //Factorial int factorial(int n) { if(n == 1) { return 1; } return n * factorial(n-1); } //Print Decreasing void print(int n) { if(n == 0) { return; } cout << n << " "; print(n-1); } //Sum of N Natural Numbers int sum(int n) { if(n == 1) { return 1; } return n + sum(n-1); } //Nth Fibonacci int fibonacci(int n) { if(n == 0 || n == 1) { return n; } return fibonacci(n-1) + fibonacci(n-2); } //Is Array Sorted bool isSorted(int arr[], int i, int n) { if(i == n-1) { return true; } if(arr[i] > arr[i+1]) { return false; } return isSorted(arr, i+1, n); } //First Occurrence int firstOccur(vector vec, int target, int i) { if(i == vec.size()) { return -1; } if(vec[i] == target) { return i; } return firstOccur(vec, target, i+1); } //Last Occurrence int lastOccur(vector vec, int target, int i) { if(i == vec.size()) { return -1; } int idxFound = lastOccur(vec, target, i+1); if(idxFound == -1 && vec[i] == target) { return i; } return idxFound; } //X^N int pow(int x, int n) { if(n == 0) { return 1; } int halfPow = pow(x, n/2); int halfPowSquare = halfPow * halfPow; if(n % 2 == 0) { //even return halfPowSquare; } else { return x * halfPowSquare; } } int main() { cout << factorial(5) << endl; print(6); cout << endl; cout << sum(5) << endl; cout << fibonacci(6) << endl; int arr1[5] = {1, 2, 3, 4, 5}; int arr2[5] = {1, 2, 4, 3, 5}; cout << isSorted(arr1, 0, 5) << endl; cout << isSorted(arr2, 0, 5) << endl; vector vec = {1, 2, 3, 3, 3, 4}; cout << firstOccur(vec, 3, 0) << endl; cout << lastOccur(vec, 3, 0) << endl; cout << pow(2, 10) << endl; return 0; } ================================================ FILE: 20_Recursion2/rec2.cpp ================================================ #include #include using namespace std; //Tiling Problem int countWays(int n) { if(n == 0 || n == 1) { return 1; } //vertical choice int ways1 = countWays(n-1); //horizonal choice int ways2 = countWays(n-2); return ways1 + ways2; } //Remove Duplicates void removeDuplicates(string str, int i, bool map[26], string ans) { if(i == str.length()) { cout << "ans : " << ans << endl; return; } int mapIdx = (int)(str.at(i) - 'a'); if(map[mapIdx]) { removeDuplicates(str, i+1, map, ans); } else { map[mapIdx] = true; removeDuplicates(str, i+1, map, ans+str.at(i)); } } //Friends Pairing Problem int pairFriends(int n) { if(n == 1 || n == 2) { return n; } return pairFriends(n-1) + (n-1) * pairFriends(n-2); } //Binary Strings Problem void binStrings(int n, string ans, int lastPlace) { if(n == 0) { cout << ans << endl; return; } binStrings(n-1, ans+'0', 0); if(lastPlace != 0) { binStrings(n-1, ans+'1', 1); } } void binStrings(int n, string ans) { if(n == 0) { cout << ans << endl; return; } binStrings(n-1, ans+'0'); if(ans[ans.size()-1] != '1') { binStrings(n-1, ans+'1'); } } int main() { cout << countWays(4) << endl; string ans = ""; bool map[26] = {false}; removeDuplicates("appnnacollege", 0, map, ans); //apncoleg cout << pairFriends(3) << endl; ans = ""; //binStrings(3, ans, 0); binStrings(3, ans); return 0; } ================================================ FILE: 21_Divide_and_Conquer/divideAndConquer.cpp ================================================ #include #include using namespace std; void printArr(int arr[], int n) { for(int i=0; i temp; int i=si, j=mid+1; while(i <= mid && j <= ei) { if(arr[i] <= arr[j]) { temp.push_back(arr[i++]); } else { temp.push_back(arr[j++]); } } while(i <= mid) { temp.push_back(arr[i++]); } while(j <= ei) { temp.push_back(arr[j++]); } //copy back to original for(int idx=si, x=0; idx<=ei; idx++) { arr[idx] = temp[x++]; } } void mergeSort(int arr[], int si, int ei) { if(si >= ei) { return; } int mid = si + (ei - si)/2; mergeSort(arr, si, mid); mergeSort(arr, mid+1, ei); merge(arr, si, mid, ei); } int partition(int arr[], int si, int ei) { int pivot = arr[ei]; int i=si-1; for(int j=si; j= ei) { return; } int pivotIdx = partition(arr, si, ei); quickSort(arr, si, pivotIdx-1); //left quickSort(arr, pivotIdx+1, ei); //right } int search(int arr[], int si, int ei, int tar) { if(si > ei) { return -1; } int mid = si + (ei - si)/2; if(arr[mid] == tar) { return mid; } if(arr[si] <= arr[mid]) { //Line 1 if(arr[si] <= tar && tar <= arr[mid]) { //go left return search(arr, si, mid-1, tar); } else { //go right return search(arr, mid+1, ei, tar); } } else { //Line2 if(tar >= arr[mid] && tar <= arr[ei]) { //go right return search(arr, mid+1, ei, tar); } else { //go left return search(arr, si, mid-1, tar); } } } int main() { int arr[6] = {6, 3, 7, 5, 2, 4}; int n = 6; //mergeSort(arr, 0, n-1); quickSort(arr, 0, n-1); printArr(arr, n); int arr2[7] = {4, 5, 6, 7, 0, 1, 2}; int tar = 0; cout << "idx : " << search(arr2, 0, 6, tar) << endl; return 0; } ================================================ FILE: 24_Backtracking/backtracking.cpp ================================================ #include #include #include using namespace std; void printArr(int arr[], int n) { for(int i=0; i> board) { int n = board.size(); for(int i=0; i> board, int row, int col) { int n = board.size(); //vertical for(int j=0; j=0 && j>=0; i--, j--) { if(board[i][j] == 'Q') { return false; } } //diagonal right for(int i=row-1, j=col+1; i>=0 && j> board, int row) { int n = board.size(); if(row == n) { printBoard(board); return 1; } int count = 0; for(int j=0; j= n || j >= m) { return 0; } int totWays = 0; //go right totWays += gridWays(i, j+1, n, m); //go down totWays += gridWays(i+1, j, n, m); return totWays; } bool isSafe(int sudoku[9][9], int row, int col, int val) { //same col for(int i=0; i<9; i++) { if(sudoku[i][col] == val) { return false; } } //same row for(int j=0; j<9; j++) { if(sudoku[row][j] == val) { return false; } } //same 3x3 grid int sr = (row/3) * 3; int sc = (col/3) * 3; for(int i=sr; i> board; for(int i=0; i newRow; for(int j=0; j using namespace std; class Node { public: int data; Node* next; Node(int data) { this->data = data; next = NULL; } ~Node() { if(next != NULL) { delete next; next = NULL; } } }; class List { Node* head; Node* tail; public: List() { head = NULL; tail = NULL; } void push_front(int val) { Node* newNode = new Node(val); if(tail == NULL) { head = tail = newNode; } else { newNode->next = head; head = newNode; } } void push_back(int val) { Node* newNode = new Node(val); if(tail == NULL) { head = tail = newNode; } else { tail->next = newNode; tail = newNode; } } void printList() { Node* temp = head; while(temp != NULL) { cout << temp->data << " -> "; temp = temp->next; } cout << "NULL\n"; } void insert(int val, int pos) { if(pos == 0) { push_front(val); return; } Node* temp = head; int i=0; while(temp != NULL && inext; i++; } if(temp == NULL) { cout << "Invalid position\n"; return; } Node* newNode = new Node(val); newNode->next = temp->next; temp->next = newNode; } void pop_front() { if(head == NULL) { return; } Node* temp = head; head = head->next; temp->next = NULL; delete temp; } void pop_back() { if(head == NULL) { //0 els return; } if(head->next == NULL) { //1 el delete head; head = NULL; return; } Node* temp = head; while(temp->next->next != NULL) { temp = temp->next; } //temp has tail's prev temp->next = NULL; delete tail; tail = temp; } ~List() { if(head != NULL) { delete head; head = NULL; } } int searchItr(int key) { Node* temp = head; int idx = 0; while(temp != NULL) { if(temp->data == key) { return idx; } temp = temp->next; idx++; } return -1; } int searchRec(int key) { return searchHelper(head, key); } int searchHelper(Node* h, int key) { if(h == NULL) { return -1; } if(h-> data == key) { return 0; //current idx } int ans = searchHelper(h->next, key); if(ans == -1) { return -1; } return ans + 1; } void reverseLL() { Node* prev = NULL; Node* curr = head; while(curr != NULL) { Node* next = curr->next; curr->next = prev; prev = curr; curr = next; } head = prev; } int sizeLL() { Node* temp = head; int sz = 0; while(temp != NULL) { temp = temp->next; sz++; } return sz; } void removeNth(int n) { int size = sizeLL(); cout << "size : " << size << endl; if(n == size) { pop_front(); return; } Node* temp = head; for(int i=1; inext; } Node* toDel = temp->next; //node to delete temp->next = temp->next->next; } }; int main() { List ll; ll.push_front(5); ll.push_front(4); ll.push_front(3); ll.push_front(2); ll.push_front(1); ll.printList(); ll.removeNth(2); //delete 4 ll.printList(); return 0; } ================================================ FILE: 26_LinkedList2/doubly_linkedlist.cpp ================================================ #include using namespace std; class Node { public: int data; Node* next; Node* prev; Node(int data) { this->data = data; next = prev = NULL; } }; class DoublyList { public: Node* head; Node* tail; DoublyList() { head = NULL; tail = NULL; } void push_front(int val) { Node* newNode = new Node(val); if(head == NULL) { head = tail = newNode; } else { head->prev = newNode; newNode->next = head; head = newNode; } } void printList() { Node* temp = head; while(temp != NULL) { cout << temp->data << " <=> "; temp = temp->next; } cout << "NULL" << endl; } void pop_front() { cout << "deleting : " << head->data << endl; Node* temp = head; head = head->next; if(head != NULL) { head->prev = NULL; } temp->next = NULL; delete temp; } }; int main() { DoublyList dll; dll.push_front(3); dll.push_front(2); dll.push_front(1); dll.printList(); dll.pop_front(); dll.printList(); } ================================================ FILE: 26_LinkedList2/linkedlist.cpp ================================================ #include #include #include using namespace std; class Node { public: int data; Node* next; Node(int data) { this->data = data; next = NULL; } // ~Node() { // if(next != NULL) { // delete next; // next = NULL; // } // } }; class List { public: Node* head; Node* tail; List() { head = NULL; tail = NULL; } void push_front(int val) { Node* newNode = new Node(val); if(tail == NULL) { head = tail = newNode; } else { newNode->next = head; head = newNode; } } void push_back(int val) { Node* newNode = new Node(val); if(head == NULL) { head = tail = newNode; } else { tail->next = newNode; tail = newNode; } } void printList() { Node* temp = head; while(temp != NULL) { cout << temp->data << " -> "; temp = temp->next; } cout << "NULL\n"; } void insert(int val, int pos) { if(pos == 0) { push_front(val); return; } Node* temp = head; int i=0; while(temp != NULL && inext; i++; } if(temp == NULL) { cout << "Invalid position\n"; return; } Node* newNode = new Node(val); newNode->next = temp->next; temp->next = newNode; } void pop_front() { if(head == NULL) { return; } Node* temp = head; head = head->next; temp->next = NULL; delete temp; } void pop_back() { if(head == NULL) { //0 els return; } if(head->next == NULL) { //1 el delete head; head = NULL; return; } Node* temp = head; while(temp->next->next != NULL) { temp = temp->next; } //temp has tail's prev temp->next = NULL; delete tail; tail = temp; } // ~List() { // if(head != NULL) { // delete head; // head = NULL; // } // } }; //cycle detection bool isCycle(Node* head) { Node* slow = head; Node* fast = head; while(fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if(slow == fast) { return true; } } return false; } void removeCycle(Node* head) { Node* slow = head; Node* fast = head; bool isCycle = false; while(fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if(slow == fast) { isCycle = true; break; } } if(!isCycle) { return; } //Removing Loop slow = head; if(slow == fast) { //special case when tail is connected to head while(fast->next != slow) { fast = fast->next; } fast->next = NULL; } else { Node* prev = fast; while(slow != fast) { prev = fast; slow = slow->next; fast = fast->next; } //prev is the last node prev->next = NULL; } } Node* splitAtMid(Node* head) { Node* slow = head; Node* fast = head; Node* prev = NULL; while(fast != NULL && fast->next != NULL) { prev = slow; slow = slow->next; fast = fast->next->next; } if(prev != NULL) { prev->next = NULL; } return slow; } Node* merge(Node* h1, Node*h2) { List ans; Node* i = h1; Node* j = h2; while(i != NULL && j != NULL) { if(i->data <= j->data) { ans.push_back(i->data); i = i->next; } else { ans.push_back(j->data); j = j->next; } } while(i != NULL) { ans.push_back(i->data); i = i->next; } while(j != NULL) { ans.push_back(j->data); j = j->next; } return ans.head; } Node* mergeSort(Node* head) { if(head == NULL || head->next == NULL) { return head; } Node* rightHead = splitAtMid(head); Node* sortedLeft = mergeSort(head); Node* sortedRight =mergeSort(rightHead); return merge(sortedLeft, sortedRight); } Node* reverse(Node* head) { Node* prev = NULL; Node* curr = head; while(curr != NULL) { Node* next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; // prev is head } void printList(Node* head) { Node* temp = head; while(temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } Node* zigzag(Node* head) { Node* rightHead = splitAtMid(head); Node* rightRev = reverse(rightHead); //alternate merging Node* left = head; Node* right = rightRev; Node* nextLeft = NULL; Node* nextRight = NULL; Node* tail = head; while(left != NULL && right != NULL) { nextLeft = left->next; left->next = right; nextRight = right->next; right->next = nextLeft; tail = right; left = nextLeft; right = nextRight; } if(right != NULL) { tail->next = right; } return head; } int main(){ List ll; //QS : Cycle Detection & Removal /* ll.push_front(4); ll.push_front(3); ll.push_front(2); ll.push_front(1); ll.tail->next = ll.head; //creating a cycle cout << isCycle(ll.head) << endl; removeCycle(ll.head); cout << isCycle(ll.head) << endl; ll.printList(); */ //QS : Merge Sort the Linked List // ll.push_front(1); // ll.push_front(2); // ll.push_front(3); // ll.push_front(4); // ll.printList(); // ll.head = mergeSort(ll.head); // ll.printList(); //QS : Zig Zag Linked List ll.push_front(5); ll.push_front(4); ll.push_front(3); ll.push_front(2); ll.push_front(1); ll.printList(); ll.head = zigzag(ll.head); ll.printList(); } ================================================ FILE: 26_LinkedList2/list_using_stl.cpp ================================================ #include #include #include using namespace std; void printList(list ll) { list::iterator itr; for(itr=ll.begin(); itr!=ll.end(); itr++) { cout << *itr << " "; } cout << endl; } int main() { list ll; ll.push_front(2); ll.push_front(1); ll.push_back(3); ll.push_back(4); cout << "size : " << ll.size() << endl; printList(ll); cout << "head = " << ll.front() << endl; cout << "tail = " << ll.back() << endl; ll.pop_front(); ll.pop_back(); printList(ll); return 0; } ================================================ FILE: README.md ================================================ # Cpp-DSAClasses This repo contains the codes of C++ DSA Batch of Apna College.