int A[MAX_SIZE]; // create a integer array of maximum expected size for the stack
int *A = (int *) malloc(1000 * sizeof(int)); // or malloc it.
int size = 0; // Also keep track of the current size
A[size++] = newElement; // Put the new Element on the end of the array. O(1).
size--; // Simply reduce the size. O(1)
return (size == 0); // Check if size is 0. O(1)
return size; // 'size' tracks the current size of the stack.
A[size - 1]
C style array stack works in C++ as well. However, C++ provides a library implementation of stack as well.
stack<int> A; // declares an empty stack.
A.push(newElement); // Pushes a new element. O(1)
A.pop(); // O(1) pop
A.empty() // O(1)
A.size(); // O(1)
A.top(); // O(1). Gives the top element.
Java has a stack similar to C++.
Stack<Integer> A = new Stack<Integer>();
A.push(new Integer(newElement)); // Pushes a new element. O(1)
A.pop(); // O(1) pop
A.empty() // O(1)
A.size(); // O(1)
A.peek(); // O(1). Gives the top element.
We can use list as a stack in python. Very similar to how we do it in C.
A = [] # declares an empty stack. O(1)
A.append(newElement) # Put the new Element on the end of the array. O(1).
A.pop() # removes the last element. O(1)
return (len(A) == 0); # Check if size is 0. O(1)
return len(A); # O(1)
A[-1] # O(1)
Walkthrough examples :
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Balanced Parantheses! | 200 |
|
15:59 | |
Simplify Directory Path | 250 |
|
54:00 | |
Redundant Braces | 300 |
|
42:41 | |
Min Stack | 400 |
|
43:31 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
MAXSPPROD | 200 |
|
88:22 | |
Nearest Smaller Element | 350 |
|
41:37 | |
Largest Rectangle in Histogram | 450 |
|
65:52 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Hotel Service | 200 |
|
48:48 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
First non-repeating character in a stream of characters | 200 |
|
58:46 | |
Sliding Window Maximum | 450 |
|
69:38 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
Evaluate Expression | 400 |
|
32:46 | |
Rain Water Trapped | 400 |
|
59:06 |