Open In App

Create a customized data structure which evaluates functions in O(1)

Last Updated : 08 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Create a customized data structure such that it has functions :- 

  • GetLastElement(); 
  • RemoveLastElement(); 
  • AddElement() 
  • GetMin()

All the functions should be of O(1)

Question Source : amazon interview questions

Approach : 

  1. create a custom stack of type structure with two elements, (element, min_till_now) 
  2. implement the functions on this custom data type 

Implementation:

C++




// program to demonstrate customized data structure
// which supports functions in O(1)
#include <iostream>
#include <vector>
using namespace std;
const int MAXX = 1000;
 
// class stack
class stack {
    int minn;
    int size;
 
public:
    stack()
    {
        minn = 99999;
        size = -1;
    }
    vector<pair<int, int> > arr;
    int GetLastElement();
    int RemoveLastElement();
    int AddElement(int element);
    int GetMin();
};
 
// utility function for adding a new element
int stack::AddElement(int element)
{
    if (size > MAXX) {
        cout << "stack overflow, max size reached!\n";
        return 0;
    }
    if (element < minn)
        minn = element;
    arr.push_back(make_pair(element, minn));
    size++;
    return 1;
}
 
// utility function for returning last element of stack
int stack::GetLastElement()
{
    if (size == -1) {
        cout << "No elements in stack\n";
        return 0;
    }
    return arr[size].first;
}
 
// utility function for removing last element successfully;
int stack::RemoveLastElement()
{
    if (size == -1) {
        cout << "stack empty!!!\n";
        return 0;
    }
 
    // updating minimum element
    if (size > 0 && arr[size - 1].second > arr[size].second) {
        minn = arr[size - 1].second;
    }
    arr.pop_back();
    size -= 1;
    return 1;
}
 
// utility function for returning min element till now;
int stack::GetMin()
{
    if (size == -1) {
        cout << "stack empty!!\n";
        return 0;
    }
    return arr[size].second;
}
 
// Driver code
int main()
{
    stack s;
    int success = s.AddElement(5);
    if (success == 1)
        cout << "5 inserted successfully\n";
 
    success = s.AddElement(7);
    if (success == 1)
        cout << "7 inserted successfully\n";
 
    success = s.AddElement(3);
    if (success == 1)
        cout << "3 inserted successfully\n";
    int min1 = s.GetMin();
    cout << "min element  :: " << min1 << endl;
 
    success = s.RemoveLastElement();
    if (success == 1)
        cout << "removed successfully\n";
 
    success = s.AddElement(2);
    if (success == 1)
        cout << "2 inserted successfully\n";
 
    success = s.AddElement(9);
    if (success == 1)
        cout << "9 inserted successfully\n";
    int last = s.GetLastElement();
    cout << "Last element :: " << last << endl;
 
    success = s.AddElement(0);
    if (success == 1)
        cout << "0 inserted successfully\n";
    min1 = s.GetMin();
    cout << "min element  :: " << min1 << endl;
 
    success = s.RemoveLastElement();
    if (success == 1)
        cout << "removed successfully\n";
 
    success = s.AddElement(11);
    if (success == 1)
        cout << "11 inserted successfully\n";
    min1 = s.GetMin();
    cout << "min element  :: " << min1 << endl;
 
    return 0;
}


Java




// program to demonstrate customized data structure
// which supports functions in O(1)
import java.util.ArrayList;
public class Gfg
{
   
  // class Pair
  static class Pair{
    int element;
    int minElement;
 
    public Pair(int element, int minElement) {
      this.element = element;
      this.minElement = minElement;
    }
  }
  int min;
  ArrayList<Pair> stack = new ArrayList<>();
 
  public Gfg() {
    this.min = Integer.MAX_VALUE;
  }
 
  // utility function for adding a new element
  void addElement(int x)
  {
    if(stack.size() == 0 || x < min)
    {
      min=x;
    }
    Pair pair = new Pair(x,min);
    stack.add(pair);
    System.out.println(x + " inserted successfully");
  }
 
  // utility function for returning last element of stack
  int getLastElement()
  {
    if (stack.size() == 0)
    {
      System.out.println("UnderFlow Error");
      return -1;
    }
    else
    {
      return stack.get(stack.size() - 1).element;
    }
  }
 
  // utility function for removing last element successfully;
  void removeLastElement()
  {
 
    if (stack.size() == 0)
    {
      System.out.println("UnderFlow Error");
    }
    else if (stack.size() > 1)
    {
      min=stack.get(stack.size() - 2).minElement;
    }
    else
    {
      min=Integer.MAX_VALUE;
    }
    stack.remove(stack.size() - 1);
    System.out.println("removed successfully");
  }
 
  // utility function for returning min element till now;
  int getMin()
  {
    if (stack.size() == 0)
    {
      System.out.println("UnderFlow Error");
      return -1;
    }
    return stack.get(stack.size() - 1).minElement;
  }
 
  // Driver Code
  public static void main(String[] args) {
    Gfg newStack = new Gfg();
    newStack.addElement(5);
    newStack.addElement(7);
    newStack.addElement(3);
    System.out.println("min element :: "+newStack.getMin());
    newStack.removeLastElement();
    newStack.addElement(2);
    newStack.addElement(9);
    System.out.println("last element :: "+newStack.getLastElement());
    newStack.addElement(0);
    System.out.println("min element :: "+newStack.getMin());
    newStack.removeLastElement();
    newStack.addElement(11);
    System.out.println("min element :: "+newStack.getMin());
  }
}
 
// This code is contributed by AkashYadav4.


Python3




# Program to demonstrate customized data structure
# which supports functions in O(1)
import sys
 
stack = []
Min = sys.maxsize
 
# Utility function for adding a new element
def addElement(x):
     
    global Min, stack
    if (len(stack) == 0 or x < Min):
        Min = x
    pair = [x, Min]
    stack.append(pair)
    print(x, "inserted successfully")
 
# Utility function for returning last
# element of stack
def getLastElement():
     
    global Min, stack
     
    if (len(stack) == 0):
        print("UnderFlow Error")
        return -1
    else:
        return stack[-1][0]
 
# Utility function for removing last
# element successfully;
def removeLastElement():
     
    global Min, stack
    if (len(stack) == 0):
        print("UnderFlow Error")
    elif (len(stack) > 1):
        Min = stack[-2][1]
    else:
        Min = sys.maxsize
    stack.pop()
     
    print("removed successfully")
 
# Utility function for returning min
# element till now;
def getMin():
     
    global Min, stack
    if (len(stack) == 0):
        print("UnderFlow Error")
        return -1
         
    return stack[-1][1]
 
# Driver code
addElement(5)
addElement(7)
addElement(3)
print("min element ::", getMin())
removeLastElement()
addElement(2)
addElement(9)
print("Last element ::", getLastElement())
addElement(0)
print("min element ::", getMin())
removeLastElement()
addElement(11)
print("min element ::", getMin())
 
# This code is contributed by mukesh07


C#




// program to demonstrate customized data structure
// which supports functions in O(1)
using System;
using System.Collections.Generic;
class GFG {
 
  static List<Tuple<int,int>> stack = new List<Tuple<int,int>>();
  static int min = Int32.MaxValue;
  
  // utility function for adding a new element
  static void addElement(int x)
  {
    if(stack.Count == 0 || x < min)
    {
      min=x;
    }
    Tuple<int,int> pair = new Tuple<int,int>(x,min);
    stack.Add(pair);
    Console.WriteLine(x + " inserted successfully");
  }
  
  // utility function for returning last element of stack
  static int getLastElement()
  {
    if (stack.Count == 0)
    {
      Console.WriteLine("UnderFlow Error");
      return -1;
    }
    else
    {
      return stack[stack.Count - 1].Item1;
    }
  }
  
  // utility function for removing last element successfully;
  static void removeLastElement()
  {
  
    if (stack.Count == 0)
    {
      Console.WriteLine("UnderFlow Error");
    }
    else if (stack.Count > 1)
    {
      min=stack[stack.Count - 2].Item2;
    }
    else
    {
      min=Int32.MaxValue;
    }
    stack.RemoveAt(stack.Count - 1);
    Console.WriteLine("removed successfully");
  }
  
  // utility function for returning min element till now;
  static int getMin()
  {
    if (stack.Count == 0)
    {
      Console.WriteLine("UnderFlow Error");
      return -1;
    }
    return stack[stack.Count - 1].Item2;
  }
   
  static void Main() {
    addElement(5);
    addElement(7);
    addElement(3);
    Console.WriteLine("min element :: "+getMin());
    removeLastElement();
    addElement(2);
    addElement(9);
    Console.WriteLine("Last element :: "+getLastElement());
    addElement(0);
    Console.WriteLine("min element :: "+getMin());
    removeLastElement();
    addElement(11);
    Console.WriteLine("min element :: "+getMin());
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
    // program to demonstrate customized data structure
    // which supports functions in O(1)
     
    let min;
    let stack = [];
 
    min = Number.MAX_VALUE
 
    // utility function for adding a new element
    function addElement(x)
    {
      if(stack.length == 0 || x < min)
      {
        min=x;
      }
      let pair = [x,min];
      stack.push(pair);
      document.write(x + " inserted successfully" + "</br>");
    }
 
    // utility function for returning last element of stack
    function getLastElement()
    {
      if (stack.length == 0)
      {
        document.write("UnderFlow Error" + "</br>");
        return -1;
      }
      else
      {
        return stack[stack.length - 1][0];
      }
    }
 
    // utility function for removing last element successfully;
    function removeLastElement()
    {
 
      if (stack.length == 0)
      {
        document.write("UnderFlow Error" + "</br>");
      }
      else if (stack.length > 1)
      {
        min=stack[stack.length - 2][1];
      }
      else
      {
        min=Number.MAX_VALUE;
      }
      stack.pop();
      document.write("removed successfully" + "</br>");
    }
 
    // utility function for returning min element till now;
    function getMin()
    {
      if (stack.length == 0)
      {
        document.write("UnderFlow Error" + "</br>");
        return -1;
      }
      return stack[stack.length - 1][1];
    }
     
    addElement(5);
    addElement(7);
    addElement(3);
    document.write("min element :: "+getMin() + "</br>");
    removeLastElement();
    addElement(2);
    addElement(9);
    document.write("Last element :: "+getLastElement() + "</br>");
    addElement(0);
    document.write("min element :: "+getMin() + "</br>");
    removeLastElement();
    addElement(11);
    document.write("min element :: "+getMin() + "</br>");
     
    // This code is contributed by rameshtravel07.
</script>


Output

5 inserted successfully
7 inserted successfully
3 inserted successfully
min element  :: 3
removed successfully
2 inserted successfully
9 inserted successfully
Last element :: 9
0 inserted successfully
min element  :: 0
removed successfully
11 inserted successfully
min element  :: 2

Time complexity: Each function runs in O(1)

Auxiliary space: O(n) for stack

 



Previous Article
Next Article

Similar Reads

Customized Debugging in Sublime Text using C++ for Competitive Programming
Competitive Programming is a mental sport that enables us to code a given problem under provided constraints. The purpose of this article is to guide every individual on how they can debug their code efficiently during a contest.Prerequisite: Setting up Sublime Text for C++ Competitive Programming Environment Time is something that is precious and
15+ min read
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
Which data structure is used by Map?
What is a Map? Before learning the data structure used by a map, let us have an overlook of map. Map is the part of the STL library that stores key value pairs in it and no two values have the same keys but the different keys can store similar values. The map stores keys in sorted order. These are some functions which map uses with their Time Compl
2 min read
How to Recognize which Data Structure to use in a question?
Data structures are fundamental components in computer science that help organize and store data effectively. Choosing the right data structure is crucial for solving problems efficiently. Different data structures have unique properties that make them suitable for specific types of problems. Understanding the Problem:Before selecting a data struct
4 min read
Is array a Data Type or Data Structure?
What is Data Type? In computer programming, a data type is a classification of data that determines the type of values that can be stored, manipulated, and processed. It tells the computer what kind of data a particular variable or constant can hold, and what operations can be performed on that data. Common data types include integers, floating-poi
8 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
Difference between data type and data structure
Data Type A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compile
4 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
Design a structure which supports insertion and first non-repeating element in O(1) time
Design a Data structure which supports insertion and first non-repeating element in O(1) time. Operations that are supported by the data structure: Insertion: Insert a element into the data structure.First non-repeating Element: First non-repeating element into the array. Note: If there is no non-repeating element in the array then print -1. Consid
12 min read
Find the element before which all the elements are smaller than it, and after which all are greater
Given an array, find an element before which all elements are smaller than it, and after which all are greater than it. Return the index of the element if there is such an element, otherwise, return -1. Examples: Input: arr[] = {5, 1, 4, 3, 6, 8, 10, 7, 9}; Output: 4 Explanation: All elements on left of arr[4] are smaller than it and all elements o
15+ min read
Article Tags :
Practice Tags :