The Wayback Machine - https://web.archive.org/web/20241129131741/https://www.geeksforgeeks.org/implementing-hash-table-open-addressing-linear-probing-cpp/
Open In App

Implementing own Hash Table with Open Addressing Linear Probing

Last Updated : 25 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite – Hashing Introduction, Implementing our Own Hash Table with Separate Chaining in Java
In Open Addressing, all elements are stored in the hash table itself. So at any point, size of table must be greater than or equal to total number of keys (Note that we can increase table size by copying old data if needed).

  • Insert(k) – Keep probing until an empty slot is found. Once an empty slot is found, insert k.
  • Search(k) – Keep probing until slot’s key doesn’t become equal to k or an empty slot is reached.
  • Delete(k) – Delete operation is interesting. If we simply delete a key, then search may fail. So slots of deleted keys are marked specially as “deleted”.

Here, to mark a node deleted we have used dummy node with key and value -1. 
Insert can insert an item in a deleted slot, but search doesn’t stop at a deleted slot.
The entire process ensures that for any key, we get an integer position within the size of the Hash Table to insert the corresponding value. 
So the process is simple, user gives a (key, value) pair set as input and based on the value generated by hash function an index is generated to where the value corresponding to the particular key is stored. So whenever we need to fetch a value corresponding to a key that is just O(1).
 

Implementation:

CPP
#include <bits/stdc++.h>
using namespace std;

// template for generic type
template <typename K, typename V>

// Hashnode class
class HashNode {
public:
    V value;
    K key;

    // Constructor of hashnode
    HashNode(K key, V value)
    {
        this->value = value;
        this->key = key;
    }
};

// template for generic type
template <typename K, typename V>

// Our own Hashmap class
class HashMap {
    // hash element array
    HashNode<K, V>** arr;
    int capacity;
    // current size
    int size;
    // dummy node
    HashNode<K, V>* dummy;

public:
    HashMap()
    {
        // Initial capacity of hash array
        capacity = 20;
        size = 0;
        arr = new HashNode<K, V>*[capacity];

        // Initialise all elements of array as NULL
        for (int i = 0; i < capacity; i++)
            arr[i] = NULL;

        // dummy node with value and key -1
        dummy = new HashNode<K, V>(-1, -1);
    }
    // This implements hash function to find index
    // for a key
    int hashCode(K key) { return key % capacity; }

    // Function to add key value pair
    void insertNode(K key, V value)
    {
        HashNode<K, V>* temp
            = new HashNode<K, V>(key, value);

        // Apply hash function to find index for given key
        int hashIndex = hashCode(key);

        // find next free space
        while (arr[hashIndex] != NULL
               && arr[hashIndex]->key != key
               && arr[hashIndex]->key != -1) {
            hashIndex++;
            hashIndex %= capacity;
        }

        // if new node to be inserted
        // increase the current size
        if (arr[hashIndex] == NULL
            || arr[hashIndex]->key == -1)
            size++;
        arr[hashIndex] = temp;
    }

    // Function to delete a key value pair
    V deleteNode(int key)
    {
        // Apply hash function
        // to find index for given key
        int hashIndex = hashCode(key);

        // finding the node with given key
        while (arr[hashIndex] != NULL) {
            // if node found
            if (arr[hashIndex]->key == key) {
                HashNode<K, V>* temp = arr[hashIndex];

                // Insert dummy node here for further use
                arr[hashIndex] = dummy;

                // Reduce size
                size--;
                return temp->value;
            }
            hashIndex++;
            hashIndex %= capacity;
        }

        // If not found return null
        return NULL;
    }

    // Function to search the value for a given key
    V get(int key)
    {
        // Apply hash function to find index for given key
        int hashIndex = hashCode(key);
        int counter = 0;

        // finding the node with given key
        while (arr[hashIndex]
               != NULL) { // int counter =0; // BUG!

            if (counter++
                > capacity) // to avoid infinite loop
                return NULL;

            // if node found return its value
            if (arr[hashIndex]->key == key)
                return arr[hashIndex]->value;
            hashIndex++;
            hashIndex %= capacity;
        }

        // If not found return null
        return NULL;
    }

    // Return current size
    int sizeofMap() { return size; }

    // Return true if size is 0
    bool isEmpty() { return size == 0; }

    // Function to display the stored key value pairs
    void display()
    {
        for (int i = 0; i < capacity; i++) {
            if (arr[i] != NULL && arr[i]->key != -1)
                cout << "key = " << arr[i]->key
                     << "  value = " << arr[i]->value
                     << endl;
        }
    }
};

// Driver method to test map class
int main()
{
    HashMap<int, int>* h = new HashMap<int, int>;
    h->insertNode(1, 1);
    h->insertNode(2, 2);
    h->insertNode(2, 3);
    h->display();
    cout << h->sizeofMap() << endl;
    cout << h->deleteNode(2) << endl;
    cout << h->sizeofMap() << endl;
    cout << h->isEmpty() << endl;
    cout << h->get(2);

    return 0;
}
Java
// Our own HashNode class
class HashNode {
    int key;
    int value;

    public HashNode(int key, int value)
    {
        this.key = key;
        this.value = value;
    }
}

// Our own Hashmap class
class HashMap {
    // hash element array
    int capacity;
    int size;
    HashNode[] arr;
    // dummy node
    HashNode dummy;

    public HashMap()
    {
        this.capacity = 20;
        this.size = 0;
        this.arr = new HashNode[this.capacity];
        // initialize with dummy node
        this.dummy = new HashNode(-1, -1);
    }

    // This implements hash function to find index for a key
    public int hashCode(int key)
    {
        return key % this.capacity;
    }

    // Function to add key value pair
    public void insertNode(int key, int value)
    {
        HashNode temp = new HashNode(key, value);
        // Apply hash function to find index for given key
        int hashIndex = hashCode(key);
        // find next free space
        while (this.arr[hashIndex] != null
               && this.arr[hashIndex].key != key
               && this.arr[hashIndex].key != -1) {
            hashIndex++;
            hashIndex %= this.capacity;
        }
        // if new node to be inserted, increase the current
        // size
        if (this.arr[hashIndex] == null
            || this.arr[hashIndex].key == -1) {
            this.size++;
        }
        this.arr[hashIndex] = temp;
    }

    // Function to delete a key value pair
    public int deleteNode(int key)
    {
        // Apply hash function to find index for given key
        int hashIndex = hashCode(key);
        // finding the node with given key
        while (this.arr[hashIndex] != null) {
            // if node found
            if (this.arr[hashIndex].key == key) {
                HashNode temp = this.arr[hashIndex];
                // Insert dummy node here for further use
                this.arr[hashIndex] = this.dummy;
                // Reduce size
                this.size--;
                return temp.value;
            }
            hashIndex++;
            hashIndex %= this.capacity;
        }
        // If not found return -1
        return -1;
    }

    // Function to search the value for a given key
    public int get(int key)
    {
        // Apply hash function to find index for given key
        int hashIndex = hashCode(key);
        int counter = 0;
        // finding the node with given key
        while (this.arr[hashIndex] != null) {
            // If counter is greater than capacity to avoid
            // infinite loop
            if (counter > this.capacity) {
                return -1;
            }
            // if node found return its value
            if (this.arr[hashIndex].key == key) {
                return this.arr[hashIndex].value;
            }
            hashIndex++;
            hashIndex %= this.capacity;
            counter++;
        }
        // If not found return 0
        return 0;
    }

    // Return current size
    public int sizeofMap() { return this.size; }

    // Return true if size is 0
    public boolean isEmpty() { return this.size == 0; }

    // Function to display the stored key value pairs
    public void display()
    {
        for (int i = 0; i < this.capacity; i++) {
            if (this.arr[i] != null
                && this.arr[i].key != -1) {
                System.out.println(
                    "key = " + this.arr[i].key
                    + " value = " + this.arr[i].value);
            }
        }
    }
}

public class Main {
    public static void main(String[] args)
    {
        HashMap h = new HashMap();
        h.insertNode(1, 1);
        h.insertNode(2, 2);
        h.insertNode(2, 3);
        h.display();
        System.out.println(h.sizeofMap());
        System.out.println(h.deleteNode(2));
        System.out.println(h.sizeofMap());
        System.out.println(h.isEmpty());
        System.out.println(h.get(2));
    }
}
Python3
# Our own Hashnode class
class HashNode:
    def __init__(self, key, value):
        self.key = key
        self.value = value

# Our own Hashmap class


class HashMap:
    # hash element array
    def __init__(self):
        self.capacity = 20
        self.size = 0
        self.arr = [None] * self.capacity
        # dummy node
        self.dummy = HashNode(-1, -1)

    # This implements hash function to find index for a key
    def hashCode(self, key):
        return key % self.capacity

    # Function to add key value pair
    def insertNode(self, key, value):
        temp = HashNode(key, value)
        # Apply hash function to find index for given key
        hashIndex = self.hashCode(key)
        # find next free space
        while self.arr[hashIndex] is not None and self.arr[hashIndex].key != key and self.arr[hashIndex].key != -1:
            hashIndex += 1
            hashIndex %= self.capacity
        # if new node to be inserted, increase the current size
        if self.arr[hashIndex] is None or self.arr[hashIndex].key == -1:
            self.size += 1
        self.arr[hashIndex] = temp

    # Function to delete a key value pair
    def deleteNode(self, key):
        # Apply hash function to find index for given key
        hashIndex = self.hashCode(key)
        # finding the node with given key
        while self.arr[hashIndex] is not None:
            # if node found
            if self.arr[hashIndex].key == key:
                temp = self.arr[hashIndex]
                # Insert dummy node here for further use
                self.arr[hashIndex] = self.dummy
                # Reduce size
                self.size -= 1
                return temp.value
            hashIndex += 1
            hashIndex %= self.capacity
        # If not found return None
        return None

    # Function to search the value for a given key
    def get(self, key):
        # Apply hash function to find index for given key
        hashIndex = self.hashCode(key)
        counter = 0
        # finding the node with given key
        while self.arr[hashIndex] is not None:
            # If counter is greater than capacity to avoid infinite loop
            if counter > self.capacity:
                return None
            # if node found return its value
            if self.arr[hashIndex].key == key:
                return self.arr[hashIndex].value
            hashIndex += 1
            hashIndex %= self.capacity
            counter += 1
        # If not found return None
        return 0

    # Return current size
    def sizeofMap(self):
        return self.size

    # Return true if size is 0
    def isEmpty(self):
        return self.size == 0

    # Function to display the stored key value pairs
    def display(self):
        for i in range(self.capacity):
            if self.arr[i] is not None and self.arr[i].key != -1:
                print("key = ", self.arr[i].key,
                      " value = ", self.arr[i].value)


# Driver method to test map class
if __name__ == "__main__":
    h = HashMap()
    h.insertNode(1, 1)
    h.insertNode(2, 2)
    h.insertNode(2, 3)
    h.display()
    print(h.sizeofMap())
    print(h.deleteNode(2))
    print(h.sizeofMap())
    print(h.isEmpty())
    print(h.get(2))
C#
using System;

class HashNode {
    public int key;
    public int value;
    public HashNode next;

    public HashNode(int key, int value)
    {
        this.key = key;
        this.value = value;
        next = null;
    }
}

class HashMap {
    private HashNode[] table;
    private int capacity;
    private int size;

    public HashMap(int capacity)
    {
        this.capacity = capacity;
        table = new HashNode[capacity];
        size = 0;
    }

    // hash function to find index for a given key
    private int HashCode(int key) { return key % capacity; }

    // function to add key value pair
    public void InsertNode(int key, int value)
    {
        int hashIndex = HashCode(key);
        HashNode newNode = new HashNode(key, value);

        // if the key already exists, update the value
        if (table[hashIndex] != null) {
            HashNode current = table[hashIndex];

            while (current != null) {
                if (current.key == key) {
                    current.value = value;
                    return;
                }
                current = current.next;
            }
        }

        // if the key is new, add a new node to the table
        newNode.next = table[hashIndex];
        table[hashIndex] = newNode;
        size++;
    }

    // function to delete a key value pair
    public int ? DeleteNode(int key)
    {
        int hashIndex = HashCode(key);

        if (table[hashIndex] != null) {
            HashNode current = table[hashIndex];
            HashNode previous = null;

            while (current != null) {
                if (current.key == key) {
                    if (previous == null) {
                        table[hashIndex] = current.next;
                    }
                    else {
                        previous.next = current.next;
                    }
                    size--;
                    return current.value;
                }
                previous = current;
                current = current.next;
            }
        }

        return null;
    }

    // function to get the value for a given key
    public int ? Get(int key)
    {
        int hashIndex = HashCode(key);

        if (table[hashIndex] != null) {
            HashNode current = table[hashIndex];

            while (current != null) {
                if (current.key == key) {
                    return current.value;
                }
                current = current.next;
            }
        }

        return 0;
    }

    // function to get the number of key value pairs in the
    // hashmap
    public int Size() { return size; }

    // function to check if the hashmap is empty
    public bool IsEmpty() { return size == 0; }

    // function to display the key value pairs in the
    // hashmap
    public void Display()
    {
        for (int i = 0; i < capacity; i++) {
            if (table[i] != null) {
                HashNode current = table[i];

                while (current != null) {
                    Console.WriteLine("key = " + current.key
                                      + " value = "
                                      + current.value);
                    current = current.next;
                }
            }
        }
    }
}

class Program {
    static void Main(string[] args)
    {
        HashMap h = new HashMap(20);

        h.InsertNode(1, 1);
        h.InsertNode(2, 2);
        h.InsertNode(2, 3);

        h.Display();

        Console.WriteLine(h.Size());
        Console.WriteLine(h.DeleteNode(2));
        Console.WriteLine(h.Size());
        Console.WriteLine(h.IsEmpty());
        Console.WriteLine(h.Get(2));
    }
}
JavaScript
// template for generic type
class HashNode {
  constructor(key, value) {
    this.key = key;
    this.value = value;
  }
}

// template for generic type
class HashMap {
  constructor() {
    this.capacity = 20;
    this.size = 0;
    this.arr = new Array(this.capacity);

    // Initialise all elements of array as NULL
    for (let i = 0; i < this.capacity; i++) {
      this.arr[i] = null;
    }

    // dummy node with value and key -1
    this.dummy = new HashNode(-1, -1);
  }

  // This implements hash function to find index for a key
  hashCode(key) {
    return key % this.capacity;
  }

  // Function to add key value pair
  insertNode(key, value) {
    const temp = new HashNode(key, value);

    // Apply hash function to find index for given key
    let hashIndex = this.hashCode(key);

    // find next free space
    while (
      this.arr[hashIndex] !== null &&
      this.arr[hashIndex].key !== key &&
      this.arr[hashIndex].key !== -1
    ) {
      hashIndex++;
      hashIndex %= this.capacity;
    }

    // if new node to be inserted
    // increase the current size
    if (
      this.arr[hashIndex] === null ||
      this.arr[hashIndex].key === -1
    ) {
      this.size++;
    }
    this.arr[hashIndex] = temp;
  }

  // Function to delete a key value pair
  deleteNode(key) {
    // Apply hash function to find index for given key
    let hashIndex = this.hashCode(key);

    // finding the node with given key
    while (this.arr[hashIndex] !== null) {
      // if node found
      if (this.arr[hashIndex].key === key) {
        const temp = this.arr[hashIndex];

        // Insert dummy node here for further use
        this.arr[hashIndex] = this.dummy;

        // Reduce size
        this.size--;
        return temp.value;
      }
      hashIndex++;
      hashIndex %= this.capacity;
    }

    // If not found return null
    return null;
  }

  // Function to search the value for a given key
  get(key) {
    // Apply hash function to find index for given key
    let hashIndex = this.hashCode(key);
    let counter = 0;

    // finding the node with given key
    while (this.arr[hashIndex] !== null) {
      if (counter++ > this.capacity) {
        // to avoid infinite loop
        return 0;
      }

      // if node found return its value
      if (this.arr[hashIndex].key === key) {
        return this.arr[hashIndex].value;
      }
      hashIndex++;
      hashIndex %= this.capacity;
    }

    // If not found return null
    return 0;
  }

  // Return current size
  sizeofMap() {
    return this.size;
  }

  // Return true if size is 0
  isEmpty() {
    return this.size === 0;
  }

  // Function to display the stored key value pairs
  display() {
    for (let i = 0; i < this.capacity; i++) {
      if (this.arr[i] !== null && this.arr[i].key !== -1) {
        console.log(`key = ${this.arr[i].key} value = ${this.arr[i].value}`);
      }
    }
  }
}

// Driver method to test map class
const h = new HashMap();
h.insertNode(1,1);
h.insertNode(2,2);
h.insertNode(2,3);
h.display();
console.log(h.sizeofMap());
console.log(h.deleteNode(2));
console.log(h.sizeofMap());
console.log(h.isEmpty());
console.log(h.get(2));

Output
key = 1  value = 1
key = 2  value = 3
2
3
1
0
0

Complexity analysis for Insertion:

  • Time Complexity:
    • Best Case: O(1)
    • Worst Case: O(N). This happens when all elements have collided and we need to insert the last element by checking free space one by one.
    • Average Case: O(1) for good hash function, O(N) for bad hash function
  • Auxiliary Space: O(1)

Complexity analysis for Deletion:

  • Time Complexity:
    • Best Case: O(1)
    • Worst Case: O(N)
    • Average Case: O(1) for good hash function; O(N) for bad hash function
  • Auxiliary Space: O(1) 

Complexity analysis for Searching:

  • Time Complexity:
    • Best Case: O(1)
    • Worst Case: O(N)
    • Average Case: O(1) for good hash function; O(N) for bad hash function
  • Auxiliary Space: O(1) for search operation




Previous Article
Next Article

Similar Reads

Implementing our Own Hash Table with Separate Chaining in Java
All data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add and remove an element in constant time. Anyone mus
10 min read
Linear Probing in Python
Linear probing is a technique used in hash tables to handle collisions. When a collision occurs (i.e., when two keys hash to the same index), linear probing searches for the next available slot in the hash table by incrementing the index until an empty slot is found. What is Linear Probing?In linear probing, the hash table is searched sequentially
2 min read
Quadratic Probing in Hashing
Hashing is an improvement technique over the Direct Access Table. The idea is to use a hash function that converts a given phone number or any other key to a smaller number and uses the small number as the index in a table called a hash table. Hash Function: A function that converts a given big number to a small practical integer value. The mapped
15 min read
Quadratic Probing in Python
Hashing is an improvement technique over the Direct Access Table. The idea is to use a hash function that converts a given phone number or any other key to a smaller number and uses the small number as the index in a table called a hash table. What is Quadratic Probing?Quadratic probing is a technique used in hash tables to resolve collisions that
5 min read
Open Addressing Collision Handling technique in Hashing
Open Addressing is a method for handling collisions. In Open Addressing, all elements are stored in the hash table itself. So at any point, the size of the table must be greater than or equal to the total number of keys (Note that we can increase table size by copying old data if needed). This approach is also known as closed hashing. This entire p
7 min read
What are Hash Functions and How to choose a good Hash Function?
Prerequisite: Hashing | Set 1 (Introduction) What is a Hash Function? A function that converts a given big phone number to a small practical integer value. The mapped integer value is used as an index in the hash table. In simple terms, a hash function maps a big number or string to a small integer that can be used as the index in the hash table. W
5 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Comparison of an Array and Hash table in terms of Storage structure and Access time complexity
Arrays and Hash Tables are two of the most widely used data structures in computer science, both serving as efficient solutions for storing and accessing data in Java. They have different storage structures and time complexities, making them suitable for different use cases. In this article, we will explore the differences between arrays and hash t
3 min read
Various load balancing techniques used in Hash table to ensure efficient access time
Load balancing refers to the process of distributing workloads evenly across multiple servers, nodes, or other resources to ensure optimal resource utilization, maximize output, minimize response time, and avoid overload of any single resource. Load balancing helps to improve the reliability and scalability of applications and systems, as well as r
3 min read
Implementation of Hash Table in Python using Separate Chaining
A hash table is a data structure that allows for quick insertion, deletion, and retrieval of data. It works by using a hash function to map a key to an index in an array. In this article, we will implement a hash table in Python using separate chaining to handle collisions. Separate chaining is a technique used to handle collisions in a hash table.
7 min read
Implementation of Hash Table in C/C++ using Separate Chaining
Introduction: Hashing is a technique that maps a large set of data to a small set of data. It uses a hash function for doing this mapping. It is an irreversible process and we cannot find the original value of the key from its hashed value because we are trying to map a large set of data into a small set of data, which may cause collisions. It is n
10 min read
Hash Table vs Trie
What is Hash Table? An array that stores pointers to records corresponding to a given element. An entry in the hash table is NIL if no existing element has a hash function value equal to the index for the entry. In simple terms, we can say that a hash table is a generalization of the array. Hash table gives the functionality in which a collection o
5 min read
Hash Table vs STL Map
This article focus on : Compare and contrast Hash table and an STL Map. How is the hash table implemented? If the number of inputs is small, which data structure options can be used instead of a hash table? Hash table In a hash table, a value is stored by calling a hash function on a key. Values are not stored in sorted order.Additionally, since ha
4 min read
Why use an Array to implement a "list" instead of a Hash Table?
What is an Array?An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. C/C++ Code #include <iostream> using namespace std; // driver program int main() { // initaizling array int arr[] = {1, 2,
4 min read
Advantages of BST over Hash Table
Hash Table supports following operations in O(1) time. 1) Search 2) Insert 3) Delete The time complexity of above operations in a self-balancing Binary Search Tree (BST) (like Red-Black Tree, AVL Tree, Splay Tree, etc) is O(Logn). So Hash Table seems to beating BST in all common operations. When should we prefer BST over Hash Tables, what are advan
2 min read
Hash Table Data Structure
What is Hash Table?A Hash table is defined as a data structure used to insert, look up, and remove key-value pairs quickly. It operates on the hashing concept, where each key is translated by a hash function into a distinct index in an array. The index functions as a storage location for the matching value. In simple words, it maps the keys with th
11 min read
Difference between Linear and Non-linear Data Structures
Linear Data Structure: Data structure where data elements are arranged sequentially or linearly where each and every element is attached to its previous and next adjacent is called a linear data structure. In linear data structure, single level is involved. Therefore, we can traverse all the elements in single run only. Linear data structures are e
5 min read
Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Implement Your Own sizeof
Here is an implementation. #include<stdio.h> #define my_sizeof(type) (char *)(&type+1)-(char*)(&type) int main() { double x; printf("%ld", my_sizeof(x)); getchar(); return 0; } Type is like a local variable to the macro. &type gives the address of the variable (double x) declared in the program and incrementing it with 1
2 min read
Write you own Power without using multiplication(*) and division(/) operators
Method 1 (Using Nested Loops): We can calculate power by using repeated addition. For example to calculate 5^6. 1) First 5 times add 5, we get 25. (5^2) 2) Then 5 times add 25, we get 125. (5^3) 3) Then 5 times add 125, we get 625 (5^4) 4) Then 5 times add 625, we get 3125 (5^5) 5) Then 5 times add 3125, we get 15625 (5^6) C/C++ Code // C++ code fo
13 min read
Compile our own Android Kernel in 5 Simple Steps
The Android kernel helps the applications to communicate with the hardware components of the device. For example: Most of us are familiar with game mode. What it does is instructs the processor and the graphics processing unit to run at their maximum frequencies. Another example is power saver mode. It instructs the processor and the graphics proce
3 min read
How to implement our own Dynamic Array class in Java?
Given task is to implement a class in Java which behaves just like the Dynamic array using ArrayList. ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. ArrayList elements are placed in contiguous storage so that
4 min read
Generate an Array of length N having K subarrays as permutations of their own length
Given integers N and K, the task is to generate an array of length N which contains exactly K subarrays as a permutation of 1 to X where X is the subarray length. There may exist multiple answers you may print any one of them. If no array is possible to construct then print -1. Note: A Permutation of length N is a list of integers from 1 to N(inclu
7 min read
How to implement our own Vector Class in C++?
The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can b
5 min read
Javascript Program To Write Your Own atoi()
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer. Syntax: int atoi(const char strn) Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted
5 min read
When should we write our own assignment operator in C++?
The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or a
3 min read
Write your own strcmp that ignores cases
Write a modified strcmp function which ignores cases and returns -1 if s1 < s2, 0 if s1 = s2, else returns 1. For example, your strcmp should consider "GeeksforGeeks" and "geeksforgeeks" as same string.Source: Microsoft Interview Set 5Following solution assumes that characters are represented using ASCII representation, i.e., codes for 'a', 'b',
6 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
Write your own memcpy() and memmove()
The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype. void * memcpy(void * destination, const void * source, size_t num);The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of t
4 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an implementation of the copy constructor (and assignm
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg