LeetCode 155. Min Stack - algorithm

I am trying to solve the problem using extra space. In the pop() function, when I compare the top of both the stacks inside the if condition, the following test case is failing:
["MinStack","push","push","push","push","pop","getMin","pop","getMin","pop","getMin"]\ [[],[512],[-1024],[-1024],[512],[],[],[],[],[],[]]
When I store the top of the first stack and then compare it with the top of the second stack, all the test cases pass.
Can someone please help me understand what is causing this?
The below code caused the test case to fail.
class MinStack {
Stack<Integer> s;
Stack<Integer> auxStack;
public MinStack() {
s = new Stack<Integer>();
auxStack = new Stack<Integer>();
}
public void push(int val) {
this.s.push(val);
if (this.auxStack.empty() || val <= this.auxStack.peek()) {
this.auxStack.push(val);
}
}
public void pop() {
if (this.s.peek() == this.auxStack.peek()) {
this.auxStack.pop();
}
this.s.pop();
}
public int top() {
return this.s.peek();
}
public int getMin() {
return this.auxStack.peek();
}
}
The below code worked for all the test cases.
class MinStack {
Stack<Integer> s;
Stack<Integer> auxStack;
public MinStack() {
s = new Stack<Integer>();
auxStack = new Stack<Integer>();
}
public void push(int val) {
this.s.push(val);
if (this.auxStack.empty() || val <= this.auxStack.peek()) {
this.auxStack.push(val);
}
}
public void pop() {
int ans = this.s.pop();
if (ans == this.auxStack.peek()) {
this.auxStack.pop();
}
}
public int top() {
return this.s.peek();
}
public int getMin() {
return this.auxStack.peek();
}
}

The problem is that you are comparing Integer objects, not int values. The data type stored on the stack is Integer. So the peek() method returns an Integer, not int, which means that the following comparison is always false:
this.s.peek() == this.auxStack.peek()
Fix this by explicitly converting at least one of those two Integer objects to an int:
this.s.peek().intValue() == this.auxStack.peek()
Or use the equals method:
this.s.peek().equals(this.auxStack.peek())

Related

create an application that prompts the user for a set of five integer numbers using data structure

*Using the ArrayBoundedStack class,create an application named EditNumbers that prompts the user for a set of five integer numbers, push its content into a stack, and then repeatedly prompts the user for changes to numbers, until the user enters an X, indicating the end of changes. Legal change operations are: M, A, R, and C.
• Option M return the maximum value in the set
• Option A v1 means add v1 to each number in the set
• Option R means reverse the numbers in the set
• Option C v1 v2 means change all occurrences of v1 to v2
*
(arrayboundedstack) using this codes bellow
**1)** package stack;
public class ArrayBoundedStack <T> implements StackInterface <T> {
private final int DEFSIZE=100;
private int index=-1;
private T[] arr;
public ArrayBoundedStack()
{
arr=(T[])new Object[DEFSIZE];
}
public ArrayBoundedStack(int size)
{
arr=(T[])new Object[size];
}
public boolean isFull()
{
return index == (arr.length-1);
}
public boolean isEmpty()
{
return index == -1;
}
public void push(T element)
{
if(!isFull())
{
index++;
arr[index]=element;
}
else{
throw new OverflowStackException("The stack is fill , you cannot push");
}
}
public void pop()
{
if(!isEmpty())
{
arr[index]=null;
index--;
}
else{
throw new UnderflowStackException("The stack is empty , you cannot pop");
}
}
public T top()
{
T temp=null;
if (!isEmpty())
temp=arr[index];
else{
throw new UnderflowStackException("The stack is empty , there is no top");
}
return temp;
}
}
**2) ** package stack;
public class MyApp1 {
public static void printStack(ArrayBoundedStack<Integer> st)
{
ArrayBoundedStack<Integer> temp=new ArrayBoundedStack<>(10);
System.out.println("the stack contains:");
while(!st.isEmpty())
{
System.out.println(st.top());
temp.push(st.top());
st.pop();
}
while(!temp.isEmpty())
{
st.push(temp.top());
temp.pop();
}
}
public static void nonNegativeStack(ArrayBoundedStack<Integer> st)
{
ArrayBoundedStack<Integer> temp=new ArrayBoundedStack<>();
while(!st.isEmpty())
{
if(st.top()>=0)
temp.push(st.top());
st.pop();
}
while(!temp.isEmpty())
{
st.push(temp.top());
temp.pop();
}
}
public static void main(String[] args)
{
ArrayBoundedStack<Integer> st=new ArrayBoundedStack<>(10);
st.push(10);
st.push(15);
st.push(30);
printStack(st);
System.out.println("the top of stack is " + st.top());
st.pop();
st.pop();
st.pop();
System.out.println("the top of stack is " + st.top());
}
}
**3) ** package stack;
public class MyApp2 {
public static void main(String[] args)
{
System.out.println("This is a test for exception");
throw new OverflowStackException("the stack is full");
}
}
**4)** package stack;
public class OverflowStackException extends RuntimeException{
public OverflowStackException()
{
super();
}
public OverflowStackException(String msg)
{
super(msg);
}
}
**5) ** package stack;
public interface StackInterface <T> {
public void push(T element) throws OverflowStackException;
public void pop() throws UnderflowStackException;
public T top()throws UnderflowStackException;
public boolean isFull();
public boolean isEmpty();
}
**6)**package stack;
public class UnderflowStackException extends RuntimeException{
public UnderflowStackException()
{
super();
}
public UnderflowStackException(String msg)
{
super(msg);
}
}
i made all the class up and i didnt know how to make a main class

Struggling terribly on how to start and complete a file

I am unsure how to complete these 3 methods. 4 Reference classes are also given (at the bottom)
I know I have to first start building the tree from the array "a" but I am not sure how to do that. SOS pls help. :(
The data stored in the binary tree are doubles. The binary tree will store the data only on the
leaves. The internal nodes are used for searching only.
Your tree will work like a normal BST, to find a target element, your program will compare it to the root of the current subtree and if the target is less than the value of the root you will recursively search on the left subtree.Otherwise, you will search on the right subtree.
Your tree will allow duplicate values, by keeping track of the
number of times that a particular value appears (this data is kept only in the leaves).
Your binary tree is always created from scratch given a sorted array of doubles, in such a way
that the root of every subtree (not a leaf) contains the average of the maximum element in the
left subtree and the minimum element in the right subtree.
Example:
Suppose that you are given the following array:
1, 2.3, 5.8, 5.8, 7.2, 7.2, 7.2, 8, 9.1, 9.2, 10, 10.3, 10.3, 11.9, 12.1, 12.3, 12.5, 13
The tree that is generated has a root with a value of 10.15, which is the average of the maximum
value of the left subtree (which is 10) and the minimum value of the right subtree (which is 10.3),
so the root has a value of (10+10.3)/2 = 10.15
The leaves have the actual values and the number of times each value appears.
public static Queue<BTNode<dataNode>> makeQueue(double[] a){
// Each element of the given array a must be inserted into a BTNode,
// this method returns a queue of BTNodes, each node will contain a dataNode
// the dataNode will have the value equal to the element of the array
// count equal to the number of times that the element repeats
// min and max must be equal to value.
// the BTNode created must have its parent, right, and left references set to null
return null;
}
public static Queue<BTNode<dataNode>> join(Queue<BTNode<dataNode>> myQueue){
// For every two elements dequeued from myQueue create a new root element and
// make the two dequeued elements be the left and right child of that root.
// Each new root must contain the min value, obtained from the left subtree,
// the max value, obtained from the right subtree, and the value should be
// equal to the average of the maximum value of the left subtree and the
// minimum value of the right subtree, count should be set equal to 0 (internal node)
// Enqueue each new root node into another queue and return that queue.
// In case that only one element is left in myQueue, just enqueue it
// in the queue that will be returned.
return null;
}
public static int search(BTNode<dataNode> root,double target) {
// given a target value recursively search on the left or the right subtrees
// by comparing the value in root to the target. You know that you got to a
// leaf when the value count of the root is not equal to 0.
return 0;
}
---------------
public class dataNode implements Comparable<dataNode>{
public double value;
public int count;
public double max;
public double min;
public dataNode() {
value=0;
count=0;
}
public int compareTo(dataNode node2) {
return 0;
}
public String toString() {
return "("+value+","+count+")";
}
}
---------
public class BTNode<T extends Comparable<T>> {
private T data;
private BTNode<T> left,right,parent;
public BTNode(T data,BTNode<T> left,BTNode<T> right,BTNode<T> parent) {
this.data=data;
this.left=left;
this.right=right;
this.parent=parent;
}
public BTNode<T> getLeft(){
return this.left;
}
public BTNode<T> getRight(){
return this.right;
}
public BTNode<T> getParent(){
return this.parent;
}
public T getData(){
return this.data;
}
public void setLeft(BTNode<T> left) {
this.left=left;
}
public void setRight(BTNode<T> right) {
this.right=right;
}
public void setParent(BTNode<T> parent) {
this.parent=parent;
}
public void setData(T data) {
this.data=data;
}
public String toString() {
return this.data.toString();
}
}
----------
public class DLL<T> {
private Node<T> first;
private Node<T> last;
private int count;
private Node<T> current;
public DLL() {
this.first=null;
this.last=null;
count=0;
}
public T getFirst() {
current=first;
if (first!=null)
return first.getData();
return null;
}
public T getNext() {
if (current!=null) {
current=current.getNext();
return current.getData();
}
return null;
}
public T getLast() {
if (last!=null)
return last.getData();
return null;
}
public void addFirst(T data) {
Node<T> n=new Node<T>(data,null,first);
if (this.first!=null) {
this.first.setPrev(n);
}
else {
this.last=n;
}
this.first=n;
count++;
}
public void addLast(T data) {
Node<T> n=new Node<T>(data,last,null);
if (this.last!=null) {
this.last.setNext(n);
}
else {
this.first=n;
}
this.last=n;
count++;
}
public void deleteFirst() {
if (this.first!=null) {
Node<T> newFirst=this.first.getNext();
this.first=newFirst;
if (newFirst!=null) {
newFirst.setPrev(null);
}
else {
this.last=null;
}
count--;
}
}
public void deleteLast() {
if (this.last!=null) {
Node<T> newLast=this.last.getPrev();
this.last=newLast;
if (newLast!=null) {
newLast.setNext(null);
}
else {
this.first=null;
}
count--;
}
}
public void traverse() {
Node<T> current=this.first;
while (current!=null) {
System.out.print(current.getData()+" ");
current=current.getNext();
}
}
public int size() {
return count;
}
public String toString() {
String ret="";
Node<T> current=this.first;
while (current!=null) {
ret=ret+"+"+current.getData();
current=current.getNext();
}
return ret;
}
}
------------
public class Node<T> {
private T data;
private Node<T> prev;
private Node<T> next;
public Node(T data,Node<T> prev,Node<T> next) {
this.data=data;
this.prev=prev;
this.next=next;
}
public T getData() {
return data;
}
public Node<T> getPrev(){
return prev;
}
public Node<T> getNext(){
return next;
}
public void setPrev(Node<T> prev) {
this.prev=prev;
}
public void setNext(Node<T> next) {
this.next=next;
}
}
-----------
public class Queue<T> {
private DLL<T> myList;
public Queue() {
myList=new DLL<T>();
}
public void enqueue(T element) {
myList.addFirst(element);
}
public T dequeue() {
T element=null;
if (myList.size()>0) {
element = myList.getLast();
myList.deleteLast();
}
return element;
}
public int size() {
return myList.size();
}
public boolean isEmpty() {
return myList.size()==0;
}
public void traverse() {
myList.traverse();
}
public static void main(String[] args) {
Queue<String> myQueue=new Queue<String>();
myQueue.enqueue("the");
myQueue.enqueue("quick");
myQueue.enqueue("brown");
myQueue.enqueue("fox");
myQueue.enqueue("jumps");
myQueue.enqueue("over");
myQueue.traverse();
System.out.println("dequeue->"+myQueue.dequeue());
myQueue.traverse();
myQueue.enqueue("the");
myQueue.enqueue("lazy");
myQueue.traverse();
System.out.println("dequeue->"+myQueue.dequeue());
myQueue.traverse();
}
}

get average value from a tree of nodes

I have to implement this method:
public int GetAverage(Node root){
//TODO implement
}
this method should get average value of all nodes of root tree. where :
public interface Node {
int getValue();
List<Node> getNodes();
}
do you have any ideas how to implement this method?
thank you
my attempt:
public static double value;
public static int count;
public static double getAverage(Node root) {
count++;
value += root.getValue();
for (Node node : root.getNodes()) {
getAverage(node);
}
return value / count;
}
but how to do it without the static fields outside of the method?
Simply traverse through all nodes and remember the count and the overall sum of all values. Then calculate the average. This is an example written in Java.
public interface INode {
int getValue();
List<INode> getNodes();
}
public class Node implements INode {
private List<INode> children = new ArrayList<INode>();
private int value;
#Override
public int getValue() {
return value;
}
#Override
public List<INode> getNodes() {
return children;
}
public static int getAverage(INode root) {
if (root == null)
return 0;
Counter c = new Counter();
calculateAverage(root, c);
return c.sum / c.count;
}
class Counter {
public int sum;
public int count;
}
private static void calculateAverage(INode root, Counter counter) {
if (root == null)
return;
counter.sum += root.getValue();
counter.count++;
// recursively through all children
for (INode child : root.getNodes())
calculateAverage(child, counter);
}
}
public static double getAverage(Node root) {
Pair p = new Pair(0,0);
algo(root, p);
return ((double) p.element1) / ((double) p.element2);
}
private static void algo(Node root, Pair acc) {
for(Node child : root.getNodes()) {
algo(child, acc);
}
acc.sum += root.getValue();
acc.nbNodes++;
}
With Pair defined as follows:
public class Pair {
public int sum;
public int nbNodes;
public Pair(int elt1, int elt2) {
this.sum = elt1;
this.nbNodes = elt2;
}
}

Storm Trident 'average aggregator

I am a newbie to Trident and I'm looking to create an 'Average' aggregator similar to 'Sum(), but for 'Average'.The following does not work:
public class Average implements CombinerAggregator<Long>.......{
public Long init(TridentTuple tuple)
{
(Long)tuple.getValue(0);
}
public Long Combine(long val1,long val2){
return val1+val2/2;
}
public Long zero(){
return 0L;
}
}
It may not be exactly syntactically correct, but that's the idea. Please help if you can. Given 2 tuples with values [2,4,1] and [2,2,5] and fields 'a','b' and 'c' and doing an average on field 'b' should return '3'. I'm not entirely sure how init() and zero() work.
Thank you so much for your help in advance.
Eli
public class Average implements CombinerAggregator<Number> {
int count = 0;
double sum = 0;
#Override
public Double init(final TridentTuple tuple) {
this.count++;
if (!(tuple.getValue(0) instanceof Double)) {
double d = ((Number) tuple.getValue(0)).doubleValue();
this.sum += d;
return d;
}
this.sum += (Double) tuple.getValue(0);
return (Double) tuple.getValue(0);
}
#Override
public Double combine(final Number val1, final Number val2) {
return this.sum / this.count;
}
#Override
public Double zero() {
this.sum = 0;
this.count = 0;
return 0D;
}
}
I am a complete newbie when it comes to Trident as well, and so I'm not entirely if the following will work. But it might:
public class AvgAgg extends BaseAggregator<AvgState> {
static class AvgState {
long count = 0;
long total = 0;
double getAverage() {
return total/count;
}
}
public AvgState init(Object batchId, TridentCollector collector) {
return new AvgState();
}
public void aggregate(AvgState state, TridentTuple tuple, TridentCollector collector) {
state.count++;
state.total++;
}
public void complete(AvgState state, TridentCollector collector) {
collector.emit(new Values(state.getAverage()));
}
}

Hadoop Raw comparator

I am trying to implement the following in a Raw Comparator but not sure how to write this?
the tumestamp field here is of tyoe LongWritable.
if (this.getNaturalKey().compareTo(o.getNaturalKey()) != 0) {
return this.getNaturalKey().compareTo(o.getNaturalKey());
} else if (this.timeStamp != o.timeStamp) {
return timeStamp.compareTo(o.timeStamp);
} else {
return 0;
}
I found a hint here, but not sure how do I implement this dealing with a LongWritabel type?
http://my.safaribooksonline.com/book/databases/hadoop/9780596521974/serialization/id3548156
Thanks for your help
Let say i have a CompositeKey that represents a pair of (String stockSymbol, long timestamp).
We can do a primary grouping pass on the stockSymbol field to get all of the data of one type together, and then our "secondary sort" during the shuffle phase uses the timestamp long member to sort the timeseries points so that they arrive at the reducer partitioned and in sorted order.
public class CompositeKey implements WritableComparable<CompositeKey> {
// natural key is (stockSymbol)
// composite key is a pair (stockSymbol, timestamp)
private String stockSymbol;
private long timestamp;
......//Getter setter omiited for clarity here
#Override
public void readFields(DataInput in) throws IOException {
this.stockSymbol = in.readUTF();
this.timestamp = in.readLong();
}
#Override
public void write(DataOutput out) throws IOException {
out.writeUTF(this.stockSymbol);
out.writeLong(this.timestamp);
}
#Override
public int compareTo(CompositeKey other) {
if (this.stockSymbol.compareTo(other.stockSymbol) != 0) {
return this.stockSymbol.compareTo(other.stockSymbol);
}
else if (this.timestamp != other.timestamp) {
return timestamp < other.timestamp ? -1 : 1;
}
else {
return 0;
}
}
Now the CompositeKey comparator would be:
public class CompositeKeyComparator extends WritableComparator {
protected CompositeKeyComparator() {
super(CompositeKey.class, true);
}
#Override
public int compare(WritableComparable wc1, WritableComparable wc2) {
CompositeKey ck1 = (CompositeKey) wc1;
CompositeKey ck2 = (CompositeKey) wc2;
int comparison = ck1.getStockSymbol().compareTo(ck2.getStockSymbol());
if (comparison == 0) {
// stock symbols are equal here
if (ck1.getTimestamp() == ck2.getTimestamp()) {
return 0;
}
else if (ck1.getTimestamp() < ck2.getTimestamp()) {
return -1;
}
else {
return 1;
}
}
else {
return comparison;
}
}
}
Are you asking about way to compare LongWritable type provided by hadoop ?
If yes, then the answer is to use compare() method. For more details, scroll down here.
The best way to correctly implement RawComparator is to extend WritableComparator and override compare() method. The WritableComparator is very good written, so you can easily understand it.
It is already implemented from what I see in the LongWritable class:
/** A Comparator optimized for LongWritable. */
public static class Comparator extends WritableComparator {
public Comparator() {
super(LongWritable.class);
}
public int compare(byte[] b1, int s1, int l1,
byte[] b2, int s2, int l2) {
long thisValue = readLong(b1, s1);
long thatValue = readLong(b2, s2);
return (thisValue<thatValue ? -1 : (thisValue==thatValue ? 0 : 1));
}
}
That byte comparision is the override of the RawComparator.

Resources