find the middle element of a stack

Pattern: Implementation

easy

Build the stack on a doubly linked list and keep a pointer to the middle node. Each push or pop changes the count by one, and the middle moves one step only when the count crosses an odd or even boundary. So findMiddle and deleteMiddle are O(1).

The problem

Build a MiddleStack with push(x), pop(), findMiddle() and deleteMiddle(), all O(1). With c items, the middle is item number ceil(c / 2) counting from the bottom (so with 4 items it is the 2nd). pop, findMiddle and deleteMiddle return -1 when the stack is empty; deleteMiddle returns the value it removed.

The linked GFG page asks for these four operations; the rule for an even count and the -1 are this guide's.

Think first

  • Can an array give O(1) deleteMiddle?
  • When the count goes from 4 to 5, does the middle change?
  • What links does a node need so that you can remove it in O(1)?

Hints

    Brute force, and why it fails

    Keep the stack in an array and index (c + 1) / 2 - 1 for findMiddle (O(1)), but deleteMiddle shifts items: O(n).

    The key insight

    Track the middle as the count changes. Push: if the count becomes odd, the middle moves up one. Pop: if the count becomes even, it moves down one. A doubly linked list makes both moves and the deletion O(1).

    Dry run

    10 
    21 
    32 
    43 
    54 
    count5
    mid3

    push 1, 2, 3, 4, 5. With count 5 the middle is item ceil(5 / 2) = 3rd from the bottom.

    Step 1 of 3

    The plan

    push(x):  link x on top; count += 1
              if count == 1: mid = x  elif count is odd: mid = mid.next
    pop():    unlink top; count -= 1
              if count == 0: mid = null  elif count is even: mid = mid.prev
    deleteMiddle(): unlink mid; count -= 1
              mid = (count even) ? old.prev : old.next
    

    Complexity

    Time
    O(1) per operation
    Space
    O(n)

    Each operation changes a few links and moves mid at most one step.

    Edge cases

    • Deleting the middle of a 1-item stack: the stack becomes empty.
    • Deleting the middle of a 2-item stack: the middle is the bottom item, and the top becomes the new middle.
    • Empty stack: -1 for every read.
    I've built my logic, show the code

    Java

    class MiddleStack {
        private static class Node {
            int val;
            Node prev, next;                        // prev is towards the bottom, next towards the top
            Node(int val) { this.val = val; }
        }
    
        private Node top = null, mid = null;
        private int count = 0;                      // mid is item number ceil(count / 2) from the bottom
    
        public void push(int x) {
            Node node = new Node(x);
            node.prev = top;
            if (top != null) top.next = node;
            top = node;
            count++;
            if (count == 1) mid = node;
            else if (count % 2 == 1) mid = mid.next;   // the middle moves up on every odd count
        }
    
        public int pop() {
            if (top == null) return -1;
            int x = top.val;
            top = top.prev;
            if (top != null) top.next = null;
            count--;
            if (count == 0) mid = null;
            else if (count % 2 == 0) mid = mid.prev;   // the middle moves down when the count becomes even
            return x;
        }
    
        public int findMiddle() {
            return mid == null ? -1 : mid.val;
        }
    
        public int deleteMiddle() {
            if (mid == null) return -1;
            Node gone = mid;
            if (gone.prev != null) gone.prev.next = gone.next;
            if (gone.next != null) gone.next.prev = gone.prev;
            else top = gone.prev;                   // it was also the top
            count--;
            mid = count == 0 ? null : (count % 2 == 0 ? gone.prev : gone.next);
            return gone.val;
        }
    }

    C++

    class MiddleStack {
    public:
        struct Node {
            int val;
            Node* prev;                             // towards the bottom
            Node* next;                             // towards the top
            Node(int v) : val(v), prev(NULL), next(NULL) {}
        };
    
        Node* top = NULL;
        Node* mid = NULL;
        int count = 0;                              // mid is item number ceil(count / 2) from the bottom
    
        void push(int x) {
            Node* node = new Node(x);
            node->prev = top;
            if (top != NULL) top->next = node;
            top = node;
            count++;
            if (count == 1) mid = node;
            else if (count % 2 == 1) mid = mid->next;   // the middle moves up on every odd count
        }
    
        int pop() {
            if (top == NULL) return -1;
            Node* old = top;
            int x = old->val;
            top = old->prev;
            if (top != NULL) top->next = NULL;
            count--;
            if (count == 0) mid = NULL;
            else if (count % 2 == 0) mid = mid->prev;   // the middle moves down when the count becomes even
            delete old;
            return x;
        }
    
        int findMiddle() {
            return mid == NULL ? -1 : mid->val;
        }
    
        int deleteMiddle() {
            if (mid == NULL) return -1;
            Node* gone = mid;
            if (gone->prev != NULL) gone->prev->next = gone->next;
            if (gone->next != NULL) gone->next->prev = gone->prev;
            else top = gone->prev;                  // it was also the top
            count--;
            mid = count == 0 ? NULL : (count % 2 == 0 ? gone->prev : gone->next);
            int x = gone->val;
            delete gone;
            return x;
        }
    };

    Python

    from lib import DNode
    
    
    class MiddleStack:
        def __init__(self):
            self.top = self.mid = None
            self.count = 0                          # mid is item number ceil(count / 2) from the bottom
    
        def push(self, x: int) -> None:
            node = DNode(x, self.top, None)         # prev is towards the bottom, next towards the top
            if self.top is not None:
                self.top.next = node
            self.top = node
            self.count += 1
            if self.count == 1:
                self.mid = node
            elif self.count % 2 == 1:
                self.mid = self.mid.next            # the middle moves up on every odd count
    
        def pop(self) -> int:
            if self.top is None:
                return -1
            x = self.top.val
            self.top = self.top.prev
            if self.top is not None:
                self.top.next = None
            self.count -= 1
            if self.count == 0:
                self.mid = None
            elif self.count % 2 == 0:
                self.mid = self.mid.prev            # the middle moves down when the count becomes even
            return x
    
        def findMiddle(self) -> int:
            return -1 if self.mid is None else self.mid.val
    
        def deleteMiddle(self) -> int:
            if self.mid is None:
                return -1
            gone = self.mid
            if gone.prev is not None:
                gone.prev.next = gone.next
            if gone.next is not None:
                gone.next.prev = gone.prev
            else:
                self.top = gone.prev                # it was also the top
            self.count -= 1
            if self.count == 0:
                self.mid = None
            else:
                self.mid = gone.prev if self.count % 2 == 0 else gone.next
            return gone.val

    Common mistakes

    • Moving mid before updating count, so the parity test reads the old count.
    • Forgetting to update top when the middle node was also the top.

    Similar problems