Pages

Sunday, June 29, 2025

Linked List - Part 1 (Includes all operations)

#include <iostream>
#include <vector>
using namespace std;

class Node {
public:
    int data;
    Node* next;




    Node(int val) {
        data = val;
        next = NULL;
    }

    ~Node(){
       
        cout << "~Node " << data << endl;
        if(next != NULL) {
            delete next;
            next = NULL;
        }
    }

};


class List {
    Node* head;
    Node* tail;

public:

    // constructor
    List() {
        head = NULL;
        tail = NULL;
    }


    // Destructor
    ~List()
    {   cout << "~List\n";
        if(head != NULL) {
            delete head;
            head = NULL;
        }
    }



    void push_front(int val) {
        Node* newNode = new Node(val); // dynamic allocation of Node
        // OR Node* newNode(val); // static allocation of Node creation method

        if(head == NULL) {
            head = tail = newNode;
        } else {
            newNode->next = head; // points towards new Node head
            head = newNode; // now head points towards 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";
    }

    // 1->2->3 pos = 25
    void insert(int val, int pos) {
        Node* newNode = new Node(val);

        Node* temp = head;
        for(int i=0; i<pos-1; i++) {
            if(temp == NULL) {
                cout << "position is INVALID\n";
                return;
            }
            temp = temp->next;

        }



        // temp is now at pos-1 i.e. prev/left
        newNode->next = temp->next;
        temp->next = newNode;
    }

    void pop_front() {
        if(head == NULL) {
            cout << "LL is empty\n";
            return;
        }

        Node* temp = head;

        head = head->next;
        temp->next = NULL;
        delete temp;
    }

    void pop_back() {
        Node* temp = head;
        while(temp->next->next != NULL) {
            temp = temp->next;
        }

        temp->next = NULL; // temp = tail's prev
        delete tail;
        tail = temp;
    }


    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 helper(Node* temp, int key) {  // Node* head in some articles if you read...
        if(temp == NULL) { // base case
            return -1;
        }

        if(temp->data == key) {
            return 0;
        }

        int idx = helper(temp->next, key);
        if(idx == -1) {
            return -1;
        }

        return idx+1;
    }

    int searchRec(int key) {
        return helper(head, key);
    }

    void reverse() {
        Node* curr = head;
        Node* prev = NULL;
        tail = head;
        while(curr != NULL) {
            Node* next = curr->next;
            curr->next = prev;

            //updations for next itr
            prev = curr;
            curr = next;

        }

        head = prev;
    }

    int getSize() {
        int sz = 0;
        Node* temp = head;

        while(temp != NULL) {
            temp = temp->next;
            sz++;
        }

        return sz;
    }


    void removeNth(int n) { // O(N); SC: O(1)
        int size = getSize();
        Node* prev = head;
       

        for(int i=1; i<(size-n); i++) { // i=size-n => prev => deletion node prev
            prev = prev->next; // phele temp bolte the, ab prev boldiya
        }

        Node* toDel = prev->next;
        cout << "going to delete : " << toDel->data << endl;
        prev->next = prev->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();  // 1->2->3->4->5->null
       
   
    ll.removeNth(2);
    ll.printList(); // 1->2->3->5->null

    // // // // // //ll.reverse();
    // // // // // //ll.printList();
   
   
   
   
    // // // // //  cout << "Found at Idx: " << ll.searchRec(4) << endl;
   
   
   
    // // // // cout << "Found at Idx: " <<  ll.searchItr(4) << endl;
   
   
    // // // ll.pop_back();
    // // // ll.printList();
   
   
    // // ll.pop_front();
    // // ll.printList();

    // ll.push_back(4);
    // ll.push_back(5);
    // ll.printList(); // 1->2->3->4->5->null

    // ll.insert(100, 2);
    // ll.printList(); // 1->2->100->3->4->5->null


    return 0;
}

Thursday, June 26, 2025

Iterative Search in Linked List in C++

 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;



Friday, June 20, 2025

Merge Sort using divide and conquer approach (With Mistakes noted! this time!)


When writing merge sort next time, ask yourself:

✅ Did I divide properly using si, mid, ei?

✅ Did I initialize i=si and j=mid+1 in merge()?

✅ Did I correctly loop with i <= mid and j <= ei?

✅ Did I merge into a temp vector and copy back?



#include <iostream>

#include <vector>

using namespace std;


void printArray(int arr[], int n) {

    for(int i =0; i<n; i++) {

        cout << arr[i] << " ";

    }

    

    cout << endl;

}


void merge(int arr[], int si, int mid, int ei) {

    int i = si; // Major part of mistake

    int j = mid+1; // Major part of mistake

    vector<int> temp;    // Did Mistake this line 

    

    

    // Merge the two sorted halves

    while (i <= mid && j <= ei) { // Did Mistake this line 

        

        if(arr[i] < arr[j]) {

            temp.push_back(arr[i++]);

        } else {

            temp.push_back(arr[j++]);

        }

    }

    

    

    // Copy remaining elements

    while(i <= mid) {  // Did Mistake this line 

        temp.push_back(arr[i++]);

    }

    

    

    while(j <= ei) {  // Did Mistake this line 

        temp.push_back(arr[j++]);

    }


    // Copy temp back to array

    

    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 main() {

    int arr[] = {1,4, 7,2, 10};

    int n = sizeof(arr)/sizeof(int);


    

    cout << "Original array: ";

    printArray(arr, n);

    

    

    mergeSort(arr, 0, n-1);

    

    cout << "Sorted Array: ";

    printArray(arr, n);

    return 0;

}

Tuesday, June 17, 2025

Bubble Sort in C++

#include <iostream>

using namespace std;



void print(int arr[], int n) {

    for(int i=0; i<n; i++) {

        cout << arr[i] << " ";

    }

    

    cout << endl;

}


void bubbleSort(int arr[], int n) {

    

    // outer loop

    for(int i=0; i<n-1; i++) {

        

        // inner loop

        for(int j=0; j<n-i-1; j++) {

            if(arr[j] > arr[j+1]) { 

                swap(arr[j], arr[j+1]);

            }

        }

    }

    

    

    print(arr, n);

}


int main() {

    int arr[] = {5,3 ,2,4,1};

    int n = sizeof(arr)/sizeof(int);

    

    

    bubbleSort(arr, n);

    

    

    return 0;

}

Binary Search in C++

 #include <iostream>

using namespace std;



//  BInary Search


int binarySearch(int *arr, int key, int n) {

    int si=0;

    int ei=n-1;

    

    

    while(si <= ei) {

        int mid = si + (ei-si)/2;

        if(key == arr[mid]) {

            return mid;

        } else if(key >= arr[mid]) {

            si = mid+1; // right half

        } else {

            si = mid-1; // left half

        }

    }

    

    return -1;

}



int main() {

    int arr[] = {5, 4, 2, 1, 7};

    int n = sizeof(arr)/sizeof(int);

    

    cout << binarySearch(arr, 2, n);

 


    return 0;

}

Factorial of N in C++

 


#include <iostream>

using namespace std;



// Factorial of N


int factorial(int n) {

    if (n == 0) {

        return 1;

    }

    

    return n * factorial(n-1);

}


int main() {

   

    cout << factorial(5);


    return 0;

}

Sum of N numbers in C++

 


#include <iostream>

using namespace std;



// Sum of N numbers in C++


int sum(int n) {

    if(n == 0) {

        return n;

    }

    

    return n + sum(n-1);

}


int main() {

   

    cout << sum(5);


    return 0;

}

Monday, June 16, 2025

Arrange the following words: sun, earth , mercury, mars in Alphabetical(lexicographical order) using Merge Sort in C++

 #include <iostream>

#include <vector>

using namespace std;



void merge(string arr[], int si, int mid, int ei) {

    int m = mid; // correct 

    int i = si; // correct

    vector<string> temp;// i wrote it <vector> which is wrong


    int n = ei; // n

    int j = mid+1;  // j     

    

    while(i<=m && j<=n) {

        if(arr[i] <= arr[j]) {

        temp.push_back(arr[i]);

        i++;

    } else {

        temp.push_back(arr[j]);  

        j++;

    }

}

    

    

    

    

    while(i <= m) {

        temp.push_back(arr[i]);

        i++;

    }

    

    while(j <= n) {

        temp.push_back(arr[j]);

        j++;

    }

    

    

    // mistake: i put this loop inside merge function

    for(int idx=0, x=si; x<=ei; x++) {

        arr[x] = temp[idx++];

    }

    

}   


void mergeSort(string arr[], int si, int ei) {

    if(si >= ei) {

        return; 

    }

    

    int mid = si + (ei-si)/2; // mistakes i forgot the formula of mid

    

    

    mergeSort(arr, si, mid); // left half

    mergeSort(arr, mid+1, ei); // right half

    

    

    merge(arr, si, mid, ei);

    

}


    

void printArray(string arr[], int n) {

    for(int i=0; i<n; i++) {

        cout << arr[i] << " ";

    }

    

    cout << endl;

}


int main() {

    string arr[4] = {"mars", "mercury", "sun", "earth"};

    

    mergeSort(arr, 0, 3);

    

    cout << "Arranged : ";

    printArray(arr, 4);

    

    


    return 0;

}


OUTPUT:


earth mars mercury suns

Sunday, June 15, 2025

Quick Sort algorithm in C++ (University Topic)

 


#include <iostream>

using namespace std;


// quick sort algorithm 

int partition(int arr[], int si, int ei){

    int pivot = arr[ei]; // last element as pivot

    int i = si-1; 

    

    for(int j=si; j<ei; j++) {

        if(arr[j] < pivot) {

            i++;

            swap(arr[i], arr[j]);

        }

    }

    swap(arr[i+1], arr[ei]);

    return i+1;

}


// Quick Sort function

void quickSort(int arr[], int si, int ei) {

    if(si < ei) {

        int pivotIdx = partition(arr, si, ei);

        

        quickSort(arr, si, pivotIdx-1); // sort left part

        quickSort(arr, pivotIdx+1, ei); // sort right part

    }

}



 void printArray(int arr[], int n) {

     for(int i=0; i<n; i++) {

         cout << arr[i] << " ";

     }

     cout << endl;

 }

int main() {

    int arr[] = {10, 5, 6, 7, 2, 1, 3};

    int n = sizeof(arr)/sizeof(int);

    

    cout << "Original Array: "; 

    printArray(arr, n);

    

    quickSort(arr, 0, n-1);

    cout << "Sorted Array: ";

    printArray(arr, n);


    return 0;

}

Thursday, June 12, 2025

Rotated Sorted Array Code in C++

 #include <iostream>

using namespace std;

// Rotated Sorted Code
int search(int arr[], int si , int ei, int tar) { n// O(logn) -> most optimized solution


    int mid = si + (ei-si)/2;
    if(arr[mid] == tar) {
        return mid;
    }

    if(arr[si] <= arr[mid])  // L1
    {
        if(arr[si] <= tar && tar <= arr[mid]) {


            // left half
            return search(arr, si, mid-1, tar);
        } else {
            // right half
            return search(arr, mid-1, ei, tar);
        }
    }
    else {
        // L2
        if(arr[mid] <= tar && tar <= arr[ei]) {
            // right half
            return search(arr, si, mid+1, tar);
        } else  {

            // left half
            return search(arr, mid+1, ei, tar);
        }
    }

}  


int main() {
    int arr[7] = {4, 5, 6, 7, 0, 1, 2};
    int n = 7;


    cout << "idx: " << search(arr, 0, n-1, 6) << endl; // 4



    return 0;
}


output:
idx: 2

Friday, June 6, 2025

Merge Sort (using divide and conquer approach) in C++ with explaination!

#include<iostream>
#include<vector>

using namespace std;


// conquer step - O(n)
void merge(int arr[], int si, int mid,int ei) {  
    vector<int> temp;
    int i = si;
    int j = mid+1;

    while(i <= mid && j <= ei) {
        if(arr[i] <= arr[j]) { // so jo value choti hai, ushe add krna h
            temp.push_back(arr[i++]);
        } else {
            temp.push_back(arr[j++]);
        }
    }


    // i will keep pushing itself until reaches mid
    while(i <= mid) {
        temp.push_back(arr[i++]);
    }


    // j will keep pushing itself until reaches ei

    while(j <= ei) {
        temp.push_back(arr[j++]);
    }


    // vector -> original array
    for(int idx=si, x=0; idx <= ei; idx++)  { // playing this loop on original arr
        arr[idx] = temp[x++]; // temp ka iterater
    }
}


// merge sort step - O(nlogn)
void mergeSort(int arr[], int si, int ei) {
    if(si >= ei) {
        return;
    }


    int mid = si + (ei-si)/2;

    mergeSort(arr, si, mid); // left half
    mergeSort(arr, mid+1, ei); // right half

    merge(arr, si, mid, ei); // conquer
}

void printArr(int arr[], int n) {
    for(int i=0; i<n; i++) {
    cout << arr[i] << " ";
}

cout << endl;

}



int main() {
    int arr[6] = {6, 3, 7, 5, 2, 4};
    int n = 6;
    int si = 0;
    int ei = n-1;

    mergeSort(arr, si, ei);
    printArr(arr, n);
    return 0;
}

Tower of Hanoi using Recursion in C++

 #include <iostream>

using namespace std;



// A to C using B 


void TOH(int n, char A, char B, char C) 

{

    if(n==0) {

        return;

        

    }

    

    

    TOH(n-1, A, C,B);

    cout << A << " to " << C<< endl;

    

    TOH(n-1, B, A,C);

}

int main()

{

    TOH(3, 'A', 'B', 'C');


    return 0;

}

Wednesday, June 4, 2025

Count all contiguous substrings of string S where the first and last characters are the same. (USING RECURSION in C++)

#include <iostream>

using namespace std;


// Count how many times it starts and ends with same string

int go(string str, int i, int j, int n) {

    if(n == 1) {

        return 1;

    }

    

    if(n<=0) {

        return 0;

    }

    

    int res = go(str, i+1, j, n-1)+go(str, i, j-1, n-1)-go(str, i+1, j-1, n-2);

    

    if(str[i] == str[j]) {

        res++;

    }

    

    return res;

}


int main() {

    string S = "abcab";

    int size = S.length();

    

    cout << go(S, 0, size-1, size);

    

    

    return 0;

}


OUTPUT:


7

Student Info Display (University OOPs Lab Topic)

 #include <iostream>

using namespace std;


// Base class

class Person {

protected: 

    string name;

    int age;


public:

    // Parameterized constructor

    Person(string n, int a) {

        name = n;

        age = a;

        cout << "Person constructor called with name = " << name << " and age = " << age << endl;

    }

};


// Derived class

class Student : public Person {

private: 

    string studentID;

    

public:

    // COnstructor for Student that intializes base class (Person) and studentID

    Student(string n, int a, string id) : Person(n, a), // Call the base class constructor with name and age

    studentID(id) {

        

        // Constructor body (can be empty if no additional initialization is needed)

    } 

    

    

    // Method to display student info

    void displayStudentInfo() {

        cout << "Name: " << name << endl;

        cout << "Age: " << age << endl;

        cout << "Student ID: " << studentID << endl;

    }

};



int main() {

    Student student("Rahul", 20, "50342324");

    student.displayStudentInfo();


    return 0;

}

Find all Occurences using Recursion in C++

 #include <iostream>

using namespace std;


void allOccurences(int arr[], int key, int i, int n) {

    if(i == n) {

        return;

    }

    

    if(arr[i] == key) {

        cout << i << " ";

    }

    

    allOccurences(arr, key, i+1, n);

}


int main() {

    int arr[] = {3, 2, 4, 5, 6, 2, 7, 2, 2};

    int n = sizeof(arr)/sizeof(int);

    int key = 2; 

    allOccurences(arr, key, 0, n);


    return 0;

}

Bank Account Question (University OOPs Lab Topic)

 #include <iostream>

using namespace std;

class BankAccount {
private:
    int accountNumber;
    double balance;
   
public:    
// Constructor to initialize account    
    BankAccount(int accNo, double initialBalance = 0.0) {
        accountNumber = accNo;
        balance = initialBalance;
    }
   
   
    void deposit(double amount) {
        if(amount > 0) {
            balance += amount;
             cout << "Deposited: " << amount << endl;
        } else {
            cout << "Invalid deposit amount!" << endl;
        }
    }
    void withdraw(double amount) {
        if(amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "Withdrawn: " << amount<< endl;
        } else {
            cout << "Invalid or insufficient funds for withdrawal!" << endl;
        }
    }
   
    // method to get balance
    double getBalance() const {
        return balance;
    }
   
    // Optional: Show account number and balance
    void showAccountInfo() const {
        cout << "Account Number: " << accountNumber << endl;
        cout << "Current Balance: " << balance << endl;
    }
   
   
};

int main() {
    // Create a bank with account number 1001 and initial balance of 500
   
    BankAccount account(1001, 500.0);
   
    account.showAccountInfo();
   
    // Perform deposit and withdrawal operations
    account.deposit(250);
    account.withdraw(100);
   
    //Show final balance
    cout << "Final balance: " << account.getBalance() << endl;
   
    return 0;
}

Tuesday, June 3, 2025

Function Pointer (the TOPIC that I missed!) - Part 1

 #include <iostream>

using namespace std;



// Function declaration + definition (function to be pointed to..)

void greet() {

    cout << "Hello!\n";

}


int main() {

    

    // Function pointer

    void (*fp)();


    // Assign the address of greet() fnx to the fnx pointer..

    

    fp = greet;

    

    greet();

    

    return 0;

}




OR



with parameters 


#include <iostream>

using namespace std;


int add(int a, int b) {

    return a+b;

}



int main() {

    // Declare function pointer

    int (*operation)(int, int);

    

    

    // Assign fnx address

    operation = add;

    

    // Call the fnx using pointer

    cout << operation(4, 4);


    return 0;

}



Sunday, June 1, 2025

Watermelon in Codeforces(It accepted at 3rd attempt!!)

 #include <iostream>

using namespace std;




int main() {

    int watermelon;

    cin >> watermelon;


    

    if(watermelon == 2) {

        cout << "NO" << endl;

    }

    else if(watermelon%2==0) { // even no;

        cout << "YES" << endl;

    }else { // odd no.

        cout << "NO" << endl;

    }

    

    return 0;

}

Binary Strings using Recursion in C++

 #include <iostream>

#include <string>
using namespace std;

void binString(int n, int lastPlace, string ans) {
    if(n == 0) {
        cout << ans << endl;
        return;
    }
   
    if(lastPlace != 1) {
        binString(n-1, 0, ans+'0');
        binString(n-1, 1, ans+'1');
    } else {
        binString(n-1, 0, ans + '0');
    }
}

void binString(int n, string ans) {
    if(n == 0) {
        cout << ans << endl;
        return;
    }
   
    if(ans[ans.size()-1] != '1') {
        binString(n-1, ans+'0');
        binString(n-1, ans+'1');
    } else {
        binString(n-1, ans + '0');
    }
}

int main() {
    string ans = " ";
    binString(3, ans);

return 0;
}

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...