How to implement stack which stores only unique values in Java

1.1k Views Asked by At

I'm trying to implement the unique stack. If I try to extend the stack class and use the contains it will look the entire stack and the time complexity will become O(n). So I tried to extend the LinkedHashSet which will remove duplicates by itself and maintains the order. I'm able to implement all the methods except the pop.

Can anyone share thoughts here?

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Stack;
import java.util.stream.Stream;

public class UniqueStack<E> extends LinkedHashSet<E>{

    private int size = 0;

    @Override
    public Stream<E> stream() {
        return super.stream();
    }

    public boolean push(E e) {
        if (!contains(e)) {
            ++size;
            return super.add(e);
        }
        return false;
    }

    public E pop() {       
       // struck here
    return;
    }
}

1

There are 1 best solutions below

0
WJS On

I believe it would be best to use an instance of a regular stack for stack operations but use the efficiency of a HashSet to track duplicates. Additional methods could be added using the same idea.

    UniqueStack<Integer> stack = new UniqueStack<>();

    stack.push(10);
    stack.push(20);
    stack.push(30);
    stack.push(40);
    stack.push(30); // ignored
    stack.push(50);

    System.out.println(stack);
    int v = stack.pop();
    System.out.println(v);
    System.out.println(stack);
    stack.push(1);
    stack.push(2);
    System.out.println(stack);
    v = stack.pop();
    System.out.println(v);
    System.out.println(stack);

The output of this is

[10, 20, 30, 40, 50]
50
[10, 20, 30, 40]
[10, 20, 30, 40, 1, 2]
2
[10, 20, 30, 40, 1]

class UniqueStack<E> extends LinkedHashSet<E> {

    Stack<E> stack = new Stack<>();
    private int size = 0;


    public Stream<E> stream() {
        return stack.stream();
    }

    public boolean push(E e) {
        if (!contains(e)) {
            ++size;
            stack.push(e);
            return add(e);
        }
        return false;
    }

    public E pop() {
        E val = null;
        if (!stack.isEmpty()) {
            --size;
            val = stack.pop();
            remove(val);
        }
        return val;
    }
}