Open In App

Design a Data Structure that performs add in O(n) and getMinimum & deleteMinimum in O(1)

Last Updated : 11 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Design a data structure which can do following operations

  1. add() in O(n)
  2. getMinimum() in O(1)
  3. deleteMinimum() in O(1)

Source : MakeMyTrip Interview.

  1. Maintain a linkedlist with elements in increasing order.
  2. Move head to next position in case of delete Min operation.
  3. Return First element in case of get Min Operation.

Implementation:

C++
#include <iostream>

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

    Node(int d)
    {
        data = d;
        next = nullptr;
    }
};

// Main class
class MinDS
{
    Node* start;

public:
    MinDS()
    {
        start = nullptr;
    }

    // Function to add an element
    void addElement(int d)
    {
        Node* tmp = new Node(d);

        // If the linked list is empty
        if (start == nullptr)
        {
            start = tmp;
            return;
        }

        // If the new element is smaller than the head
        if (d < start->data)
        {
            tmp->next = start;
            start = tmp;
            return;
        }

        // If the new element needs to be inserted in the middle
        Node* prev = start;
        Node* ptr = start->next;
        while (ptr != nullptr)
        {
            if (d < ptr->data)
            {
                tmp->next = ptr;
                prev->next = tmp;
                return;
            }
            else
            {
                prev = ptr;
                ptr = ptr->next;
            }
        }
        prev->next = tmp;
    }

    // Function to get the minimum element
    int getMin()
    {
        return start->data;
    }

    // Function to delete the minimum element
    int delMin()
    {
        int min = start->data;
        start = start->next;
        return min;
    }

    // Function to print elements
    void print()
    {
        Node* ptr = start;
        std::cout << "Elements: ";
        while (ptr != nullptr)
        {
            std::cout << ptr->data << ", ";
            ptr = ptr->next;
        }
        std::cout << "\n";
    }
};

int main()
{
    MinDS x;
    x.addElement(10);
    x.addElement(20);
    x.addElement(5);
    x.addElement(15);
    x.print();

    std::cout << "Get Min: " << x.getMin() << std::endl;
    std::cout << "Del Min: " << x.delMin() << std::endl;
    x.print();

    std::cout << "Min: " << x.getMin() << std::endl;

    return 0;
}
Java
// Java code for linked list to
// perform required operations
import java.util.*;

// Node class
class Node
{
    int data;
    Node next;

    Node(int d)
    {
        data = d;
        next = null;
    }
}

// main class
class MinDS
{
    Node start;

    public MinDS()
    {
        start = null;
    }

    // Function to add element
    void addElement(int d)
    {
        Node tmp = new Node(d);

        // If linked list is empty
        if (start == null)
        {
            start = tmp;
            return;
        }

        // If head itself is greater
        if (d < start.data)
        {
            tmp.next = start;
            start = tmp;
            return;
        }

        // If need to insert somewhere in middle
        Node prev = start;
        Node ptr = start.next;
        while (ptr != null)
        {
            if (d < ptr.data)
            {
                tmp.next = ptr;
                prev.next = tmp;
                return;
            }
            else
            {
                prev = ptr;
                ptr = ptr.next;
            }
        }
        prev.next = tmp;
    }

    // Function to get minimum
    int getMin()
    {
        return start.data;
    }

    // Function to delete minimum
    int delMin()
    {
        int min = start.data;
        start = start.next;
        return min;
    }

    // Function to print elements
    void print()
    {
        Node ptr = start;
        System.out.print("Elements: ");
        while (ptr != null)
        {
            System.out.print(ptr.data + ", ");
            ptr = ptr.next;
        }
        System.out.println("\n");
    }

    // Driver code
    public static void main(String[] args)
    {
        MinDS x = new MinDS();
        x.addElement(10);
        x.addElement(20);
        x.addElement(5);
        x.addElement(15);
        x.print();

        System.out.println("Get Min: " + x.getMin());
        System.out.println("Del Min: " + x.delMin());
        x.print();

        System.out.println("Min: " + x.getMin());
    }
}
Python3
# Python code for linked list to perform required operations

# Node class
class Node:
    def __init__(self, d):
        self.data = d
        self.next = None

# Main class
class MinDS:
    def __init__(self):
        self.start = None

    # Function to add element
    def addElement(self, d):
        tmp = Node(d)

        # If linked list is empty
        if self.start is None:
            self.start = tmp
            return

        # If head itself is greater
        if d < self.start.data:
            tmp.next = self.start
            self.start = tmp
            return

        # If need to insert somewhere in the middle
        prev = self.start
        ptr = self.start.next
        while ptr is not None:
            if d < ptr.data:
                tmp.next = ptr
                prev.next = tmp
                return
            else:
                prev = ptr
                ptr = ptr.next
        prev.next = tmp

    # Function to get minimum
    def getMin(self):
        return self.start.data

    # Function to delete minimum
    def delMin(self):
        min_val = self.start.data
        self.start = self.start.next
        return min_val

    # Function to print elements
    def printList(self):
        ptr = self.start
        print("Elements: ", end="")
        while ptr is not None:
            print(ptr.data, end=", ")
            ptr = ptr.next
        print("\n")

# Driver code
if __name__ == "__main__":
    x = MinDS()
    x.addElement(10)
    x.addElement(20)
    x.addElement(5)
    x.addElement(15)
    x.printList()

    print("Get Min:", x.getMin())
    print("Del Min:", x.delMin())
    x.printList()

    print("Min:", x.getMin())
C#
using System;

// Node class
public class Node
{
    public int data;
    public Node next;

    // Constructor
    public Node(int d)
    {
        data = d;
        next = null;
    }
}

// Main class
public class MinDS
{
    private Node start;

    // Constructor
    public MinDS()
    {
        start = null;
    }

    // Function to add an element
    public void AddElement(int d)
    {
        Node tmp = new Node(d);

        // If the linked list is empty
        if (start == null)
        {
            start = tmp;
            return;
        }

        // If the new element is smaller than the head
        if (d < start.data)
        {
            tmp.next = start;
            start = tmp;
            return;
        }

        // If the new element needs to be inserted in the middle
        Node prev = start;
        Node ptr = start.next;
        while (ptr != null)
        {
            if (d < ptr.data)
            {
                tmp.next = ptr;
                prev.next = tmp;
                return;
            }
            else
            {
                prev = ptr;
                ptr = ptr.next;
            }
        }
        prev.next = tmp;
    }

    // Function to get the minimum element
    public int GetMin()
    {
        if (start == null)
        {
            throw new InvalidOperationException("List is empty");
        }
        return start.data;
    }

    // Function to delete the minimum element
    public int DelMin()
    {
        if (start == null)
        {
            throw new InvalidOperationException("List is empty");
        }
        int min = start.data;
        start = start.next;
        return min;
    }

    // Function to print elements
    public void Print()
    {
        Node ptr = start;
        Console.Write("Elements: ");
        while (ptr != null)
        {
            Console.Write(ptr.data + ", ");
            ptr = ptr.next;
        }
        Console.WriteLine();
    }
}

class Program
{
    static void Main(string[] args)
    {
        MinDS x = new MinDS();
        x.AddElement(10);
        x.AddElement(20);
        x.AddElement(5);
        x.AddElement(15);
        x.Print();

        Console.WriteLine("Get Min: " + x.GetMin());
        Console.WriteLine("Del Min: " + x.DelMin());
        x.Print();

        Console.WriteLine("Min: " + x.GetMin());
    }
}
JavaScript
// Node class
class Node {
    constructor(d) {
        this.data = d;
        this.next = null;
    }
}

// Main class
class MinDS {
    constructor() {
        this.start = null;
    }

    // Function to add element
    addElement(d) {
        let tmp = new Node(d);

        // If linked list is empty
        if (this.start === null) {
            this.start = tmp;
            return;
        }

        // If head itself is greater
        if (d < this.start.data) {
            tmp.next = this.start;
            this.start = tmp;
            return;
        }

        // If need to insert somewhere in middle
        let prev = this.start;
        let ptr = this.start.next;
        while (ptr !== null) {
            if (d < ptr.data) {
                tmp.next = ptr;
                prev.next = tmp;
                return;
            } else {
                prev = ptr;
                ptr = ptr.next;
            }
        }
        prev.next = tmp;
    }

    // Function to get minimum
    getMin() {
        return this.start.data;
    }

    // Function to delete minimum
    delMin() {
        let min = this.start.data;
        this.start = this.start.next;
        return min;
    }

    // Function to print elements
    print() {
        let ptr = this.start;
        let result = "Elements: ";
        while (ptr !== null) {
            result += ptr.data + ", ";
            ptr = ptr.next;
        }
        console.log(result + "\n");
    }

    // Driver code
    static main() {
        let x = new MinDS();
        x.addElement(10);
        x.addElement(20);
        x.addElement(5);
        x.addElement(15);
        x.print();

        console.log("Get Min: " + x.getMin());
        console.log("Del Min: " + x.delMin());
        x.print();

        console.log("Min: " + x.getMin());
    }
}

// Call the main function
MinDS.main();

Output
Elements: 5, 10, 15, 20, 

Get Min: 5
Del Min: 5
Elements: 10, 15, 20, 

Min: 10



Similar Reads

Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Design and Implement Special Stack Data Structure | Added Space Optimized Version
Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure
24 min read
Design a data structure that supports insert, delete, search and getRandom in constant time
Design a data structure that supports the following operations in O(1) time. insert(x): Inserts an item x to the data structure if not already present.remove(x): Removes item x from the data structure if present. search(x): Searches an item x in the data structure.getRandom(): Returns a random element from the current set of elements We can use has
5 min read
HP R&amp;D Interview Experience | Set 4 (R&amp;D Lab Bangalore)
First round: 20 Aptitude Questions 22 Technical Questions and 8 OOPS Questions(CPP or Java). NO CODING QUESTIONS. Level of both Aptitude and Technical was tough. Second Round:TECHNICAL( Lasted about 45 mins-1 hour) Storage classes; SET bits in a number; puzzles on tanks;pointers; OSI MODEL; Linked list coding; fork(); vfork() ; semaphore; mutex; Ta
1 min read
Design a Queue data structure to get minimum or maximum in O(1) time
Problem: Design a Data Structure a SpecialQueue which supports following operations enqueue, deque, getMin() or getMax() where getMin() operation takes O(1) time.Example: Let the data to be inserted in queue be -4, 2, 1, 6Operation Queue Outputpush(4) 4 -push(2) 4, 2 -push(1) 4, 2, 1 -getMin() 4, 2, 1 1push(6) 4, 2, 1, 6 -pop() 2, 1, 6 4pop() 1, 6
7 min read
Design a data structure for LRU Cache
Design a data structure for LRU Cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the l
22 min read
Design a data structure that supports insert, delete, getRandom in O(1) with duplicates
Design a Data Structure that can support the following operations in O(1) Time Complexity. insert(x): Inserts x in the data structure. Returns True if x was not present and False if it was already present.remove(x): Removes x from the data structure, if present.getRandom(): Returns any value present in the stream randomly. The probability of each e
9 min read
Design an efficient data structure for given operations
To design an efficient data structure for a specific set of operations, it's important to consider the time and space complexity of different data structures and choose the one that is best suited for the specific requirements. For example, if you need to perform operations such as inserting elements, finding the minimum element, and deleting the m
38 min read
Data Structure Design for Two Sum III
You have to design a data structure that accepts a stream of integers and then checks if it has a pair of integers that added/sum up to a particular value. Implement the TwoSum class: TwoSum(): Initializes the TwoSum object, with an empty array initially.void add(int number): Adds number to the data structure.boolean find(int value): Returns true i
6 min read
Data Structure Alignment : How data is arranged and accessed in Computer Memory?
Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at an address equal to some multiple of the word size.
4 min read