Tag: C++ pointers

  • Master How to Count Duplicates in a Linked List (2026)

    Learn how to count duplicates in a linked list in C++ with this beginner-friendly guide. Step-by-step explanation, easy-to-understand code, and tips for detecting duplicate nodes efficiently.

    Linked lists are one of the fundamental data structures in programming. While they are simple to understand, performing operations like counting duplicates can be tricky for beginners. In this guide, we will explain how to count duplicates in a linked list in an easy-to-understand, step-by-step way.

    What is a Linked List?

    A linked list is a collection of nodes where each node contains two things:

    1. Data – The value stored in the node.
    2. Pointer (Next) – A reference to the next node in the list.

    For example, a linked list can look like this:

    1 → 2 → 2 → 3 → 3 → 3 → 4
    

    What Are Duplicates in a Linked List?

    Duplicates are values that appear more than once in the linked list.

    In the example above:

    • 2 appears twice → 1 duplicate
    • 3 appears three times → 2 duplicates

    Total duplicates = 3

    Step-By-Step Approach to Count Duplicates

    Here’s a simple way to count duplicates, perfect for beginners:

    1. Start with the first node (curr).
    2. Compare it with all nodes that come after it (temp).
    3. If a node has the same value as curr, it’s a duplicate.
    4. Move to the next node and repeat until the end.

    Understanding the Key Line: Node* temp = curr->next;

    One line often confuses beginners:

    Node* temp = curr->next;

    Here’s what it means:

    • Node* temp → temp is a pointer that can point to a node.
    • curr->next → the next node after the current node.
    • Together → temp starts checking from the node after curr, not from the beginning. This avoids counting the same value multiple times.

    Count Duplicates in a Linked List : C++ Code

    #include <iostream>
    using namespace std;
    
    class Node {
    public:
        int data;
        Node* next;
    
        Node(int data) {
            this->data = data;
            this->next = NULL;
        }
    };
    
    // Function to count duplicates
    int countDuplicates(Node* head) {
        int count = 0;
        Node* curr = head;
    
        while (curr != NULL) {
            Node* temp = curr->next; // Start checking from next node
    
            while (temp != NULL) {
                if (curr->data == temp->data) {
                    count++;
                    break; // Count only once per value
                }
                temp = temp->next;
            }
            curr = curr->next;
        }
    
        return count;
    }
    
    // Main function
    int main() {
        Node* head = new Node(1);
        head->next = new Node(2);
        head->next->next = new Node(2);
        head->next->next->next = new Node(3);
        head->next->next->next->next = new Node(3);
        head->next->next->next->next->next = new Node(3);
        head->next->next->next->next->next->next = new Node(4);
    
        cout << "Total duplicate nodes: " << countDuplicates(head) << endl;
        return 0;
    }
    

    How This Works

    1. curr pointer moves node by node.
    2. temp pointer checks all nodes after curr.
    3. If curr->data == temp->data, we found a duplicate.
    4. Count is updated once per duplicate value.

    Time and Space Complexity

    • Time Complexity: O(n²) – two nested loops
    • Space Complexity: O(1) – no extra memory used

    Note: For beginners, this approach is easy to understand. Advanced methods (like using a hash map) can reduce time complexity.

    Time Complexity

    Answer:

    Time Complexity = O(n²)

    Why O(n²)? (How we calculate it)

    Look at this part of the code:

    while (curr != NULL) {          // Outer loop
        Node* temp = curr->next;
    
        while (temp != NULL) {      // Inner loop
            if (curr->data == temp->data) {
                count++;
                break;
            }
            temp = temp->next;
        }
        curr = curr->next;
    }
    

    Step-by-step thinking

    • Let total number of nodes = n

    Outer loop (curr)

    • Runs for every node
    • So it runs n times

    Inner loop (temp)

    • For each curr, it checks the remaining nodes
    • In worst case:
      • First time → checks ~ (n-1) nodes
      • Second time → checks ~ (n-2) nodes
      • …
      • Last time → checks 1 node

    Total comparisons (worst case)

    (n-1) + (n-2) + (n-3) + ... + 1
    

    This adds up to:

    n² (approximately)
    

    That’s why Time Complexity = O(n²)

    Simple line to remember (for exams/interviews)

    Since there are two nested loops, the time complexity is O(n²).

    Space Complexity

    Answer:

    Space Complexity = O(1)

    Why O(1)? (How we calculate it)

    Let’s see what extra memory we use:

    int count;
    Node* curr;
    Node* temp;
    
    • These are just variables and pointers
    • They do not grow with input size
    • No arrays, maps, or extra lists are used

    What we are NOT using

    • No extra linked list
    • No hash map
    • No array

    So memory usage stays constant, no matter how big the linked list is.

    Therefore, Space Complexity = O(1)

    Final Summary (Perfect for Notes)

    TypeComplexity
    Time ComplexityO(n²)
    Space ComplexityO(1)

    Tips for Beginners

    • Use two loops to make your logic clear.
    • Always check from the next node, not from the head again.
    • Use visual examples to understand how curr and temp work.

    Frequently Asked Questions (FAQ)

    1. What is a duplicate in a linked list?

    A duplicate is a node whose value appears more than once in a linked list. For example, in the list 1 → 2 → 2 → 3, the value 2 is a duplicate because it appears twice.

    2. Why do we use Node* temp = curr->next?

    This line ensures that we start checking for duplicates from the node after the current one (curr). It avoids re-checking nodes and makes counting accurate.

    3. Can we count duplicates in a sorted linked list faster?

    Yes! In a sorted linked list, duplicates are always next to each other. So, we can use a single loop to compare each node with the next, which reduces time complexity from O(n²) to O(n).

    4. What is the time complexity of this method?

    The beginner-friendly method using two nested loops has O(n²) time complexity, where n is the number of nodes in the list.

    5. Can we count duplicates without using extra space?

    Yes, the method shown in this guide uses O(1) extra space, meaning no additional memory is required apart from the linked list itself.

    6. How is this different from using a hash map?

    Using a hash map can reduce the time complexity to O(n), but it uses extra memory to store counts. The method in this guide is memory-efficient and easier for beginners to understand.

    7. Can this method handle strings or other data types?

    Yes, as long as the linked list stores comparable data (like integers, characters, or strings), you can modify the comparison curr->data == temp->data accordingly.

    Read More : Master Most Asked Stack Coding Questions in Interviews

  • Don’t Miss These Pointer Questions Master Before Any Interview! (2026)

    Don’t miss these must-know pointer questions for interviews. A simple, friendly guide covering basic to advanced pointers to help you prepare with confidence

    Get interview-ready with this friendly and beginner-focused guide on the most important pointer questions. From simple pointer basics to advanced pointer tricks, everything is explained in an easy and clear way. Perfect for students, freshers, and professionals preparing for C, C++, or embedded interviews boost your confidence, strengthen your core concepts, and stay ahead in any technical round!

    BEGINNER-LEVEL POINTER QUESTIONS

    Basics

    1. What is a pointer in C/C++?
    2. Why do we use pointers?
    3. How do you declare a pointer?
    4. What is the size of a pointer?
    5. What does a NULL pointer mean?
    6. What is a wild pointer?
    7. What is a dangling pointer?
    8. What is pointer initialization?
    9. What is the difference between a pointer and a normal variable?
    10. What is the address-of operator (&)?
    11. What is the dereference operator (*)?
    12. How do you assign an address to a pointer?
    13. Can a pointer store NULL?
    14. What happens if you dereference an uninitialized pointer?
    15. What is a void pointer?
    16. What is the use of void *?
    17. What is the difference between int *p and int* p?
    18. What is const int *p?
    19. What is int *const p?
    20. What is const int *const p?

    INTERMEDIATE-LEVEL POINTER QUESTIONS

    Pointer Arithmetic

    1. What is pointer arithmetic?
    2. Why does pointer arithmetic depend on data type size?
    3. Can we increment/decrement a void pointer?
    4. What happens when you compare two pointers?
    5. What is the difference between p++ and ++*p?
    6. How do you find the difference between two pointers?
    7. What is pointer scaling?

    Function Pointers

    1. What is a function pointer?
    2. How do you declare a function pointer?
    3. Why do we use function pointers?
    4. What is a callback function?
    5. What is typedef for function pointers?
    6. How do you pass a function pointer as a parameter?
    7. How do you return a function pointer from a function?
    8. What is a pointer to member function in C++?

    Pointers & Arrays

    1. What is the relationship between pointers and arrays?
    2. Why does array name act like a pointer?
    3. Why can’t we assign to an array name?
    4. What is the difference between arr and &arr?
    5. What is the difference between arr and arr[0]?
    6. How do you use pointer arithmetic to traverse an array?
    7. What is a pointer to an array (int (*p)[5])?
    8. What is an array of pointers (int* p[5])?
    9. What is the difference between pointer to array and array of pointers?
    10. How do you pass a 2D array to a function using pointers?

    Dynamic Memory

    1. What is dynamic memory allocation?
    2. What is malloc, calloc, realloc, free?
    3. What is memory leak?
    4. How do you avoid memory leaks?
    5. What is a double-free error?
    6. Why must you free allocated memory?
    7. What does malloc return?
    8. Why should you check if malloc returned NULL?
    9. What is segmentation fault in context of pointers?

    ADVANCED-LEVEL POINTER QUESTIONS

    Pointer to Pointer & Multi-Level Pointers

    1. What is a pointer to pointer (int **p)?
    2. Why do we use multiple levels of pointers?
    3. What is triple pointer (int ***p) and where used?
    4. How is pointer-to-pointer used in dynamic 2D arrays?

    Constant Pointers & Qualifiers

    1. What is immutable pointer?
    2. What is mutable pointer?
    3. What is the importance of const with pointers in APIs?

    Memory Alignment & Pointers

    1. What is memory alignment?
    2. What happens when a pointer is misaligned?
    3. What is strict aliasing rule?
    4. Why is pointer aliasing dangerous?

    Function Pointer Tables

    1. What is a function pointer jump table?
    2. How are function pointer tables used in drivers?
    3. Why are function pointers used in State Machines?
    4. How do virtual function tables (vtable) use pointers?

    Pointer Casting

    1. What is pointer typecasting?
    2. Is casting between unrelated pointers safe?
    3. What is reinterpret_cast in C++?
    4. Why is reinterpret_cast dangerous?
    5. What is static_cast?
    6. What is dynamic_cast and when to use?

    Pointers in Embedded / System Programming

    1. What is memory-mapped I/O?
    2. How are pointers used for register access?
    3. Why do embedded systems use volatile with pointers?
    4. What does volatile uint32_t* reg = (uint32_t*)0x40002000; mean?
    5. Why is volatile pointer different from pointer-to-volatile?
    6. Why do we use uintptr_t for pointer-to-integer conversions?
    7. What happens if you access invalid memory in bare-metal?

    Pointers & Data Structures

    1. How are pointers used in linked lists?
    2. How is a node created using pointers?
    3. Why do trees heavily use pointers?
    4. How do double pointers help in inserting nodes?
    5. How do pointers enable dynamic queues?
    6. Why are pointers critical in graph adjacency list?

    Pointer Internals

    1. What is pointer indirection level?
    2. Why does pointer dereferencing take time?
    3. What are near, far, huge pointers (old compilers)?
    4. What is segmentation and offset in pointers?
    5. How do pointers work in 64-bit architecture?
    6. How do pointers behave in big-endian vs little-endian?
    7. Why can void* be assigned to any pointer?
    8. Why can’t you do arithmetic on void* in standard C?

    Special Pointer Concepts

    1. What is a smart pointer?
    2. What is unique_ptr, shared_ptr, weak_ptr?
    3. How do smart pointers prevent memory leaks?
    4. What is custom deleter in smart pointers?

    POINTER CODING EXERCISES

    BEGINNER POINTER CODING EXERCISES

    1. Print address and value using a pointer

    Write a program to:

    • Declare an int variable
    • Store its address in a pointer
    • Print the pointer value and pointed value

    2. Swap two numbers using pointers

    Use pointers to swap two integers without using a third variable.

    3. Add two numbers using pointer variables

    Pass pointer addresses to a function and return the sum.

    4. Find length of a string using pointers

    Implement strlen using only pointer arithmetic.

    5. Copy string using pointers

    Write custom strcpy using pointer-to-pointer increment.

    6. Reverse a string using pointers

    Use two pointers (start, end) to reverse a char array.

    7. Print array elements using pointer arithmetic

    Do not use indexing. Only *(p+i) or *p++.

    8. Find maximum element in array using pointers

    Pass array using pointer and find max using pointer arithmetic.

    9. Count vowels in string using pointer traversal

    Increment pointer to iterate over the string.

    10. Check if the string is palindrome using pointers

    Use two pointers: left and right.

    INTERMEDIATE POINTER CODING EXERCISES

    11. Dynamic array using malloc

    • Ask user for size
    • Allocate memory
    • Fill and print elements

    12. Implement your own strcat using pointers

    Append second string to first using pointer increments.

    13. Implement bubble sort using pointers

    Sort using pointer arithmetic instead of indexing.

    14. Create a function to return pointer to max element

    Return pointer to largest element in an array.

    15. Allocate memory for 2D array using double pointer

    int **arr = malloc(rows * sizeof(int*)) … etc.

    16. Write function to free dynamically allocated 2D array

    Free inner + outer pointers properly.

    17. Create a function pointer for arithmetic operations

    Menu:

    • add
    • sub
    • mul
    • div

    Select using function pointer array.

    18. Use function pointers to implement a state machine

    3 states: INIT → PROCESS → EXIT
    Transitions via function pointer table.

    19. Convert lowercase to uppercase using pointer traversal

    Manipulate ASCII values via pointer.

    20. Implement memory copy function (memcpy)

    Use a pointer-to-pointer loop.

    21. Implement strcmp using pointers

    Return:

    • 0 if equal
    • -1 if first < second
    • 1 if first > second

    22. Pointer to array vs array of pointers

    Write code demonstrating both with outputs.

    23. Passing pointer-to-pointer to modify original pointer

    Function should allocate memory and assign it back to caller.

    24. Detect memory leak using pointers

    Simulate:

    • allocate
    • forget to free
    • show correction

    ADVANCED POINTER CODING EXERCISES

    25. Implement a dynamic linked list (insert/delete/traverse)

    Use pointers heavily:

    • malloc
    • pointer-to-pointer for head

    26. Implement a binary tree using struct pointers

    Include:

    • insert
    • search
    • inorder traversal

    27. Create your own malloc() using static memory array

    Simulate:

    • Memory pool
    • Allocation via pointers

    28. Implement smart pointers in C++ (unique_ptr-like)

    Show:

    • RAII
    • destructor deleting memory

    29. Pointer alignment demonstration

    Write code that prints pointer addresses and checks misalignment.

    30. Implement callback mechanism using function pointers

    User function gets executed through a callback argument.

    31. Implement circular buffer using pointers

    Use:

    • read pointer
    • write pointer
    • modulo arithmetic

    32. Implement your own realloc

    Shrink/expand memory and copy old elements manually.

    33. Implement memory-mapped register access (embedded C)

    Simulate:

    #define REG (*(volatile uint32_t*)0x40020000)
    REG = 0xFF;
    

    34. Demonstrate pointer aliasing problem

    Write code where:

    • two pointers refer to same memory
    • updates cause unexpected behavior

    35. Implement a hash table using pointers

    Use:

    • dynamic arrays
    • linked list chaining
    • pointer-to-pointer for insert

    36. Implement function pointer table for drivers

    Simulate operations struct:

    struct ops { void (*init)(); void (*read)(); void (*write)(); };
    

    37. Demonstrate dangling pointer

    Step:

    • allocate
    • free
    • access again

    Then fix it.

    38. Implement double-pointer dynamic 2D matrix

    Manually allocate:

    • row pointers
    • each row

    Print, free.

    39. Implement triple pointer for 3D array

    Show how int ***p manages a 3D matrix.

    40. Implement pointer-based stack

    Use dynamic memory + pointers for:

    • push
    • pop

    50 Pointer Snippet Questions

    Beginner Pointer Snippets

    1.

    int x = 10;
    int *p = &x;
    printf("%d", *p);
    

    2.

    int x = 5;
    int *p = &x;
    *p = 20;
    printf("%d", x);
    

    3.

    int x = 10;
    int *p = NULL;
    printf("%p", p);
    

    4.

    int x = 10;
    int *p = &x;
    p++;
    printf("%d", *p);
    

    5.

    int arr[] = {10,20,30};
    int *p = arr;
    printf("%d", *(p+1));
    

    6.

    char s[] = "Hello";
    char *p = s;
    printf("%c", *p++);
    

    7.

    int a = 10;
    int b = 20;
    int *p = &a;
    p = &b;
    printf("%d", *p);
    

    8.

    int *p;
    int x = 10;
    *p = x;
    printf("%d", *p);
    

    9.

    int x = 10;
    int *p = &x;
    printf("%p %p", &x, p);
    

    10.

    int x = 10;
    int *p = &x;
    printf("%d", *p+2);
    

    Intermediate Pointer Snippets

    11.

    int x = 5;
    int *p = &x;
    int **pp = &p;
    printf("%d", **pp);
    

    12.

    int arr[] = {1,2,3,4};
    int *p = arr+2;
    printf("%d", p[-1]);
    

    13.

    char *p = "ABC";
    printf("%c", *(p+2));
    

    14.

    int a = 5;
    void *vp = &a;
    printf("%d", *(int*)vp);
    

    15.

    int arr[3] = {10,20,30};
    int (*p)[3] = &arr;
    printf("%d", (*p)[1]);
    

    16.

    int *p = NULL;
    printf("%d", *p);
    

    17.

    int a = 10, b = 20;
    int *p1 = &a, *p2 = &b;
    printf("%d", *p1 + *p2);
    

    18.

    int x = 10;
    int *p = &x;
    printf("%lu", sizeof(p));
    

    19.

    int x = 10;
    int *p = &x;
    int **pp = &p;
    pp++;
    printf("%p", *pp);
    

    20.

    int arr[] = {5, 10, 15};
    int *p = arr;
    printf("%d", ++*p);
    

    Advanced Pointer Snippets

    21.

    char str[] = "ABCDE";
    char *p = str;
    printf("%c", ++*p);
    

    22.

    int a = 10;
    int *p = &a;
    *p = ++a;
    printf("%d", a);
    

    23.

    int a = 10;
    int *p = &a;
    int *q = p;
    *q = 100;
    printf("%d", a);
    

    24.

    int arr[5] = {1,2,3,4,5};
    int *p = arr;
    printf("%d", *(p++) + *(++p));
    

    25.

    int x = 10;
    int *p = &x;
    printf("%d", *p++);
    

    26.

    char *p = "hello";
    p[0] = 'H';
    printf("%s", p);
    

    27.

    int a = 10;
    int *p = &a;
    printf("%d %d", a, *p);
    a = 50;
    printf("%d %d", a, *p);
    

    28.

    int arr[] = {10,20,30,40};
    int *p = arr + 3;
    printf("%d", p[-2]);
    

    29.

    void fun(int *p) { *p = 100; }
    int x = 10;
    fun(&x);
    printf("%d", x);
    

    30.

    int *p = malloc(sizeof(int));
    *p = 20;
    printf("%d", *p);
    free(p);
    printf("%d", *p);
    

    Deep Advanced & Tricky Snippets

    31.

    int a = 10;
    int *p = &a;
    *p = *p + (*p++);  
    printf("%d", a);
    

    32.

    int arr[] = {10,20,30,40};
    int *p = arr;
    printf("%d", *++p + ++*p);
    

    33.

    int x = 0;
    int *p = &x;
    if (p)
        printf("Pointer is not NULL");
    

    34.

    int x = 10;
    int y = 20;
    int *p = &x;
    *p = y;
    printf("%d %d", x, y);
    

    35.

    int x = 5;
    int *p = &x;
    printf("%d", (++*p)++);
    

    36.

    int arr[] = {4,3,2,1};
    int *p = arr;
    printf("%d", *p + *(p+1) + *(p+2));
    

    37.

    int x = 5;
    int *p = &x;
    int **pp = &p;
    **pp = 50;
    printf("%d", x);
    

    38.

    char *s = "HELLO";
    printf("%c", *s + 32);
    

    39.

    int a = 10;
    int *p = &a;
    printf("%d", *p + *(p));
    

    40.

    int x = 10;
    int *p = &x;
    printf("%p %p", p, &p);
    

    Pointer + Function Snippets

    41.

    void fun(int *p) {
        p = NULL;
    }
    int x = 10;
    int *p = &x;
    fun(p);
    printf("%p", p);
    

    42.

    void fun(int **p) {
        *p = NULL;
    }
    int x = 10;
    int *p = &x;
    fun(&p);
    printf("%p", p);
    

    43.

    void fun(int *p) { *p = 200; }
    int a = 10;
    fun(&a);
    printf("%d", a);
    

    44.

    void fun(int *p) { p++; }
    int arr[] = {10,20,30};
    int *p = arr;
    fun(p);
    printf("%d", *p);
    

    45.

    void fun(int p) { p = 100; }
    int x = 10;
    fun(x);
    printf("%d", x);
    

    46.

    int fun() { return 5; }
    int (*fp)() = fun;
    printf("%d", fp());
    

    47.

    int add(int a, int b) { return a+b; }
    int (*fp)(int,int) = add;
    printf("%d", fp(5,6));
    

    48.

    int arr[] = {1,2,3};
    int *p = arr;
    printf("%d", (*p)++);
    

    49.

    int x = 10;
    int *p = &x;
    printf("%d", ++(*p));
    

    50.

    int arr[3] = {1,2,3};
    int *p = arr;
    printf("%d", *p + *(p+2));
    

    When it comes to mastering ESP microcontrollers, developers often struggle to find a single place where everything from basics to advanced real-world projects—is explained clearly.
    That’s why resources like Embedded Prep Master have become extremely valuable for students, embedded engineers, and hobbyists.

    One of the best guides available today is:

    Complete ESP Tutorials (Beginner to Advanced) : ESP32 Tutorials

    This guide is a complete gateway for anyone who wants to learn ESP32, ESP8266, IoT development, sensor interfacing, Wi-Fi programming, and real embedded-system projects.