Data Types and Variables-: Int Int Int Sizeof
Data Types and Variables-: Int Int Int Sizeof
int main() {
int a = 123;
int size = sizeof(a);
cout << "Size of a: " << size << endl;
}
int a = 5;
In this case, 5 in binary is “101” which is 3 bits but, the total space of an int is 32 bits.
As a result, the first 29 bits are stored as 0.
5=00000000000000000000000000000101
In case of a character like ‘a’, we consider the binary value of the ASCII code, in this
case, ‘97’. Thus, ‘a’ = 0 1 1 0 0 0 0 1 as ‘97’ = 1 1 0 0 0 0 1.
int main() {
int a = 'a';
cout << a << endl; //Output: 97 (ASCII Code)
char ch = 98;
cout << ch << endl; //Output: b (ASCII Value)
}
Logical Operator-
1. &&- And
2. || - Or
3. ! - Reverse
int main() {
//Normal integer input
int a,b;
cin >> a >> b;
While Loop-
int main() {
int n;
cin >> n;
int i = 1;
int sum = 0;
while(i<=n) {
sum = sum + i;
i = i + 1;
}
Pattern Problems-
****
****
****
****
*/
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
int i = 1;
while(i<=n) {
int j = 1;
while(j<=n) {
cout << "*";
j++;
}
cout << endl;
i++;
}
}
/*
1 1 1
2 2 2
3 3 3
*/
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
int i = 1;
while(i<=n) {
int j = 1;
while(j<=n) {
cout << i;
j++;
}
cout << endl;
i++;
}
}
/*
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
*/
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
int i = 1;
while(i<=n) {
int j = 1;
while(j<=n) {
cout << j;
j++;
}
cout << endl;
i++;
}
}
/*
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
*/
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
int i = 1;
int count = 1;
while(i<=n) {
int j = 1;
while(j<=n) {
cout << count << " ";
count++;
j++;
}
cout << endl;
i++;
}
}
/*
*
**
***
****
*/
#include<iostream>
using namespace std;
int main() {
int n = 4;
int row = 1;
while(row<=n) {
int col = 1;
while(col<=row) {
cout << "*";
col++;
}
cout << endl;
row++;
}
}
Bitwise Operator-
AND (&)
X Y Result
0 0 0
0 1 0
1 0 0
1 1 1
OR (|)
X Y Result
0 0 0
0 1 1
1 0 1
1 1 1
XOR (^)
X Y Result
0 0 0
0 1 1
1 0 1
1 1 0
Left Shift- Shift the binary to the left and add 0 at the end.
Right Shift- Shift the binary to the right and add 0 at the start.
For Loop-
int main() {
int n;
cout << "Enter N: " << endl;
cin >> n;
int sum = 0;
Fibonacci Series-
#include<iostream>
using namespace std;
int main() {
int n = 10;
int a = 0;
int b = 1;
a = b;
b = nextNumber;
}
}
class Solution {
public:
int hammingWeight(uint32_t_n) {
int count = 0;
while(n!=0) {
//checking the last bit
if(n&1) {
count++;
}
//right shift till n=0
n = n>>1;
}
return count;
}
}
class Solution {
public:
int subtractProductAndSum(int n) {
int prod = 1;
int sum = 0;
while(n!=0) {
int digit = n%10;
prod *= digit;
sum += digit;
n /= 10;
}
int answer = prod - sum;
return answer;
}
};
Decimal to Binary-
1. Divide by 2
2. Store remainder
3. Repeat the above 2 steps until n!=0
4. Reverse the remainder list
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int n;
cin >> n;
int ans = 0;
int i = 0;
while(n!=0) {
int bit = n&1;
ans = (bit * pow(10,i)) + ans; //(10^0 x digit) + answer
n = n>>1; //isse divide by 2 ho jata hai
i++;
}
cout << "Answer: " << ans << endl;
}
Binary to Decimal-
1. If the bit is 1 then add 2place to the final answer
2. If the bit is 0 then ignore
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int n=110;
int i = 0, ans = 0;
while(n!=0) {
int digit = n%10;
if(digit == 1) {
ans += pow(2, i);
}
n /= 10;
i++;
}
cout << ans << endl;
}
(Q3) Given a 32-bit integer x, return x with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range, then return 0.
class Solution {
public:
int reverse(int x) {
int ans = 0;
while(x!=0) {
int digit = x%10;
(Q4) Complement of Base 10 Integer, when you flip all the 0 to 1 and all the 1 to
0 in its binary representation.
class Solution {
public:
int bitwiseComplement(int n) {
int m = n;
int mask = 0;
//edge case
if(n==0) {
return 1;
}
while(m!=0) {
mask = (mask<<1) | 1;
m = m >> 1;
}
int ans = (~n) & mask;
return ans;
}
}
(Q5) Power of Two, return True if the number is a power of two. Otherwise,
false.
class Solution {
public:
bool isPowerofTwo(int n) {
int ans = 1;
Switch-
int main() {
char ch = '1';
cout << endl;
switch(ch) {
case 1: cout << "First" << endl;
cout << "First Again" << endl;
break;
Function-
//Power Function
int power(int a, int b) {
long long int ans = 1;
return ans;
}
int main() {
int a, b;
cin >> a >> b;
bool isEven(int n) {
if(n&1) { //if "and" is true then the number is odd
return 0;
}
return 1;
}
int main() {
int num;
cin >> num;
if(isEven(num)) {
cout << "Even" << endl;
}
else {
cout << "Odd" << endl;
}
Passing in Function-
1. Pass by Value- Copy is created (not in case of Arrays)
2. Pass by Reference- Original is sent
Arrays - Similar type of items, they are stored in contiguous locations (101, 102, 103
and so on). They are indexed.
#include <iostream>
using namespace std;
int main() {
//Array name "arr" with 10 blocks having garbage value
int arr[10];
printArray(arr, 10);
//Initialising an Array
int number[3] = {5, 7, 11};
int array[10000] = {0}; //not possible as = {1}
#include <iostream>
using namespace std;
int main() {
cout << "Min Value: " << getMin(num, size) << endl;
}
Reversing an Array-
while(start<=end) {
swap(arr[start], arr[end]);
start++;
end--:
}
}
int main() {
int arr[6] = {1, 4, 0, 5, -2, 15};
int brr[5] = {2, 6, 3, 9, 4};
reverse(arr, 6);
reverse(brr, 5);
printArray(arr, 6);
printArray(brr, 5);
return 0;
}
#include<iostream>
using namespace std;
int main() {
int even[8] = {5, 2, 9, 4, 7, 6, 1, 0};
int odd[5] = {11, 33, 9, 76, 43};
swapAlternative(even, 8);
printArray(even, 8);
return 0;
}
(Q7) One element is unique and all other elements are 2 in number, find the
unique element in the array.
int main() {
int ans = 0;
for(int i=0; i<size; i++) {
ans = ans^arr[i]; //XOR(^): a^a = 0
}
return ans;
}
(Q8) Given an array of integers arr, return true if the number of occurrences of
each value in the array is unique or false otherwise.
class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
vector<int> ans;
int size = arr.size();
int i = 0;
sort(arr.begin(), arr.end());
while(i < size){
int count = 1;
for(int j =i+1; j<size; j++){
if(arr[i] == arr[j]){
count++;
}
else{
break;
}
}
ans.push_back(count);
i = i+count;
}
size = ans.size();
sort(ans.begin(),ans.end());
for(int i = 0; i<size-1; i++){
if(ans[i] == ans[i+1]){
return false;
}
}
return true;
}
};
/*
4 2 1 3 1
0 ^ 4 ^ 2 ^ 1 ^ 3 ^ 1 ^ 1 ^ 2 ^ 3 ^ 4
*/
(Q10) Find All Duplicates in an Array. Given an integer array nums of length n
where all the integers of nums are in the range [1, n] and each integer appears
once or twice, return an array of all the integers that appear twice.
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> ans;
int n = nums.size();
//TLE
int main() {
vector<int> ans;
//Again TLE
int main() {
vector<int> ans;
for(int i=0; i<n; i++) {
int element = arr1[i];
if(element == arr2[j]) {
ans.push_back(element);
arr2[j] = INT_MIN;
break;
}
}
}
return ans;
}
//Perfect
int main() {
int i=0, j=0;
vector<int> ans;
int main() {
vector<vector<int>> ans;
int main() {
int arr[8] = {1, 1, 0, 0, 0, 0, 1, 0};
sortOne(arr, 8);
printArray(arr, 8);
}
Time Complexity-
1. Big O Notation- Upper Bound
2. Theta- For average case complexity
3. Omega- Lower Bound
Levels- O(1) < O(LogN) < O(N) < O(NlogN) < O(N2) < O(N3) < O(2n) < O(N!)
Binary Search-
Time Complexity- O(Log n)
Space Complexity- O(1)
#include<iostream>
using namespace std;
while(start<=end) {
if(arr[mid] == key) {
return mid;
}
int main() {
int even[6] = {2, 4, 6, 8, 12, 18};
int odd[5] = {3, 8, 11, 14, 16};
#include<iostream>
using namespace std;
mid = s + (e-s)/2;
}
}
while(s<=e) {
if(arr[mid] == key) {
ans = mid;
s = mid + 1;
}
else if(key > arr[mid]) {
s = mid + 1;
}
else if(key < arr[mid]) {
e = mid - 1;
}
mid = s + (e-s)/2;
}
}
int main() {
int even[5] = {1, 2, 3, 3, 5};
cout << "First Occurance of 3: " << firstOcc(arr, 5, 3) <<
endl;
cout << "Last Occurance of 3: " << lastOcc(arr, 5, 3) << endl;
return 0;
}
while(s<e) {
if(arr[mid] < arr[mid+1]) {
s = mid + 1;
}
else{
e = mid;
}
mid = s + (e-s)/2;
}
return s;
}
#include<iostream>
using namespace std;
while(s<e) {
if(arr[mid] >= arr[0]) {
s = mid+1;
}
else{
e = mid;
}
mid = s + (e-s)/2;
}
return s; //return e; also works
}
int main() {
int arr[5] = {8, 10, 17, 1, 3};
cout << "Pivot: " << getPivot(arr, 5) << endl;
}
if(square == n) {
return mid;
}
if(square < n) {
ans = mid;
s = mid+1;
}
else{
e = mid-1;
}
mid = s + (e-s)/2;
}
return ans;
}
int mySqrt(int x) {
return binarySearch(x);
}
Selection Sort-
Time Complexity- O(n2)
Space Complexity- O(1)
We select the first element and compare it with all the other elements, if any of the
following elements is smaller than the selected element then we swap them. This
goes on till all the elements are sorted. It works on small-size arrays and vectors if
there is a memory constraint.
int main() {
for(int i=0; i<n-1; i++) {
int minIndex = i;
Bubble Sort-
Time Complexity- O(n2), O(n) if the array is sorted
Space Complexity- O(1)
We start at the first element and compare the first two elements, if the first element is
greater than the second element, we swap them. Contnue the process, by the end
the greatest element should be on the right end. Repeat all the steps but exclude the
last element in the next iteration. Keep repeating till the list is sorted.
Insertion Sort-
Time Complexity- O(n2), O(n) in the best case
Space Complexity- O(1)
We start with the first element and then compare every next element with the first
element in the new array to decide whether the element should be placed on the
right or left side.
j--;
}
}
}
while(s<=e) {
swap(v[s], v[e]);
s++;
e--;
}
return v;
}
while(i<n) {
arr3[k++] = arr1[i++];
}
while(j<m) {
arr2[k++] = arr2[j++];
}
}
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int
n) {
for(int i=0; i<n; i++){
nums1[m+i] = nums2[i];
}
sort(nums1.begin(), nums1.end());
}
};
class Solution{
public:
void moveZeroes(vector<int>& nums) {
int i=0;
class Solution{
public:
void rotate(vector<int>& nums, int k) {
vector<int> temp(nums.size());
for(int i=0; i<nums.size(); i++) {
temp[(i+k)%nums.size()] = nums[i];
}
nums = temp;
}
};
class Solution{
public:
bool check(vector<int>& nums) {
int count = 0;
int n = nums.size();
return count<=1;
}
}
//reverse string
void reverse(char name[], int n) {
int s=0;
int e = n-1;
while(s<e) {
swap(name[s++], name[e--]);
}
}
int main() {
char name[20];
cout << "Enter Name: " << endl;
cin >> name;
}
while(s<=e) {
if(toLowerCase(a[s]) != toLowerCase(a[e])) {
return 0;
}
else{
s++;
e--;
}
}
return 1;
}
class Solution {
public:
bool isPalindrome(string s) {
int i = 0;
int n = s.length();
int j = n-1;
while (i<j){
if (!isalnum(s[i])){
i++;
continue;
}
if (!isalnum(s[j])){
j--;
continue;
}
if (tolower(s[i]) != tolower(s[j])) return false;
else {
i++;
j--;
}
}
return true;
}
};
char getMaxOccCharacter(string s) {
int arr[26] = {0};
//copy
strcpy(dest, src);
class Solution {
public:
string removeOccurance(string s, string part) {
while(s.length()!=0 && s.find(part) < s.length()) {
s.erase(s.find(part), part.length());
}
return s;
}
}
class Solution {
private:
bool checkEqual(int a[26], int b[26]) {
for(int i=0; i<26; i++) {
if(a[i] != b[i]) {
return 0;
}
return 1;
}
}
public:
bool checkInclusion(string s1, string s2) {
if(checkEqual(count1, count2)) {
return 1;
}
i++;
if(checkEqual(count1, count2)) {
return 1;
}
}
return 0;
}
}
class Solution {
public:
string removeDuplicates(string s) {
string ans;
ans.push_back(s[0]);
else{
ans.push_back(s[i]);
}
}
return ans;
}
};
class Solution {
public:
int compress(vector<char>& chars) {
int i=0;
int ansIndex = 0;
int n = chars.size();
while(i<n) {
int j = i+1;
while(j<n && chars[i] == chars[j]) {
j++;
}
//store oldchar
chars[ansIndex++] = chars[i];
int count = j-i;
if(count>1) {
string cnt = to_string(count);
for(char ch: cnt) {
chars[ansIndex++] = ch;
}
}
//moving to a new character
i=j;
}
return ansIndex;
}
}
Sieve of Erastosthenes-
class Solution {
public:
int countPrimes(int n) {
int cnt = 0;
vector<bool> prime(n+1, true);
}
};
2D Arrays-
//output
for(int i=0; i<3; i++) {
for(int j=0; j<4; j++) {
cout << arr[i][j];
}
cout << endl;
}
//searching in 2d array
bool isPresent(int arr[][4], int target, int row, int col) {
for(int i=0; i<3; i++) {
for(int j=0; j<4; j++) {
if(arr[i][j] == target) {
return 1;
}
}
}
return 0;
}
int target;
cin >> target;
//row - 3, column - 4
void printSum(int arr[][4], int row, int col) {
for(int row=0; row<3; row++) {
int sum = 0;
for(int col=0; col<4; col++) {
sum += arr[row][col];
}
cout << sum << " ";
}
}
vector<int> ans;
int start = 0;
int end = row*col - 1;
while(start<=end) {
int element = matrix[mid/col][mid%col];
if(element == target) {
return 1;
}
else{
end = mid-1;
}
mid = start + (end-start)/2;
}
return 0;
}
(Q40) Search in a 2D Matrix II- Integers are sorted top to bottom and left to
right
Reference- https://leetcode.com/problems/search-a-2d-matrix-ii/
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = 0;
int col = matrix[0].size() - 1;
else
--col;
}
return false;
}
};
Symbol Table- Data structure created and maintained by the compiler in order to
keep track of the semantics of variables, it stores information about the scope and
binding information.
Pointers-
int num = 5;
Here the value of “5” has an address, for example, “120”. The integer “num” is
associated with this address.
In the case of cout << num; the address (120) is assessed, the value (5) is obtained
and then it is printed.
int main() {
int num = 5;
int main() {
int num = 5;
int *ptr = #
int main() {
int i = 5;
//method 1
int *p = 0;
p = &i;
//method 2
int *q = &i;
}
#include <iostream>
using namespace std;
int main() {
int num = 5;
int a = num;
cout << "Before: " << num << endl; //5
a++;
cout << "After: " << num << endl; //5
int *p = #
cout << "Before: " << num << endl; //5
(*p)++;
cout << "After: " << num << endl; //6
//important concept
int i = 3;
int *t = &i;
return 0;
}
Pointers in Arrays-
int main() {
int arr[10];
cout << "Address of 1st Block: " << arr << endl;
cout << arr[0] << endl;
cout << "Address of 1st Block: " << &arr[0] << endl;
return 0;
int main() {
int a[20] = {1, 2, 3, 5};
cout << &a[0] << endl; //same
cout << &a << endl; //output
cout << a << endl; //hoga
}
int main2() {
int *p = &a[0];
cout << p << endl; //same
cout << *p << endl; //value at a[0]
cout << &p << endl; //address of p not a
}
int main() {
//arr = arr + 1 (error)
Pointers in Character-
int main() {
return 0;
}
Functions in Pointers-
int sum = 0;
for(int i=0; i<n; i++) {
sum += i[arr];
}
return sum;
}
int main() {
int value = 5;
int *p = &value;
print(p);
return 0;
}
Double Pointers-
#include <iostream>
using namespace std;
int main() {
int i = 5;
int *p = &i;
int **p2 = &p;
#include <iostream>
using namespace std;
void update(int **p) {
p2 = p2 + 1; //no change
int main() {
int i = 5;
int *p = &i;
int **p2 = &p;
int main() {
int i = 5;
int &j = i;
i++; //becomes 6
j++; //also becomes 6
}
Pass by Value VS Pass by Reference- Never return using reference variable and
pointer
int main() {
int n = 5;
Bad Practice- Never take array size during runtime, you should input the size during
compilation as the memory is stored in the stack which requires the memory
beforehand.
Stack Memory (Static Allocation)- All the fixed memory, for example, int i = 5; int
arr[50]; char ch. Memory cleans itself.
int main() {
new char;
char *ch = new char; //8 bytes + 1 bytes = 9 bytes
new int;
int *i = new int; //8 bytes + 4 bytes = 12 bytes
//stack //heap
}
int main() {
int n;
cin >> n;
delete []arr;
return 0;
}
2D Dynamic Array-
int main() {
//bad practice - wrong
int m, n;
cin >> m >> n;
int arr[m][n];
}
//arr[n][n]
int main() {
int n;
cin >> n;
//creating a 2d array
int **arr = new int *[n];
for(int i=0; i<n; i++) {
arr[i] = new int[n];
}
//taking input
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
cin >> arr[i][j];
}
}
//taking output
cout << endl;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
//arr[n][m]
int main() {
int row;
cin >> row;
int col;
cin >> col;
//creating a 2d array
int **arr = new int *[row];
for(int i=0; i<row; i++) {
arr[i] = new int[col];
}
//taking input
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++) {
cin >> arr[i][j];
}
}
//taking output
cout << endl;
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
//releasing memory
for(int i=0; i<row; i++) {
delete [] arr[i];
}
delete [] arr;
}
Macros-
#include <iostream>
using namespace std;
int main() {
int r = 5;
double area = PI * r * r;
cout << "Area: " << area << endl;
return 0;
}
Global Variable- We can share values from one function to another using reference
variable, the global variable is a second method, which you should never use.
int main() {
cout << score << endl;
}
int main() {
int a = 1; b = 2; ans = 0;
//long way
if(a>b) {
ans = a;
}
else{
ans = b;
}
Inline Function- If the function is of 1 line then it will become a Inline Function, in
case of up to 3 lines, it might become an inline function. In case of more than 3 lines,
no chance.
int main() {
int a = 1; b = 2; ans = 0;
ans = getMax(a, b); //bts: ans = (a>b) ? a : b;
a = a + 1;
b = b + 1;
Default Arguments-
int main() {
int arr[5] = {1, 4, 7, 8, 9};
int size = 5;
print(arr, size);
}
Recursion- When a function calls itself. When the solution of a bigger problem
depends on the solution of a smaller problem, then it can be solved using recursion.
//Factorial
int factorial(int n) {
if(n==0) {
return 1;
}
return n * factorial(n-1);
}
int main() {
int n;
cin >> n;
return 0;
}
Tail Recursion- Recursive relation at the bottom, below the processing part.
Head Recursion- Recursive relation in the centre, above the processing part.
//Power of 2
#include <iostream>
using namespace std;
int twoPower(int n) {
if(n==0) {
return 1;
}
return 2 * twoPower(n-1);
}
int main() {
int n;
n = 8;
return 0;
}
void print(int n) {
//base case
if(n==0) {
return;
}
//recursive call
print(n-1);
}
int main() {
int n;
n = 8;
print(n);
return 0;
}
class Solution{
public:
int fib(int n) {
if(n<=1) return n;
return fib(n-1)+fib(n-2);
}
};
if(nStairs == 0)
return 1;
//recursive call
int ans = countStairs(n-1) + countStairs(n-2);
return ans;
}
(Q42) Say Digits, 412- Four One Two.
//processing
int digit = n%10;
n = n/10;
//recursive call
sayDigit(n, arr);
cout << arr[digit] << " ";
}
int main() {
string arr[10] = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
int n;
cin >> n;
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
int main() {
int arr[3] = {2, 4, 6};
int size = 3;
return 0;
}
#include<iostream>
using namespace std;
if(arr[0] == k) {
return true;
}
else{
bool remainingPart = linearSearch(arr+1, size-1, k);
return remainingPart;
}
}
int main() {
int arr[5] = {3, 5, 1, 2, 6};
int size = 5;
int key = 2;
if(ans) {
cout << "Present" << endl;
}
else{
cout << "Absent" << endl;
}
}
if(arr[mid] == k) {
return true;
}
if(arr[mid] < k) {
return binarySearch(arr, mid+1, e, k);
}
else{
return binarySearch(arr, s, mid-1, k);
}
}
int main() {
int arr[6] = {2, 4, 6, 10, 14, 18};
int size = 6;
int key = 18;
return 0;
}
#include <iostream>
using namespace std;
//recursive call
reverse(str, i, j);
}
int main() {
string name = "akshat pandey";
reverse(name, 0, name.length()-1);
cout << name << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
string name = "abcba";
if(isPalindrome) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
//recursive call
int ans = power(a, b/2);
//if b is even
if(b%2 == 0) {
return ans * ans;
}
else{
//if b is odd
return a * ans * ans;
}
}
int main() {
int a = 2;
int b = 3;
return 0;
}
//Bubble sort
void sortArray(int *arr, int n) {
//base case
if(n == 0 || n == 1) {
return;
}
int main() {
int arr[5] = {2, 5, 1, 6, 9};
sortArray(arr, 5);
return 0;
}
Merge Sort- Fastest Sorting Algorithm
#include <iostream>
using namespace std;
//copy values
int k = s;
for (int i = 0; i < len1; i++) {
first[i] = arr[k++];
}
k = mid + 1;
for (int i = 0; i < len2; i++) {
second[i] = arr[k++];
}
int mid = (s + e) / 2;
//merge
merge(arr, s, mid, e);
}
int main() {
int arr[5] = {2, 5, 1, 6, 9};
int n = 5;
mergeSort(arr, 0, n - 1);
return 0;
}
int a[n1];
int b[n2];
Quick Sort-
#include<iostream>
using namespace std;
int cnt = 0;
for(int i = s+1; i<=e; i++) {
if(arr[i] <= pivot) {
cnt++;
}
}
//base case
if(s >= e) {
return;
}
//partition karenge
int p = partition(arr, s, e);
int main() {
int arr[5] = {2, 4, 1, 6, 9};
int n = 5;
quickSort(arr, 0, n-1);
return 0;
}
class Solution {
private:
void solve(vector<int> nums, vector<int> output, int index,
vector<vector<int>> &ans) {
//base case
if(index >= nums.size()) {
ans.push_back(output);
return;
}
//exclude
solve(nums, output, index+1, ans);
//include
int element = nums[index];
output.push_back(element);
solve(nums, output, index+1, ans);
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> output;
int index = 0;
solve(nums, output, index, ans);
return ans;
}
};
class Solution{
private:
void solve(string digit, string output, int index,
vector<string> &ans, string mapping[]) {
//base case
if(index >= digit.length()) {
ans.push_back(output);
return;
}
public:
vector<string> letterCombination(string digits) {
vector<string> ans;
if(digits.length() == 0) {
return ans;
}
class Solution {
private:
void solve(vector<int> nums, vector<vector<int>> &ans, int
index){
//base case
if(index >= nums.size()) {
ans.push_back(nums);
return;
}
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
int index = 0;
solve(nums, ans, index);
return ans;
}
};
//base case
if(x == n-1 && y == n-1) {
ans.push_back(path);
return;
}
visited[x][y] = 1;
//4 choices - D, L, R, U
//down
int newx = x+1;
int newy = y;
if(isSafe(newx, newy, n, visited, m)) {
path.push_back('D');
solve(m, n, ans, newx, newy, visited, path);
path.pop_back();
}
//left
newx = x;
newy = y-1;
if(isSafe(newx, newy, n, visited, m)) {
path.push_back('L');
solve(m, n, ans, newx, newy, visited, path);
path.pop_back();
}
//right
int newx = x;
int newy = y+1;
if(isSafe(newx, newy, n, visited, m)) {
path.push_back('R');
solve(m, n, ans, newx, newy, visited, path);
path.pop_back();
}
//up
int newx = x-1;
int newy = y;
if(isSafe(newx, newy, n, visited, m)) {
path.push_back('U');
solve(m, n, ans, newx, newy, visited, path);
path.pop_back();
}
visited[x][y] = 0;
public:
vector<string> findPath(vector<vector<int>> &m, int n) {
vector <string> ans;
if(m[0][0] == 0) {
return ans;
}
int srcx = 0;
int srcy = 0;
vector<vector<int>> visited = m;
//initialising "visited" with 0
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
visited[i][j] = 0;
}
}
#include <iostream>
#include "Hero.cpp"
using namespace std;
class Hero {
//properties
int health;
};
int main() {
//creation of an object
Hero h1;
cout << "Size: " << sizeof(h1) << endl; //empty 1
return 0;
}
Access Modifiers-
class Hero {
public: //accessible everywhere
int health;
class Hero {
//properties
private:
int health;
public:
char level;
int getHealth() {
return health;
}
char getLevel() {
return level;
}
void setHealth(int h) {
health = h;
}
int main() {
//creation of object
Hero ramesh;
cout << "Health: " << ramesh.getHealth() << endl; //1
//use setter
ramesh.setHealth(70); //private
ramesh.level = 'A'; //public
return 0;
}
Static VS Dynamic-
int main() {
//static allocation
Hero a;
a.setHealth(80);
a.setLevel('B');
//dynamically
Hero *b = new Hero;
b->setLevel('A');
b->setHealth(70);
Constructor- When we make an object, for example, “Hero ramesh;”, then behind
the scenes, the code is executing “ramesh.Hero();” function. This is done by default.
class Hero {
Hero() {
cout << "Construction Called" << endl;
}
};
int main() {
//object created statically
cout << "Hi!" << endl;
Hero ramesh;
cout << "Hello!" << endl;
//dynamically
Hero *h = new Hero; //Hero()
}
Parameter Constructor-
class Hero {
Hero() { //dead, due to parameter constructor
cout << "Constructor Called" << endl;
}
Hero(int health) {
this -> health = health;
}
int main() {
//dynamically
Hero *h = new Hero(11);
h -> print();
Hero temp(22, 'B');
temp.print();
class Hero {
//copy constructor
Hero(Hero &temp) {
this->health = temp.health;
this->level = temp.level;
}
};
int main() {
class Hero {
//properties
private:
int health;
public:
char *name;
char level;
Hero() {
cout << "Simple Constructor Called" << endl;
name = new char[100];
}
void setName(char name[]) {
strcpy(this->name, name);
}
//deep copy
Hero(Hero &temp) {
char *ch = new char[strlen(temp.name) + 1];
strcpy(ch, temp.name);
this->name = ch;
int main() {
Hero hero1;
hero1.setHealth(12);
hero1.setLevel('D');
char name[7] = "Babbar";
hero1.setName(name);
hero1.print();
//shallow copy
Hero hero2(hero1);
hero2.print();
hero1.name[0] = 'G';
hero1.print();
}
Assignment Operator-
hero1 = hero2;
class Hero {
//destructor
~Hero() {
cout << "Destructor Called" << endl;
}
};
int main() {
//static- destructor automatically called
Hero a;
return 0;
}
Static Keyword- It creates a data member that belongs to the class, you don’t need
to make an object to access this.
class Hero {
private:
int health;
public:
char *name;
char level;
static int timetoComplete;
};
int main() {
cout << Hero::timetoComplete << endl;
return 0;
}
Static Function- No need to make an object, they don’t have the “this->” keyword.
They can only access static members.
class Hero {
private:
int health;
public:
char *name;
char level;
static int timetoComplete;
int main() {
cout << Hero::random() << endl;
return 0;
}
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
int height;
public:
int getAge() {
return this->age;
}
};
int main() {
Student first;
return 0;
}
Private NA NA NA
#include <iostream>
using namespace std;
class Human {
public:
int height;
int weight;
int age;
public:
int getAge() {
return this->age;
}
void setWeight(int w) {
this->weight = w;
}
};
void sleep() {
cout << "Sleeping" << endl;
}
};
int main() {
Male object1;
cout << object1.age << endl;
}
Types of Inheritance-
1. Single- One class inherit from one class.
class Animal {
public:
int age;
int weight;
public:
void speak() {
cout << "Speaking" << endl;
}
};
};
int main() {
Dog d;
d.speak();
cout << d.age << endl;
}
2. Multi Level- One class inherit from one class and another class inherit from
the second class.
class Animal {
public:
int age;
int weight;
public:
void speak() {
cout << "Speaking" << endl;
}
};
};
};
int main() {
GermanShepher g;
g.speak();
}
public:
void bark() {
cout << "Barking" << endl;
}
};
class Human {
public:
string color:
public:
void speak() {
cout << "Speaking" << endl;
}
}
//multiple inheritance
class Hybrid: public Animal, public Human {
};
int main() {
Hybrid obj1;
obj1.speak();
obj1.bark();
return 0;
}
4. Hierarchical- One class serve as Parent class for more than 1 class.
class A {
public:
void func1() {
cout << "Inside Function 1" << endl;
}
};
class B: public A {
public:
void func2() {
cout << "Insid Function 2" << endl;
}
};
class C: public A {
public:
void func3() {
cout << "Inside Function 3" << endl;
}
};
int main() {
A object1;
object1.func1();
B object2;
object2.func1();
object2.func2();
C object3;
object3.func1();
object3.func2(); //error
object3.func3();
return 0;
}
Inheritance Ambiguity- If C inherits from A and B and they have two same function
names, then ambiguity solves the problem.
class A {
public:
void func1() {
cout << "Inside Function 1" << endl;
}
};
class B: public A {
public:
void func2() {
cout << "Inside Function 2" << endl;
}
};
class C: public A {
public:
void func3() {
cout << "Inside Function 3" << endl;
}
};
int main() {
A object1;
object1.func1();
B object2;
object2.func1();
object2.func2();
C object3;
object3.func1();
object3.func2(); //error
object3.func3();
return 0;
}
2. Operation Overloading-
class B {
void operator+ (B &obj) {
int value1 = this->a;
int value2 = obj.a;
cout << "Output: " << value2 - value1 << endl;
}
};
int main() {
B obj1, obj2;
obj1.a = 4;
obj2.a = 7;
obj1 + obj2;
}
class Animal {
public:
void speak() {
cout << "Speaking" << endl;
}
};
int main() {
Dog obj;
obj.speak(); //Barking
}
Why- It is not possible to change the size of array during run time, in case of vector
the size doubles which is not a optimal case.
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int data) {
this -> data = data;
this -> next = NULL;
}
};
int main() {
Node *node1 = new Node(10);
cout << node1 -> data << endl;
cout << node1 -> next << endl;
return 0;
}
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
//constructor
Node(int data) {
this -> data = data;
this -> next = NULL;
}
//destructor
~Node() {
int value = this -> data;
//memory free
if(this -> next != NULL) {
delete next;
this -> next = NULL;
}
}
};
//insert at start
if(position == 1) {
insertAtHead(head, d);
return;
}
///insert at last
if(temp -> next == NULL) {
insertAtTail(tail, d);
return;
}
int cnt = 1;
while(cnt < position) {
prev = curr;
curr = curr -> next;
cnt++;
}
while(temp != NULL) {
cout << temp -> data << " ";
temp = temp -> next; //temp
}
cout << endl;
}
int main() {
//created a new node
Node *node1 = new Node(10);
cout << node1 -> data << endl;
cout << node1 -> next << endl;
print(head);
InsertAtTail(tail, 12);
print(head);
deleteNode(4, head);
print(head);
return 0;
}
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *prev;
Node *next;
//constructor
Node(int d) {
this -> data = d;
this -> prev = NULL;
this -> next = NULL:
}
};
while(temp != NULL) {
len++;
temp = temp -> next;
}
}
while(temp != NULL) {
cout << temp -> data;
temp = temp -> next;
}
return len;
}
//insert at start
if(position == 1) {
InsertAtHead(head, d);
return;
}
int cnt = 1;
while(cnt < position) {
prev = curr;
curr = curr -> next;
cnt++;
}
delete curr;
}
}
int main() {
print(head);
cout << getLength(head) << endl;
InsertAtHead(head, 11);
print(head);
InsertAtTail(head, 25);
print(head);
return 0;
}
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
//constructor
Node(int d) {
this -> data = d;
this -> next = NULL;
}
~Node() {
int value = this -> data;
if(this -> next != NULL) {
delete next;
next = NULL;
}
}
};
//empty list
if(tail == NULL) {
Node *newNode = new Node(d);
tail = newNode;
newNode -> next = newNode;
}
else{
//non-empty list
Node *curr = tail;
//empty list
if(tail == NULL) {
cout << "List is Empty!" << endl;
return;
}
do {
cout << tail -> data << " ";
tail = tail -> next;
} while(tail != temp);
}
int main() {
Node *tail = NULL;
return 0;
}
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int data) {
this -> data = data;
this -> next = NULL;
}
};
//iterative
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *curr = head;
ListNode *prev = NULL;
while(curr != NULL) {
ListNode *temp = curr -> next;
curr -> next = prev;
prev = curr;
curr = temp;
}
return prev;
}
};
//recursive
Node reverse(Node *head){
if(head == NULL || head -> next == NULL) {
return head;
}
if(temp == head) {
return true;
}
return false;
}
count = 0;
while(curr != NULL && count < k) {
next = curr -> next;
curr -> next = prev;
prev = curr;
curr = next;
}
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
//empty list
if(head == nullptr) {
return nullptr;
}
//non-empty list
ListNode *curr = head;
while(curr != NULL) {
if(curr -> next != NULL & curr -> data == curr -> next
-> data) {
ListNode *next_next = curr -> next -> next;
ListNode *nodeToDelete = curr -> next;
delete(nodeToDelete);
curr -> next = next_next;
}
else{ //not equal
curr = curr -> next;
}
}
return head;
}
};
while(temp != NULL) {
if(visited[temp] == true) {
return true;
}
visited[temp] = true;
temp = temp -> next;
}
return false;
}
if(fast != NULL){
fast = fast -> next;
}
if(slow == fast) {
return 1;
}
}
return false;
}
while(slow != intersection) {
slow = slow -> next;
intersection = intersection -> next;
}
return slow;
}
//approach 1
class Solution {
private:
bool checkPalindrome(vector<int> arr) {
int n = arr.size();
int s = 0;
int e = n-1;
while(s<=e) {
if(arr[s] != arr[e]) {
return false;
}
s++;
e--;
}
return true;
}
public:
bool isPalindrome(ListNode* head) {
vector<int> arr;
ListNode *temp = head;
while(temp != NULL) {
arr.push_back(temp -> val);
temp = temp -> next;
}
return checkPalindrome(arr);
}
};
//approach 2
class Solution{
private:
Node *getMid(Node *head) {
Node *slow = head;
Node *fast = head -> next;
while(curr != NULL) {
next = curr -> next;
curr -> next = prev;
prev = curr;
curr = next;
}
return prev;
}
public:
bool isPalindrome(Node *head) {
if(head -> next == NULL) {
return true;
}
while(head2 != NULL) {
if(head1 -> data != head2 -> data) {
return false;
}
head1 = head1 -> next;
head2 = head2 -> next;
}
return true;
}
};
//Approach 1
Node *sortList(Node *head) {
int zeroCount = 0;
int oneCount = 0;
int twoCount = 0;
temp = head;
while(temp != NULL) {
if(zeroCount != 0) {
temp -> data = 0;
zeroCount--;
}
else if(oneCount != 0) {
temp -> data = 1;
oneCount--;
}
else if(twoCount != 0) {
temp -> data = 2;
twoCount--;
}
temp = temp -> next;
}
return head;
}
//Approach 2
void insertAtTail(Node *&tail, Node *curr) {
tail -> next = curr;
tail = curr;
}
//merge 3 sublist
if(oneHead -> next != NULL) {
zeroTail -> next = oneHead -> next;
}
else{
//1s list is empty
zeroTail -> next = twoHead -> next;
}
//setup head
head = zeroHead -> next;
return head;
if(right == NULL) {
return left;
}
while(left != NULL) {
temp -> next = left;
temp = left;
left = left -> next;
}
while(right != NULL) {
temp -> next = right;
temp = right;
right = right -> next;
}
return result;
}
#include<iostream>
#include<stack>
using namespace std;
int main() {
//creation of stack
stack<int> s;
//basic operations
s.push(2);
s.push(3);
s.pop();
s.top();
if(s.empty()) {
cout << "Stack is Empty!" << endl;
}
else{
cout << "Stack is not Empty!" << endl;
}
s.size();
return 0;
}
#include<iostream>
#include<stack>
using namespace std;
class Stack {
//properties
public:
int *arr;
int top;
int size;
//behaviour
Stack(int size) {
this -> size = size;
arr = new int(size);
top = -1;
}
else{
cout << "Stack OverFlow" << endl;
}
}
void pop() {
if(top >= 0) {
top--;
}
else{
cout << "Stack OverFlow" << endl;
}
}
int peek() {
if(top >= 0) {
return arr[top];
}
else{
cout << "Stack is Empty!" << endl;
return -1;
}
}
bool isEmpty() {
if(top == -1) {
return true;
}
else{
return false;
}
}
}
int main() {
class MinStack {
public:
stack <int> st, s2;
MinStack() {
st.push(val);
}
void pop() {
if(st.top() == s2.top()) {
s2.pop();
}
st.pop();
}
int top() {
return st.top();
}
int getMin() {
return s2.top();
}
};
int main() {
string str = "Akshat";
stack<char> s;
while(!s.empty()) {
char ch = s.top();
ans.push_back(ch);
s.pop();
}
return 0;
}
//recursive call
solve(inputStack, count+1, size);
inputStack.push(num);
}
else{
//for closing bracket
if(!s.empty()) {
char top = s.top();
if(matches(top, ch)) {
s.pop();
}
else{
return false;
}
}
else{
return false;
}
}
}
if(s.empty()) {
return true;
}
else{
return false;
}
}
//recursive call
solve(stack, x);
s.push(num);
}
//recursive call
solve(s, x);
s.push(num);
}
//recursive call
reverseStack(stack);
insertAtBottom(stack, num);
}
int n = stack.top();
stack.pop();
//recursive call
sortedInsert(stack, num);
stack.push(n);
}
//recursive call
sortStack(stack);
sortedInsert(stack, num);
}
(Q70) Stack Discount Problem.
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
stack<int> s;
int x = prices[i];
s.push(x);
return prices;
}
};
stack<int> s;
s.push(-1);
vector<int> ans;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int> left(n);
vector<int> right(n);
stack<pair<int, int>> st;
st = {};
stack<int> s;
int b = s.top();
s.pop();
if(knows(M, a, b, n)) {
s.push(b);
}
else{
s.push(a);
}
}
//row check
bool rowCheck = false;
int zeroCount = 0;
for(int i=0; i<n; i++) {
if(M[candidate][i] == 0) {
zeroCount++;
}
}
//all zeroes
if(zeroCount == n) {
rowCheck = true;
}
//column check
bool columnCheck = false;
int oneCount = 0;
for(int i=0; i<n; i++) {
if(M[i][candidate] == 1) {
oneCount++;
}
}
//all ones
if(oneCount == n-1) {
columnCheck = false;
}