Electronics & Telecommunication (University) is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Data structures and abstract data types

What an Abstract Data Type (ADT) is, how it differs from concrete data structures, common ADTs (stack, queue, list, map, set, priority queue), how to specify and implement ADTs, representation invariants, interface vs implementation, and exam-level examples including two runnable C++ programs.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Abstract Data Types (ADTs) let engineers specify what operations a data container supports and what those operations mean, without fixing how the data is stored. This separation (specification vs implementation) makes code modular, reusable, and easier to test — used everywhere from compilers and databases to network stacks and UI code.

Key ideas

  • Abstract Data Type (ADT): a mathematical model that defines a set of values and a set of operations on those values, together with the semantics (what each operation does). An ADT is described by its interface and axioms (rules about how operations behave). It does not describe memory layout or algorithms. Example ADTs: Stack, Queue, List, Map (Dictionary), Set, Priority Queue, Graph, Tree.
  • Interface: the names, arguments, return types, and documented behaviour (preconditions and postconditions) of operations an ADT provides.
  • Implementation (representation): the concrete choice of data structure(s) and algorithms used to realize the ADT. A single ADT can have multiple implementations. Example: Stack implemented with an array or with a linked list. Know typical cost trade-offs: for stacks, array- and linked-list-based implementations support push/pop/top in O(1) time; arrays use contiguous memory and may have fixed capacity or require resizing, while linked lists use extra pointer space and incur allocation overhead.
  • Representation invariant: a statement or predicate that must always be true for the chosen representation (for example, for an array-based stack, 0 ≤ topIndex < capacity when non-empty, or topIndex == -1 when empty). Implementations must maintain these invariants after each operation.
  • Abstract operations and axioms (example: Stack ADT)
    • Values: sequences of elements (or an ordered collection where only one end is used).
    • Operations: create() (empty stack), push(x), pop(), top() / peek(), isEmpty().
    • Axioms (assume stack S is created empty):
      • isEmpty(create()) = true
      • After push(S, x), isEmpty(S) = false
      • If push(S, x) is followed by top(S), top returns x (assuming no intervening pop).
      • If push(S, x) followed by pop(S), the resulting stack is equivalent to original S. These axioms define observable behaviour in a way exam answers expect. In the abstract model, operations like push are total (no overflow); capacity/overflow is an implementation concern.
  • Preconditions and postconditions: describe when an operation is valid and what it guarantees; e.g., pop() has precondition isEmpty() == false and postcondition the size decreases by 1 and top changes accordingly.
  • Encapsulation: the implementation details (representation) must be hidden behind the interface so users depend only on the behaviour. This is crucial for changing implementations without breaking client code.
  • Mapping spec → implementation (what universities ask for): show the interface, choose a representation, state the representation invariant, implement each operation and prove it preserves the invariant and satisfies the ADT axioms. Exams often require you to show pre/postconditions and a short proof per operation. Also define an abstraction function (AF) from representations to abstract states, and use AF + the invariant to argue correctness.
  • Diagram to draw for exam answers (describe exactly):
    • Draw a box labelled "Stack ADT" containing a short list of operations: create(), push(x), pop(), top(), isEmpty().
    • To the right draw two boxes, one labelled "Array implementation" and one labelled "Linked-list implementation". Draw arrows from the Stack ADT box to each implementation box. Inside the array box draw an array with indices 0..capacity-1 and an arrow pointing to the top index. Inside the linked-list box draw nodes with data and next pointers, and an arrow pointing at the head/top node. Label the representation invariant for each.

Formulas

For a programming topic, remember these C++ syntaxes and small templates to state an ADT and implementation: class StackInterface { public: virtual void push(int x) = 0; virtual void pop() = 0; virtual int top() const = 0; virtual bool isEmpty() const = 0; virtual ~StackInterface() {} }; — interface (pure virtual class) for a stack class ArrayStack : public StackInterface { private: int *A; int capacity; int topIndex; public: ArrayStack(int cap); ~ArrayStack(); void push(int x) override; void pop() override; int top() const override; bool isEmpty() const override; }; — skeleton for array implementation // Representation invariant (comment): -1 <= topIndex < capacity; when topIndex == -1 stack is empty. // Pre/post style: // pre: !isEmpty() before pop/top; // post: size decreases by 1 for pop()

Worked examples

  1. Theory model answer (typical long question): Question: Define an Abstract Data Type (ADT). Describe the difference between an ADT and a data structure. Give an example mapping the Stack ADT to two implementations and show representation invariants. Model answer:
  • Definition: An Abstract Data Type (ADT) is a mathematical model that specifies a set of values and operations on those values, together with the semantics of the operations (axioms) but without specifying an implementation.
  • Difference: A data structure is a concrete implementation in a programming language that stores data and provides algorithms for the ADT operations. The ADT answers "what operations and what behaviour"; the data structure answers "how to store and implement them".
  • Example (Stack): Operations: create(), push(x), pop(), top(), isEmpty(). Two implementations:
    • Array-based: store elements in array A[0..capacity-1] and integer topIndex; invariant topIndex == -1 when empty; otherwise 0 ≤ topIndex < capacity. push(x) checks capacity, does A[++topIndex] = x. pop() does topIndex-- after precondition that topIndex != -1.
    • Linked-list-based: store nodes {value, next} and pointer head; invariant head == nullptr when empty. push(x) allocates new node and sets node->next = head; head = node;. pop() removes head and sets head = head->next, and deallocates the removed node.
  • For each operation show pre/postconditions and a short proof that the operation preserves the invariant. (As shown above.) This is a full-marks style answer: definition, clear difference, two implementations, invariants, code-like pseudo-steps for operations.
  1. Program 1 — Array-based Stack ADT (C++) Complete program that reads commands and prints outputs. Compile with a standard C++ compiler (g++).
#include <bits/stdc++.h>
using namespace std;
class ArrayStack {
  int *A; int capacity; int topIndex;
public:
  ArrayStack(int cap=100) { capacity = cap; A = new int[capacity]; topIndex = -1; }
  ~ArrayStack() { delete[] A; }
  void push(int x) { if (topIndex+1==capacity) { cout << "Error: stack overflow\n"; return; } A[++topIndex] = x; cout << "Pushed " << x << '\n'; }
  void pop() { if (topIndex==-1) { cout << "Error: stack underflow\n"; return; } cout << "Popped " << A[topIndex--] << '\n'; }
  void top() const { if (topIndex==-1) { cout << "Error: empty\n"; return; } cout << "Top is " << A[topIndex] << '\n'; }
  void size() const { cout << "Size is " << (topIndex+1) << '\n'; }
  void isEmpty() const { cout << "Empty: " << (topIndex==-1?"true":"false") << '\n'; }
};
int main(){
  ios::sync_with_stdio(false); cin.tie(nullptr);
  int n; if (!(cin>>n)) return 0;
  ArrayStack st(100);
  for(int i=0;i<n;i++){
    string cmd; cin>>cmd;
    if(cmd=="push"){ int x; cin>>x; st.push(x); }
    else if(cmd=="pop") st.pop();
    else if(cmd=="top") st.top();
    else if(cmd=="size") st.size();
    else if(cmd=="isempty") st.isEmpty();
    else { cout<<"Unknown command\n"; }
  }
}

Sample input:

7
push 10
push 20
top
size
pop
top
isempty

Exact output:

Pushed 10
Pushed 20
Top is 20
Size is 2
Popped 20
Top is 10
Empty: false
  1. Program 2 — Circular-array Queue ADT (C++)
#include <bits/stdc++.h>
using namespace std;
class CircularQueue {
  int *A, capacity, frontIndex, count;
public:
  CircularQueue(int cap=100){ capacity=cap; A=new int[capacity]; frontIndex=0; count=0; }
  ~CircularQueue(){ delete[] A; }
  void enqueue(int x){ if(count==capacity){ cout<<"Error: queue full\n"; return;} int idx=(frontIndex+count)%capacity; A[idx]=x; count++; cout<<"Enqueued "<<x<<'\n'; }
  void dequeue(){ if(count==0){ cout<<"Error: queue empty\n"; return;} cout<<"Dequeued "<<A[frontIndex]<<'\n'; frontIndex=(frontIndex+1)%capacity; count--; }
  void front() const{ if(count==0){ cout<<"Error: empty\n"; return;} cout<<"Front is "<<A[frontIndex]<<'\n'; }
  void size() const{ cout<<"Size is "<<count<<'\n'; }
  void isEmpty() const{ cout<<"Empty: "<<(count==0?"true":"false")<<'\n'; }
};
int main(){ ios::sync_with_stdio(false); cin.tie(nullptr);
  int n; if(!(cin>>n)) return 0; CircularQueue q(100);
  for(int i=0;i<n;i++){ string cmd; cin>>cmd;
    if(cmd=="enqueue"){ int x; cin>>x; q.enqueue(x); }
    else if(cmd=="dequeue") q.dequeue();
    else if(cmd=="front") q.front();
    else if(cmd=="size") q.size();
    else if(cmd=="isempty") q.isEmpty();
    else cout<<"Unknown command\n";
  }
}

Sample input:

6
enqueue 5
enqueue 7
front
size
dequeue
isempty

Exact output:

Enqueued 5
Enqueued 7
Front is 5
Size is 2
Dequeued 5
Empty: false

Common mistakes

  • Confusing ADT axioms with implementation steps. Axioms describe observable behaviour (e.g., push then pop returns original) not how to move indices or pointers.
  • Not writing clear preconditions/postconditions for operations like pop() or top(). If the operation is undefined when empty, say so.
  • For code answers, off-by-one mistakes in array indexing (topIndex initialization and update) or incorrect wrap-around arithmetic for circular queues.
  • Forgetting to define the abstraction function (AF) that maps the representation to the abstract state when giving a proof-style answer.
  • Omitting a brief time-complexity analysis of operations for the chosen implementation.

For your exam

Typical question types:

  • Definitions: define ADT, data structure, interface, implementation, representation invariant.
  • Short notes: compare ADT vs data structure, advantages of encapsulation, list common ADTs and their primary operations.
  • Derivations/proofs: given an implementation, prove each operation preserves representation invariant and satisfies an axiom.
  • Diagrams: draw ADT box and implementations with arrows and label invariants and key fields (index/pointer) — follow the exact diagram description above.
  • Programs: implement an ADT in C++ or pseudocode; write pre/postconditions and check edge cases (overflow/underflow). A full-marks answer includes: clear definitions, explicit interface, chosen representation with invariant, operation implementations with pre/postconditions, and a short correctness argument. Include a brief time-complexity analysis of each operation.

Quick check

  1. What is the difference between an ADT and a data structure?
  2. State the representation invariant for an array-based stack implemented with topIndex initialized to -1.
  3. Name two operations that every queue ADT should provide. Answers: 1. ADT = abstract specification of values and operations; data structure = concrete implementation storing data and algorithms. 2. -1 <= topIndex < capacity and topIndex == -1 means empty. 3. enqueue(x) and dequeue() (also front/peek and isEmpty/size).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?