Skip to content
This repository has been archived by the owner on Oct 20, 2023. It is now read-only.

Latest commit

 

History

History
737 lines (587 loc) · 21 KB

Lectures.md

File metadata and controls

737 lines (587 loc) · 21 KB

1. Linked List

Limitations of arrays.

  • size is static and bounded, dynamic resizing not possible
  • insert requires shifting out subsequent elements to right
  • delete requires shifting out subsequent elements to left

What is a linked list? .

  • A data structure that holds a pointer head to a chained link of nodes.
  • Each node contains 2 parts:
    1. data: holds the data
    2. next: holds link to the next node

Visualizing linked list.

Linked list

Properties of linked list.

  • No random access.
  • To reach a node, always start from the head and traverse.

Operations on linked list

  • insert
  • delete
  • search

Problems based on linked list properties .

  • Given a sequence of operations, print the state after each operation

Implementing linked list.

class Node {  
  int data;  
  Node next;  
}
class LinkedList {  
  Node head;  
  
  void insert(int pos, int key);
  void insert(int key);
  boolean delete(int pos);
  int search(int key); // returns position  
  int size();  
  void insertFirst(int key);
  void deleteFirst();
}

For a step-by-step implementation of LinkedList, please refer to Linked List implementation step-by-step.

LinkedList in Collections

Problems from Leetcode

  1. In a single traversal find the middle element/position
  2. Design linked list
  3. Merge two sorted lists into one
  4. Rotate a linked list by k positions
  5. Remove duplicates from a sorted list
  6. Partition list based on > and <= x
  7. Remove linked list elements
  8. Intersection of two linked lists
  9. Reverse a linked list
  10. Check if a linked list has a cycle

ArrayList in Collections

When to use LinkedList or ArrayList?

  • When inserts/deletes are more, use LinkedList
  • Otherwise ArrayList

2. Circular Linked List

What is it?

  • Last node links back to first node

Visualization

Circular Linked list

Properties

  • Can reach the first node from the last node

Operations

  • insert
  • delete
  • search
  • Rotate right k times
  • Rotate left = rotate right size - k times

Implementation changes needed

  • insert and delete needs modification to set the next back to head
  • search needs modification to stop traversal as soon as next points to head

3. Doubly Linked List

What is it?

  • Contains pointer to first node head
  • Each node contains 3 parts:
    1. data: holds the data
    2. prev: holds pointer to previous node
    3. next: holds pointer to next node

Visualization

Doubly Linked list

Properties

  • Can traverse in both left and right directions

Operations

  • insert
  • delete
  • search

Implementation changes needed

  • insert and delete needs modification to set both prev and next

For the implementation of doubly linked list, visit Doubly Linked List.


4. Stack

What is it?

  • A data structure that holds pointer (top) to a chained link of nodes
  • A new node is pushed onto the stack, and it becomes the new top
  • Delete pops the top node from the stack, the below node becomes the top
  • It can be seen as restricted linked list that supports insert first (last) and delete first (last)

Visualization

Stack

Properties

  • LIFO: Last-In-First-Out
  • Insert and delete at one end only

Operations

  • push
  • pop
  • peek

Implementation

class Node {  
  int data;  
  Node next;  
}
class Stack {  
  Node top;  
  
  void push(int key);  
  int pop();   
  int peek();  
  int size();  
}

For the implementation of stack and its applications, please refer to Stack and its applications.

Stack in Collections

Problems from Leetcode

  1. Reverse
  2. Check palindrome
  3. Balanced parantheses
  4. Postfix evaluation
  5. Basic calculator - Infix to postfix + postfix evaluation
  6. Min stack
  7. Remove k digits
  8. Decode string
  9. Backspace string compare
  10. Score of parantheses

5. Queue

What is it?

  • A data structure that holds pointers (front, rear) to the first and last nodes of chained link of nodes
  • A new node is enqueued to the rear
  • Node is removed from the front
  • It can be seen as restricted linked list that supports insert last and delete first

Visualization

Queue

Properties

  • FIFO: First-In-First-Out
  • Insert at one end and remove from the other end

Operations

  • enqueue
  • dequeue
  • peek

Implementation

class Node {  
  int data;  
  Node next;  
 
  Node(int d);  
  int getData(); 
  Node getNext();
}
class Queue {  
  Node front;  
  Node rear;
  
  void enqueue(int key);  
  int dequeue();   
  int peek();  
  int size();  
}

For the implementation of queue in its different forms, please refer to Queue implementation.

ArrayDeque in Collections

Problems from Leetcode

  1. Task scheduler
  2. Stack using queue
  3. Queue using stack
  4. Circular Queue
  5. Circular Deque
  6. Number of recent calls

6. Binary tree

What is it?

  • A non-linear representation of nodes where each node links to 0, 1 or 2 child nodes
  • Child nodes are referred to as left and right
  • Topmost node is called root

Visualization

Binary Tree

Properties

  • Access to any node always starts with the root

Traversals

  • Level-order: Level-by-level from top to bottom, at each level left to right
    • 25 48 16 11 37 64 76 83 51 93
  • Preorder: visit(node), preorder(left), preorder(right)
    • 25 48 11 76 83 37 51 16 64 93
  • Inorder: inorder(left), visit(node), inorder(right)
    • 76 11 83 48 37 51 25 16 93 64
  • Postorder: postorder(left), postorder(right), visit(node)
    • 76 83 11 51 37 48 93 64 16 25

Operations

  • insert
  • delete
  • search
  • preorder
  • inorder
  • postorder

Implementation

class Node {  
  int data;  
  Node left;  
  Node right;  
  
  Node(int d);  
  boolean search(int key);  
  boolean insert(int key);  
  boolean delete(int key);  
  void preorder();  
  void inorder();  
  void postorder();  
}
class BinaryTree {  
  Node root;  
 
  boolean search(int key) { root.search(key); }   
  boolean insert(int key) { root.insert(key); }  // Implementation depends on the type of binary tree
  boolean delete(int key) { root.delete(key); }  // Implementation depends on the type of binary tree
  void preorder() { root.preorder(); }  
  void inorder() { root.inorder(); }  
  void postorder() { root.postorder(); }  
}

Applications

  • Expression tree
  • Huffman encoding

Problems from Leetcode

  1. Inorder traversal
  2. Preorder traversal
  3. Level order traversal
  4. Same tree
  5. Symmetric tree
  6. Max depth
  7. Diameter
  8. Lowest common ancestor
  9. Longest univalue path
  10. Construct BT from preorder & inorder

7. Binary Heap

Types

  • Min heap
  • Max heap

What is min heap?

  • A binary tree in which each node's value is less than that of its left and right nodes Min Heap

What is max heap?

  • A binary tree in which each node's value is greater than that of its left and right nodes

Max Heap

Properties

  • Access starts from the root
  • Min Heap property: parent < left, right
    • Min element at the root
  • Max Heap property: parent > left, right
    • Max element at the root
  • No constraints between left and right
  • Can be implemented as array for fast access

Traversal

  • Level-order (array implementation suits this)
  • parent(i) = (i-1)/2
  • left(i) = 2i + 1
  • right(i) = 2i + 2

Heap-array correspondence

Operations

  • insert
  • getMin (or getMax)

Implementation

class MinHeap {
  int[] arr;
  int root;
  int size;
  
  MinHeap() { arr = int[100]; root = 0; size = 0; }
  int getParent(int i) { return (i-1)/2; }
  int getLeft(int i) { return 2*i + 1; }
  int getRight(int i) { return 2*i + 2; }
  void buildHeap();
  void insert(int key);
  void fixHeap();
  int getMin();
}

For a step-by-step implementation of MinHeap (a.k.a PriorityQueue), please refer to Min Heap implementation step-by-step.

Applications

  • Heap sort
  • Implement priority queue

PriorityQueue in Collections

Problems from Leetcode

  1. Kth largest element in an array
  2. Top K frequent elements
  3. Sort chars by frequency
  4. Split array into consecutive subsequences
  5. Top k frequent words
  6. Last stone weight
  7. K closest points to origin
  8. Distant bar codes
  9. Kth largest element in a stream
  10. Network delay time

8. Binary Search Tree

What is it?

  • A binary tree in which a node's value is greater than its left and smaller than its right

Why is it needed?

  • To search faster
  • It takes O(n) time to search in a linked list
  • BST provides a way to reduce search time to O(logn)
    • Not always though!!!

Visualization

Binary Search Tree

Properties

  • Access starts from the root
  • left < data < right
  • Inorder traversal results in sorted sequence

Traversal

  • Usually inorder to retrieve sorted sequence
  • Other traversals are also common

Operations

  • insert
  • delete
  • search
  • preorder, inorder, postorder

Implementation

class Node {  
  int data;  
  Node left;  
  Node right;  
  
  Node(int d);  
  boolean search(int key);  
  boolean insert(int key);  
  boolean delete(int key);  
  void preorder();  
  void inorder();  
  void postorder();  
}
class BST {  
  Node root;  
 
  boolean search(int key) { root.search(key); }  
  boolean insert(int key) { root.insert(key); }  
  boolean delete(int key) { root.delete(key); }  
  void preorder() {root. preorder(); }  
  void inorder() { root.inorder(); }  
  void postorder() { root.postorder(); }  
}

For a step-by-step implementation of LinkedList, please refer to Binary Search Tree implementation.

Additional Information

  • search: traverse recursively taking appropriate path at each level until node containing search element is found or leaf node is reached
  • insert: traverse recursively taking appropriate path at each level until point of insertion identified
  • delete: search, remove the node, replace it with the node containing next higher element
  • preorder: starting from root, traverse in node, preorder(left), preorder(right) manner
  • inorder: starting from root traverse in inorder(left), node, inorder(right) manner
  • postorder: starting from root traverse in postorder(left), postorder(right), node manner

Problems from Leet code

  1. Insert BST
  2. Search BST
  3. Delete BST
  4. Validate BST
  5. Trim BST
  6. Lowest Common Ancestor
  7. Sorted array to BST
  8. Recover BST
  9. Find Mode in a BST
  10. Minimum distance between BST nodes

9. AVL Tree

What is it?

  • A binary search tree which is height-balanced

Visualization

Properties

  • Height balanced: The height of the left and right subtrees differ by at most 1

Traversal

  • Usually inorder
    • for retrieving sorted sequence
  • Other traversals are also common

Operations

  • insert, delete, search
  • preorder, inorder, postorder
  • rotateWithLeft
  • rotateWithRight
  • computeBalance
  • height

Implementation

class Node {  
  int data;  
  Node left;  
  Node right; 
  int balanceFactor;
  
  Node(int d);  
  boolean search(int key);  
  boolean insert(int key);  
  boolean delete(int key);  
  void preorder();  
  void inorder();  
  void postorder();  
  void rotateWithLeft();
  void rotateWithRight();
}
class AVLTree {  
  Node root;  

  boolean search(int key) { root.search(key); }  
  boolean insert(int key) { root.insert(key); }  
  boolean delete(int key) { root.delete(key); }  
  void preorder() { root.preorder(); }  
  void inorder() { root.inorder(); }  
  void postorder() { root.postorder(); }  
}

The AVL Tree implementation is given here

Problems

  1. Median of two sorted arrays

10. Graph

What is it?

A non-linear data structure that contains a group of node/vertices where each node/vertex maintains a list of adjacent nodes.

Visualization

Graph

Representation

  1. Adjacency List
0: 1 -> 2
1: 4
2: 1 -> 4
3: 0 -> 2 -> 4
4: 
  1. Adjacency Matrix
------------
.| 0 1 2 3 4 
------------
0| x 1 1 0 0
1| 0 x 0 0 1
2| 0 1 x 0 1
3| 1 0 1 x 1
4| 0 0 0 0 x
------------
  1. Edge List
(0,1) (0,2) (1,4) (2,1) (2,4) (3,0) (3,2) (3,4)
  1. Incidence List
0: 3
1: 0 -> 2
2: 0 -> 3
3:
4: 1 -> 2 -> 3
  1. Incidence Matrix
------------
.| 0 1 2 3 4 
------------
0| x 0 0 1 0
1| 1 x 1 0 0
2| 1 0 x 1 0
3| 0 0 0 x 0
4| 0 1 1 1 x
------------

Traversals

  • Depth First Search (DFS) DFS Traversal

  • Breadth First Search (BFS) BFS Traversal

Implementation

  • addEdge
  • dfs
  • bfs
  • connectivity
  • path, cycle
  • components

For a step-by-step implementation of a graph, please refer Graph Implementation.

Problems from Leetcode & Hackerrank

  1. Find eventual safe states
  2. Clone graph
  3. Course schedule
  4. Reconstruct itinerary
  5. Is graph bipartite
  6. Cheapest flight within K stops
  7. Snake and ladder
  8. Connected component & cycle
  9. DFS Edges
  10. Rotting oranges

11. Disjoint-Set

What is it?

A disjoint set data structure is a collection of sets that are disjoint with each other. Also, there are no duplicates in each set.

Visualizing Disjoint-Set

Disjoint Set

Properties of Disjoint-Set

  • Items are unordered
  • No duplicates

Operations

  • Union
  • Find

Implementation

class Node {
    int label;
    Node parent;

    Node(int l);
}
class DisjointSet {
    Node[] arr;

    void makeSet(int size);
    int find(int key);
    void union(int key1, int key2);
}

For a step-by-step implementation of Disjoint-Set, please refer to Disjoint-Set implementation

Problems from Leetcode

12. Hashtable/Map/Dictionary/Associative Array

What is it?

A data structure that stores <key,value> pairs.

Visualizing HashTable

Hash Table

Operations

  • put
  • get
  • remove

Implementation

class Node {
    int key;
    int value;

    Node(int k, int v);
}
class HashTable {
    Node[] harr;

    int hash(int key);
    void put(int key, int val);
    int get(int key);
    boolean contains(int key);
    void remove(int key);
}

For a step-by-step implementation of HashTable, please refer to Hash Table implementation

Problems from Leetcode

  1. Contains Duplicate
  2. Happy number
  3. Repeated DNA sequences
  4. Isomorphic strings
  5. Fraction to recurring decimal
  6. Valid anagram
  7. Sort characters by frequency
  8. Longest palindrome
  9. Implement magic dictionary
  10. Design Hashmap