Problem overview
A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO (last in, first out), like a pile of plates. The lesson asks for a class MyStack that stores whole numbers in a private array, data: number[], and offers four operations:
push(value: number): voidputs a value on top and returns nothing.pop(): numberremoves the top value and returns it.peek(): numberreturns the top value and leaves it in place.size(): numberreturns how many values the stack holds.
The driver pushes 10, 20 and 30, then peeks, reads the size, pops three times with a size check in between, and finally pushes 7 to show that the stack keeps working after it has been emptied. The lesson's tests never pop or peek an empty stack.
Following the output: after the three pushes the top is 30 and the size is 3. The first pop returns 30 and leaves a size of 2. The next two pops return 20 and 10, in reverse order of pushing, and the size is 0. After push(7), the top is 7 and the size is 1.
Approach: the end of the array is the top of the stack
An array already has what a stack needs. Its push adds at the end and its pop removes from the end, and both are fast, because nothing else has to move. If the end of the array is the top of the stack, the last value pushed is always the last element, which is exactly the LIFO rule. Putting the top at the front instead would force every element to shift on each operation.
The class wraps the array and hides it. The field is declared private, so code outside the class can use only the four methods. That is the point of building MyStack at all: the rest of the program doesn't know whether the values live in an array, and the class could change its storage later without breaking the callers.
Step by step
- Declare the class
MyStackand write its closing brace at once. The driver'snew MyStack()builds an object from it. - Declare the field
private data: number[] = [];. The initializer gives every new stack its own empty array, andprivatekeeps it away from outside code. - Start
pushwith anumberparameter namedvalueand the return typevoid. - Call the array's own
pushinside it, so the value lands at the end. - Start
pop, with no parameters and the return typenumber. - Return what the array's
popremoves. The lesson adds a!after the call, a non-null assertion that tells the compiler the value is notundefined. - Start
peek, again returning anumber. - Return the last element,
this.data[this.data.length - 1]. With three values the last index is 2. Reading by index removes nothing. - Start
size, returning anumber. - Return
this.data.length: one array element per stored value.
The solution in TypeScript
class MyStack {
private data: number[] = [];
push(value: number): void {
this.data.push(value);
}
pop(): number {
return this.data.pop()!;
}
peek(): number {
return this.data[this.data.length - 1];
}
size(): number {
return this.data.length;
}
}
const s = new MyStack();
s.push(10);
s.push(20);
s.push(30);
console.log("Top: " + s.peek());
console.log("Size: " + s.size());
console.log("Pop: " + s.pop());
console.log("Size: " + s.size());
console.log("Pop: " + s.pop());
console.log("Pop: " + s.pop());
console.log("Empty size: " + s.size());
s.push(7);
console.log("Top: " + s.peek());
console.log("Size: " + s.size());
It prints:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
TypeScript details worth knowing
- Two different
pushandpop. InsideMyStack.push,this.data.push(value)calls the array's method. Both share a name but belong to different objects:this.datais an array, andthisis the stack. - The
!operator. An array'spopis typed to returnnumber | undefinedwhen the compiler runs in strict mode, because an empty array givesundefined. The!removesundefinedfrom the type so that it fits the return typenumber. The lessons compile with--strict false, where the type ofpop()is alreadynumberand the!changes nothing. Under strict checking,const v: number = a.pop();is reported asType 'number | undefined' is not assignable to type 'number'. Either way,!is erased when the code compiles: it checks nothing at run time. privateis a compile-time rule. Writingw.dataoutside the class makes the compiler reportProperty 'data' is private and only accessible within class 'MyStack'. The compiled JavaScript still runs, and afterw.push(5)the expressionw.dataevaluates to[ 5 ]. Use#dataif you need privacy at run time.- Indexing past the end is not an error. A JavaScript array read at a missing index gives
undefined. That is whypeekneeds no special case to compile, and why it misbehaves quietly on an empty stack. - Field initializers.
= []runs once per object, so two stacks never share an array.
Complexity
Every operation is O(1) time: push and pop work at the end of the array, peek reads one index, and size reads the stored length. (Array push is amortized O(1): the engine occasionally grows its storage, but the average cost per call stays constant.) The stack holds one array element per value, so the space is O(n) for n values.
Edge cases and common mistakes
- Empty stack. The lesson's tests never pop or peek an empty stack. With this solution, on an empty stack
pop()andpeek()both returnundefinedat run time even though their declared type isnumber, andsize()is 0. If you want an error instead, checkthis.data.length === 0first and throw. - Using
shiftor index 0 as the top. The array'sshiftandunshiftwork at the front and move every element along. Keep the top at the end. - Peeking with
pop.peekmust not remove the value: afterpeek()the size is unchanged. Afterpop()it drops by one. - Off by one in
peek.this.data[this.data.length]is one past the last element and givesundefined. The last index islength - 1. - Sharing one array. Declaring the array outside the class, or reusing one object, would make separate stacks see each other's values. Declare it as a field with an initializer.
- Using the field without
this.. Inside a method,dataalone is not defined. It isthis.data. - Reuse after emptying. The stack must keep working after the last pop. Because the array is just empty,
push(7)afterwards makes the top 7 and the size 1.
Testing
- Push 1 and 2:
peek()returns 2 andsize()returns 2. - Then
pop()returns 2,peek()returns 1 andsize()returns 1. - A new stack has
size()0. - Push 10, 20, 30 and pop three times: the values come out as 30, 20, 10.
