Skip to main content


What is a Stack?
A Stack ADT is an ordered list in which insertion and deletion are done at the top end of the list.
A stack follows LIFO(Last In First Out) Principle i.e, the last element inserted is the first one to be deleted.

Why do we need Stack?
Well, in many algorithms you want to add objects to a temporary list at some point and then pull them off this list again at a later time. Often the order in which you add and remove these objects matters.

Applications of Stack
  • Balancing of symbols
  • Infix-to-Postfix conversion
  • Evaluation of postfix expression
  • Implementing function calls(Recursive)
  • Forward and Backward feature in a browser.
  • Redo & Undo sequence in a text editor.
  • Matching tags in HTML & XML.
  • Used in other algorithms like Tree traversal, Tower of Hanoi, Stock span, N Queens, etc.

Stack Operations
Main stack operations
Push: Inserts data onto stack
Pop: Removes and returns the last inserted element from the stack.

Auxiliary stack operations
Top: Returns the last element without removing it.
isEmpty: Indicates whether any elements are stored in a stack or not.
isFull: Indicates whether the stack is full or not.

  • Array
  • Linked list
1. Stack using Array

public struct Stack<T> {
  /// Datastructure consisting of a generic item.
  fileprivate var array = [T]()

  /// The number of items in the stack.
  public var count: Int {
    return array.count

  /// Verifies if the stack is empty.
  public var isEmpty: Bool {
    return array.isEmpty

     Pushes an item to the top of the stack.
     - Parameter element: The item being pushed.
  public mutating func push(_ element: T) {

     Removes and returns the item at the top of the stack.
     - Returns: The item at the top of the stack.
  public mutating func pop() -> T? {
    return array.popLast()

  /// Returns the item at the top of the stack.
  public var top: T? {
    return array.last
Space Complexity for n push operations O(n)
Time Complexity of Push() O(1)
Time Complexity of Pop() O(1)
Time Complexity of isEmpty() O(1)
Time Complexity of isFull() O(1)
Time Complexity of top() O(1) // Array.last = O(1)
Time Complexity of size()O(1) // Array.count = O(1)

2. Stack using LinkedList

public final class LinkedStack<T>{
    /// Linked List's Node Class De claration
    public class LinkedListNode<T> {
        var value: T
        var next: LinkedListNode?
        public init(value: T) {
            self.value = value
    /// Typealiasing the node class to increase readability of code
    public typealias Node = LinkedListNode<T>
    /// The head of the Linked List
    private(set) var head: Node?
    /// Computed property to iterate through the linked list and return the last node in the list (if any)
    public var top: T? {
        guard let node = head else {
            return nil
        return node.value
    /// Computed property to check if the linked list is empty
    public var isEmpty: Bool {
        return head == nil
    /// Computed property to iterate through the linked list and return the total number of nodes
    public var count: Int {
        guard var node = head else {
            return 0
        var count = 1
        while let next = {
            node = next
            count += 1
        return count
    /// Append a value to the end of the list
    /// - Parameter value: The data value to be appended
    public func push(_ value: T) {
        let newNode = Node(value: value) = head
        head = newNode
    /// remove last element from the list and return it's value
    @discardableResult public func pop() -> T {
        var current = head
        defer {
            current = nil
        head = current?.next
        return current!.value
    /// Function to remove all nodes/value from the list
    public func deleteStack() {
        head = nil

Space Complexity for n push operationsO(n)
Time Complexity of Push() O(1)
Time Complexity of Pop() O(1)
Time Complexity of isEmpty() O(1)
Time Complexity of top()O(1)
Time Complexity of deleteStack() O(1)


Popular posts from this blog

Design Patterns in Swift

What is a Design pattern?
A design pattern is a general solution to a real-world problem that can be re-used.
Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.
They are templates designed to help us write efficient code which is easy to understand, also can be re-used.
It is not a finished design that can be transformed directly into source or machine code.

Why do we need Design patterns?
Saves Time: Design patterns can speed up the development process by providing tested, proven development paradigmsFuture bugs: Effective design pattern can solve issues that may not become visible until later in the implementation, which helps while designing software.Re-use: Reusing design patterns helps to prevent subtle issues that can cause major problems.Code Readability: Improves code readability for coders and architects familiar with the patterns. Best practices: Design patterns teaches us some of the best pra…

UILabel text animation as in UIButton click

Animating UILabel textcolor is not easy as it seems, normal animation won't work on this property. The below code snippet animates the UILabel textcolor as in button click.
Change the duration and UIViewAnimationOptions to play with it. extensionUILabel{ func flashLabel() { func animate(duration:Double,alpha:CGFloat,completion:(()->())?){ UIView.transition(with: self, duration: duration, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { self.textColor = self.textColor?.withAlphaComponent(alpha) }) { _ in completion?() } } animate(duration: 0.1, alpha: 0) { animate(duration: 0.3, alpha: 1, completion: nil) } } } Happy coding...

Stack Problem - Balancing of Symbols

Stack Problem - Balancing of Symbols
Problem: Given an expression string exp , write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.

Input: exp = “[()]{}{[()()]()}”
Output: Balanced Input: exp = “[(])”
Output: Not Balanced
Create a stack.while ( end of input is not reached ) {If the character read is not a symbol to be balanced, ignore it.If the character is an opening delimiter like ( , {  or [ , PUSH it into the stack.If it is a closing symbol like ) , } , ] , then if the stack is empty report an error, otherwise POP the stack.If the symbol POP-ed is not the corresponding delimiter, report an error.At the end of the input, if the stack is not empty report an error.Implementation :
func balancingOfSymbols(string:String)->Bool{ guard string.count > 0else { return false } let symbols:[Character:Character] = ["{":"}","[":"]","(":")",] v…