Stack Implementation with o(1) - java

I am trying to implement kind of Stack, which has push(), pop(), getMaxSoFar().
It should be executed o(1) time. However, I got an error in push(T value), and I don't know why. The error message said the operator ">=" is not defined in the type of T. I just wanted to check the code so I put int type instead of then it worked.
class FastMaxStack<T>
{
private Stack<T> stack;
private Stack<T> maxStack;
public FastMaxStack()
{
stack = new Stack();
maxStack = new Stack();
}
public void push(T value)
{
if(maxStack.isEmpty())
{
maxStack.push(value);
}
else if(value >= maxStack.peek())
{
maxStack.push(value);
}
stack.push(value);
}
public T pop()
{
maxStack.pop();
return stack.pop();
}
public T getMaxSoFar()
{
return maxStack.peek();
}
}

Your push method is assuming that the >= operator is supported for every conceivable type T. However, that operator is only supported for numeric types.
Perhaps you should define your class to operate for integers only, and not any data type.
On the other hand, perhaps you could implement your class for all Comparables.
class FastMaxStack<Comparable<T>>
{
//etc...
}

(too long for a comment)
There is another problem.
push always pushes on stack, but only pushes on maxStack if the value is at least as large as the top. So far, so good.
But pop always pops from both. Two problems:
Even if you pop as many times as you push, there can be an EmptyStackException if maxStack does not have enough elements (which will happen if you don't push values in increasing order).
Even if there is no exception, the value of getMaxSoFar won't be correct. As I understand what you are trying to do, maxStack is supposed to hold in top the max element of the stack in its current state. But imagine you push a value smaller than top, maxStack is not updated, and if you pop (from both then), the max is lost in maxStack. But it's still here in stack.

Related

Implementation of minstack with two stacks which is failing at Pop condition

I am implementing a minstack algorithm and across something strange, Maybe I am missing either 'Some Stack concept' or 'Some Java concept' here. I am making using of two stacks(st and st2) to perform my minstack operations. Below is my pop method which fails at if condition:
Method 1 - FAILS:
public void pop() {
if(st.pop() == st2.peek())
st2.pop();
}
Below is the Pop method which works fine when I store the st.pop() results in a variable 'a':
Method 2 - PASSES:
public void pop() {
int a = st.pop();
if(a == st2.peek())
st2.pop();
}
Please assume that there are integer elements in both the stacks and the value from st.pop() is equal to st2.peek(). I would like the understand the difference as to why the st.pop() would not work in if state of method 1 and works in method 2 after storing results of st.pop() into a temporary variable a
If I understand the question correct, st.pop() doesn't work in the first method because the type of elements in st are never explicitly stated (ie. st could be initialized like Stack st = new Stack();).
As a result, any object (doesn't have to be an int) could be pushed onto the stack, so when the stack is popped, it's unclear what data type is returned, which causes the if statement to fail.
In the second method, the popped item is explicitly defined as an int in the variable a, so when the comparison is made with a, the if statement works as expected.

In Java, how do you enforce Stack.pop() as a parameter?

I have two stacks.
I want to be able to push any element onto one, but only if it was popped off the other.
Instead of My current function looks like this:
public void pushValue(int poppedValue) {
Stack.push(value)
}
I want the function to look something like this:
public void pushValue(pop() poppedValue) {
Stack.push(value)
}
How could I set the pop() function as a parameter, instead of an int?
In other words, how can I set the parameter to only accept a value that was popped from somewhere?
There is no way in Java to express that constraint. (Or in any other language, AFAIK)
(IMO) the best you can do is to pass the second Stack as an argument to the first one and make the first one responsible for popping a value; e.g.
public class Stack {
...
public int transferValue(Stack source) {
int res = source.pop(); // throws exception if source is empty
this.push(value);
return res;
}
}
This leaves you with problems regarding push:
Do you remove it entirely from the Stack API? If so, how do the elements get onto the source stack?
Do you split the Stack API into Stack and StackWithoutPush? If yes, which is the super-class / super-interface? Neither alternative is perfect. Either way, the subclass violates the contract of the superclass in some sense. (C.f. the problem of List versus UnmodifiableList APIs.)
Your syntax isn't possible, but you could make the second stack a member field and then push iff the value is present when you peek at the second stack (through the field).
private Stack otherStack = null; // <-- set this somehow (constructor?), or pass it.
public void pushValue(int newValue) {
if (otherStack != null && otherStack.peek() == newValue) {
Stack.push(newValue); // <-- please observe naming conventions (stack)
}
}
Then, pop() the value. Basically, peek, push and then pop.

Assign an Object to a String

I am writing a program that generates a maze and then finds a path. I store all my moves into a stack called visitStack (if I move north, I store "N" into it, if Northeast then "NE", on and on). For part of my backtracking I need to be able to take the data from the stack and reverse my steps if I hit a dead end, but I've hit a snag here.
I need to assign a value popped from a stack to a String variable, but I always get a compiler error. I've tried using toString, instantiating the String as an object with the popped stack value as the parameter, and still can't get it. I've been on this for about an hour. Here is the code and error message.
String direction = visitStack.pop();
Assuming that you are using java.util.Stack I suspect that you didn't describe what type of elements it should store, which is why compiler sees return type of pop as Object (common ancestor of all types).
Also assuming that stack should store only String elements it should be declared as
Stack<String> visitStack = new Stack<String>();
Now compiler should see return type of pop() as String which will allow you to store its result in other String type reference
String direction = visitStack.pop();
Above solution is preferred when you are sure that stack can contain only strings, but if there are some other elements you will need to either explicitly cast returned object to String (if you are sure that it will be instance of String) like
String direction = (String) visitStack.pop();
or if you are not sure what object will be returned calling toString() method to get its string representation:
String direction = visitStack.pop().toString();
If you define your stack as Stack<String>, pop() will return a String, and you won't need to mess around with casting. If you cannot, for some reason, and you're positive the object being popped is a String, you can cast it explicitly:
String direction = (String)visitStack.pop();
Since you are using a limited number of possible values you shloud use ENUMS for type Safety.
Use :
Stack<Direction> visitStack=new Stack<>();
visitStack.push(Direction.EAST);
Direction dir=visitStack.peek();
String dir2=visitStack.pop().toString();
System.out.println(dir);
System.out.println(dir2);
your Direction should look like:
public enum Direction {
North("N"), NORTH_WEST("NW"), NORTH_EAST("NE"), EAST("E")
, SOUTH_EAST("SE"), SOUTH("S"), SOUTH_WEST("SW"), WEST("W");
private String shortName;
private Direction(String shortName) {
this.shortName = shortName;
}
#Override
public String toString() {
return this.shortName;
}
}

Creating and array of E in Generic SortedSet

As a sample, I am developing a simple MySortedSet<E> in java which implements SortedSet<E> interface. It is backed up with a simple array which is E[] array.
I have several questions regarding that:
This is the class: (I am not writing entire code, instead of related parts)
public class MySortedSet<E> implements SortedSet<E>, Iterator<E> {
private E[] array;
private Comparator<? super E> _comparator;
private int size = 0;
private int capacity;
#SuppressWarnings("unchecked")
public MySortedSet() {
this.capacity = 10;
this.array = (E[]) new Object[this.capacity];
// this.array = Array.newInstance(Class<E> var,int size);
// We have to get Class<E> from outside caller.
}
}
Question 1: Can somebody please tell me whether there is a better solution to create a new array in constructor instead of this this.array = (E[]) new Object[this.capacity];
ArrayList<E> stores the elements in a plain Object[], primitive values are autoboxed, and it assigns null to holes left by removed elements.
Classes that implement Comparable<E> must implement int compareTo(E other) which works similarly to compare(E o1, E o2) from Comparator. You could either check your internal comparator for null and fall back on the natural ordering of the objects, or you could define an internal "use the natural ordering" comparator implementation.
Binary search is a method of minimizing the number of comparisons needed to locate an item or the spot where an item should be inserted into a sorted list. Instead of checking each element starting with the first, you start at the midpoint of the list. If the sought item should come before the found element, shift halfway toward the front and repeat; otherwise shift halfway to the end and repeat. Each time you repeat, you use the previous lower/upper bound and the midpoint as the new sublist, halving the number of elements in each step.
Think of trying to guess a number between 1 and 100 where each time you are told whether you guessed too high or too low.
50 - too high
25 - too low
37 - too high
31 - too low
34 - too low
35 - correct!
Either you should keep doing what you're doing here, or you should keep it as an Object[] and cast the values when you're outputting them. (The ArrayList implementation, for example, does the latter.)
You can change your code to remove the unsafe cast:
public MySortedSet(Class<E> clazz) {
capacity = 10;
array = Array.newInstance(clazz, capacity);
}
Although it forces the client code to provide a Class<E> object, this is a very common code pattern used to work around this class of problem (where you need a typed Class object in a constructor).

Java - sorted stack

I need a sorted stack. I mean, the element removed from the stack must be the one with great priority. Stack dimension varies a lot (becomes bigger very fast).
I need also to search elements in that stack.
Does Java give some good implementation for this? What class or algorithm do you suggest for this?
I'm using a PriorityQueue right now which I consider reasonable except for searching, so I'm wondering if I can use something better.
I also need to remove elements!
In summary: I need to maintain a sorted stack/queue, get the element with greater priority fast and also remove elements as fast as possible
TreeSet is a sorted set. Set means no duplicates though.
add() adds an item, which is inserted in the correct sorted place.
pollLast() removes and returns the last item,
pollFirst() removes and returns the first item.
Java doesn't provide a PriorityStack, but you could easily write one by wrapping the PriorityQueue class and providing the push/pop methods to manage the underlying queue.
import java.util.Stack;
public class Q6_SortStack {
/**
* #param args
* Write a program to sort a stack in ascending order.
* You should not make any assumptions about how the stack is implemented.
* The following are the only functions that should be used to
* write this program: push | pop | peek | isEmpty.
*/
public static void main(String[] args) {
int[] array = {2,5,10,3,11,7,13,8,9,4,1,6};
Stack<Integer> s1 = new Stack<Integer>();
//int[] array = {2,4,1,6};
for(int i=0;i<array.length;i++){
s1.push(array[i]);
}
//displayStack(s1);
displayStack(sortStack(s1));
}
public static Stack<Integer> sortStack(Stack<Integer> s1){
Stack<Integer> s2 = new Stack<Integer>();
while(!s1.isEmpty()){
int temp = s1.pop();
while(!s2.isEmpty() && s2.peek()<temp){
s1.push(s2.pop());
}
s2.push(temp);
}
return s2;
}
public static void displayStack(Stack<Integer> s){
while(!s.isEmpty())
System.out.print(s.pop()+"->");
System.out.println("end");
}
}
You can always use two data structures. A priority queue and a map. The first will let you get the smallest/largest item, and the second will let you search items fast. You just need to wrap them in the logic to keep them in sink (which shouldn't be too hard)
You could modify/overload the method you use to push data into your stack such that it inserts into the correct or "sorted" position. Otherwise, if you're implementing the stack using an array of some primitive datatype, you could use Arrays.sort(*Stack data array goes here*) from the java.util package every time you push data into the stack.

Categories