Question

In: Computer Science

5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and...

  1. 5 marks] A MinStack supports three main operations: the standard Stack operations push(x) and pop() and the non-standard min() operation which returns the minimum value stored on the stack. The zip file gives an implementation SlowMinStack that implements these operations so that push(x) and pop() each run in O(1) time, but  min()runs in Θ(n) time.
    For this question, you should complete the implementation of FastMinStack that implements all three operations in O(1) time per operation. As part of your implementation, you may use any of the classes in the Java Collections Framework and you may use any of the source code provided with the Java version of the textbook. Don't forget to also implement the size() and iterator()* methods.
    Think carefully about your solution before you start coding. Here are two hints: (i) don't use any kind of SortedSet or SortedMap, These all require Ω(logn) time per operation; (ii) take a look at the sample solution for Part 10 of Assignment 1.  Really understanding this solution will help you design your data structure.
  2. [5 marks] A MinDeque supports five operations: The standard Deque operations addFirst(x), removeFirst(), addLast(x), and removeLast() and the non-standard min() operation that returns the minimum value stored in the Deque. Again, the zip file provides an implementation SlowMinDeque that supports each of the first four operation in O(1) time per operation but requires Ω(n) time for the min() operation.
    For this question, you should complete the implementation of FastMinDeque that implements all five operations in O(1) (amortized) time per operation. As part of your implementation, you may use any of the classes in the Java Collections Framework and you may use any of the source code provided with the Java version of the textbook. Don't forget to also implement the size() and iterator()* methods. Think carefully about your solution before you start coding. Here are two hints: (i) don't use any kind of SortedSet or SortedMap, These all require Ω(logn) time per operation; (ii) consider using one of the techniques we've seen in class for implementing the Deque interface.

*You can still get part marks without correctly implementing the iterator() method. But for full marks, the iterator() method needs to return an Object that supports the next() and hasNext() methods from the Iterator<T> interface. For a MinStack, the iterator should output the elements at the bottom of the stack first (the elements that have been in the stack the longest), finishing with the element at the top of the stack (the element that would be returned by a call to pop()). For a MinDeque, the iterator should output the elements beginning with the first element (the one that would be returned by removeFront()) and finishing with the last element (the one that would be returned by removeLast()).

Hint: There's no need to build your iterators from scratch. The collections in java.util all have iterators.

package comp2402a2;

import java.util.Comparator;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class FastMinStack<T> implements MinStack<T> {

protected Comparator<? super T> comp;

public FastMinStack() {
this(new DefaultComparator<T>());
}

public FastMinStack(Comparator<? super T> comp) {
this.comp = comp;
// TODO: Your code goes here
}

public void push(T x) {
// TODO: Your code goes here
}

public T pop() {
// TODO: Your code goes here
return null;
}

public T min() {
// TODO: Your code goes here
return null;
}

public int size() {
// TODO: Your code goes here
return -1;
}

public Iterator<T> iterator() {
// TODO: Your code goes here
return null;
}

public Comparator<? super T> comparator() {
return comp;
}
}

package comp2402a2;

import java.util.Comparator;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class FastMinDeque<T> implements MinDeque<T> {

protected Comparator<? super T> comp;

public FastMinDeque() {
this(new DefaultComparator<T>());
}

public FastMinDeque(Comparator<? super T> comp) {
this.comp = comp;
// TODO: Your code goes here
}

public void addFirst(T x) {
// TODO: Your code goes here
}

public void addLast(T x) {
// TODO: Your code goes here
}

public T removeFirst() {
// TODO: Your code goes here
return null;
}

public T removeLast() {
// TODO: Your code goes here
return null;
}

public T min() {
// TODO: Your code goes here
return null;
}

public int size() {
// TODO: Your code goes here
return -1;
}

public Iterator<T> iterator() {
// TODO: Your code goes here
return null;
}

public Comparator<? super T> comparator() {
return comp;
}

}

Solutions

Expert Solution

import java.util.Comparator;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class FastMinStack<T> implements MinStack<T> {

  protected Comparator<? super T> comp;
  
  // we will take two linked list ds will hold our original value
  // and auxiliary will store the minimum value till now.
  
  protected List<T> ds;
  protected List<T> auxiliary;

  public FastMinStack() {
    this(new DefaultComparator<T>());
  }

  public FastMinStack(Comparator<? super T> comp) {
    this.comp = comp;
    ds=new LinkedList<T>();
    auxiliary=new LinkedList<T>();
  }

  public void push(T x) {
    // TODO: Your code goes here
        
          // when we push any element we will see that if stack is empty then insert 
          // x into both ds and auxiliary list
          // if stack is not empty then compare the top value from auxiliary list
          // with x if x is smaller then add it to auxiliary list also
          
          if(ds.size()==0)
          {
                  ds.add(x);
                  auxiliary.add(x);
                  return ;
                  
          }
          
          T y=auxiliary.get(auxiliary.size()-1);
          if(comp.compare(x, y)<0)
          {
                  auxiliary.add(x);
          }
          
          
  }

  public T pop() {
    // TODO: Your code goes here
         //  while poping we will see that if poped element is also top element of the
          // auxiliary list then also removed from auxiliary list.
          
         if(size()==0)
                 return null;
         T x=ds.remove(size()-1);
         if(comp.compare(x, auxiliary.get(size()-1))==0)
         {
                 auxiliary.remove(auxiliary.size()-1);
         }
         
    return null;
  }

  public T min() {
    if(size()==0)
    return null;
    return auxiliary.get(auxiliary.size()-1);
  }

  public int size() {
    // TODO: Your code goes here
    return ds.size();
  }

  public Iterator<T> iterator() {
    // TODO: Your code goes here
    return ds.iterator();
  }

  public Comparator<? super T> comparator() {
    return comp;
  }
}

Related Solutions

Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the...
Reverse the contents of a stack using only stack operations [ push() and pop()  ]. Using the java and give the explanation
(In Java) Design a stack that supports getMin(), pop() and push() in O(1) time. Must use...
(In Java) Design a stack that supports getMin(), pop() and push() in O(1) time. Must use the iterator and comparator, does not need to be a linked list, although it's what I've tried using. I'm using another tester class to test this class. import java.util.Comparator; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import java.util.Stack; import java.util.ListIterator; public class FMinStack<T> implements MinStack<T> { protected Comparator<? super T> comp; T min; protected List<T> ds; public FMinStack() { this(new DefaultComparator<T>()); } public FMinStack(Comparator<? super...
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting...
Using Python list tools, create the standard stack (push, pop) and queue (enqueue, dequeue) operations Counting Letter Challenge: Create a function that... Takes in a string as parameter Counts how often each letter appears in the string Returns a dictionary with the counts BONUS: make it so lowercase and uppercase letter count for the same letter
JAVA Stack - Implementation. You will be able to use the push, pop and peek of...
JAVA Stack - Implementation. You will be able to use the push, pop and peek of Stack concept. Post-Fix calculator - When an arithmetic expression is presented in the postfix form, you can use a stack to evaluate the expression to get the final value. For example: the expression 3 + 5 * 9 (which is in the usual infix form) can be written as 3 5 9 * + in the postfix. More interestingly, post form removes all parentheses...
Write a function that returns the largest value in a stack (only use push and pop)
Write a function that returns the largest value in a stack (only use push and pop)
Consider an ADT with the same operators as a stack (push(), pop(), size(), empty()), except that...
Consider an ADT with the same operators as a stack (push(), pop(), size(), empty()), except that the pop() operator returns the largest element rather than the element most recently pushed. For this to make sense, the objects on the stack must be totally ordered (e.g. numbers). Describe array and linked list implementations of the ADT. Your implementations should be as time and space efficient as you can manage. Give the running times for the CRUD operators.
# ArrayStack # TODO: push and pop using array stack with doubling technique. import numpy as...
# ArrayStack # TODO: push and pop using array stack with doubling technique. import numpy as np from future import print_function # Definisi class ArrayStack class ArrayStack(object): def __init__(self): self.data = np.zeros(20, dtype=np.int) self.count = 0 def isEmpty(self): pass # ubah saya def size(self): pass # ubah saya def push(self, obj): pass # ubah saya def pop(self): pass # ubah saya #-------------------------- # End of class if __name__ == "__main__": stack = ArrayStack() randn = np.random.permutation(1000) for i in range(1000):...
All code should be in Python 3. Implement the Stack Class, using the push, pop, str,...
All code should be in Python 3. Implement the Stack Class, using the push, pop, str, init methods, and the insurance variable 'list'.
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3....
Please code in C /* Implements functions that operate on Stack 1. PUSH 2. POP 3. isEmpty 4. PEEK 5. Size */ #include <stdio.h> #define CAPACITY 1000 //Two stacks .. for each stack we need // 1. An Array that can hold capacity of elements // 2. A top initialzied to -1 (signifying that the stak is empty at the start) //NOTE : THESE STACKS ARE OF TYPE CHAR :( ... so you need to FIX IT!!!! to int and...
void Stack :: push(float x) {   if (count _______ capacity)                               
void Stack :: push(float x) {   if (count _______ capacity)                                                    // If there is no room for a new value { float* new_A = ______ float[ 2 * ________ ];                     // Create a new array with two-fold capacity for (int i = 0; i < count; ++i)                                   // Copy existing data to new array _______= A[i]; delete[]__________ ;                                                          // Delete old array A = new_A;                                                            // Connect to the new array capacity *= _______ ;                                                    // Update the capacity } A[ ______] =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT