7 Essential Data Structures For Coding Interviews Cheat Sheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

7 ESSENTIAL Different types of complexities

Complexity Performance Type


Array example

DATA STRUCTURES
Student Grades in GSE 143

O(1) Best Constant


Array
Array 92.8 72.4 89.0 82.2 Element
O(log n) Excellent Logrithmic

FOR CODING INTERVIEWS


Index 0 1 2 3
O(n) Good Linear (Polynomial)
arr[0]; arr[1]; arr[2]; arr[3];
O(n log n) Fair Polynomial

The starting index of an


O(n2) Bad Quadratic (Polynomial) array depends on the
1. Array programming language
2. Linked List O(2n) Poor Exponential

3. Hash Table O(n!) Worst Factorial


4. Stack
5. Queue
6. Heap
7. Binary Search Tree Basic operation on data structures
Operations Description
What is a Data Structure? Access Visits an element in a data
A data structure organizes collections of data to store it efficiently to
Searches for an element in the
make the process of accessing or modifying the data easier. Search
data structure Code example
Insert Inserts an element in the data // C++ code to print an array:
Data Structure Categories #include <iostream>
Deletes an element from the data using namespace std;
Delete // This function prints an array
structure
void printArray(int *arr,int size)
Data Structures {
cout<<"The contents of the array are:\n";
1. Array for(int i=0; i<size;i++)
cout<<arr[i]<<" ";
Linear Non-Linear
An array is a linear data structure that contains cout<<endl;
elements of the same data type stored at }
contiguous memory locations. // Driver Code
int main()
Binary Search Hash Element: A data item stored in an array at a {
Static Dynamic Heap
Tree Table // Considering inputs given are valid
specific index int arr[5]={10,20,30,40,50};
Index: A unique, numerical identifier that printArray(arr,5);
Array Stack Queue Linke indicates an element's location in an array return 0;
}

Code to print an array in C++


Pros Cons

Great for storing and Arrays are fixed-size data


Time and Space Complexity accessing large amounts of structures, so expanding or
data quickly, as they minimizing one requires
Time complexity: The amount of time required to run provide constant time reallocation. This can
analgorithm, corresponding to an input of a specific size not access to all elements, consume a lot of time and
including the space taken by the input. regardless of their index memory.
position
Space complexity: The amount of space required to run an Good for storing multiple
algorithm, corresponding to an input of a specific size. not elements of the same type
including the space taken by the input. Easy to sort and search
through
2. Linked list
Pros Cons # A single node of a singly linked list
A linked list is a linear data structure that stores data as a chain of class Node:
Retrieving nodes takes nodes at non-contiguous memory locations linked together by # constructor
Dynamic data structure: pointers. Each node contains a data element and pointer to the
def __init__(self, data =None, next=None):
adding and deleting more time as it doesn’t self.data = data
support direct access to Data: Heterogeneous data can be stored in each node self.next = next
nodes is easier
individual elements via Pointer: It is used to store the address of the next node
# A Linked List class with a single head node
More efficient for data of index positions in constant class LinkedList:
arbitrary length whose Code Example
time def __init__(self):
size is not known in self.head = None
Searching data is slow as #include <iostream>
advance techniques such as binary using namespace std;
# insertion method for the linked list
Can store data even search cannot be // Making a node struct containing an int data and a pointer
def insert(self, data):
newNode = Node(data)
when no contiguous umployed // to next node
if self.head:
struct Node
memory is available current = self.head
Nodes with pointers use {
while current.next:
int data;
up some memory Node *next; current = current.next
// Parameterised constructor with default argument current.next = newNode
Node(int val=0) :data(val),next(nullptr){} else:
// Parameterise constructor self.head = newNode
Node(int val, Node *tempNext):data(val),next(tempNext){}
Types of linked lists }; # print method for the linked list
def printLL(self):
Singly-linked list: Only allows forward navigation class LinkedList current = self.head
{ while(current):
Doubly-linked list: Allows forward and backward navigation // Head pointer print(current.data)
Unlike a typical linked list, a doubly-linked list maintains two Node* head; current = current.next
Circular linked list: The node in this list has the next pointer public: # Singly Linked List with insertion and print methods
to the first node // default constructor. Initializing head pointer LL = LinkedList()
LinkedList():head(nullptr) LL.insert(6)
{ LL.insert(9)
Linked list example } LL.insert(1)
LL.insert(3)
// inserting elements (At start of the list) LL.insert(7)
Singly-linked List void insert(int val) LL.printLL()
{
// make a new node
Node Node Node Node Node *new_node = new Node(val);
I// If list is empty, make the new node, the head Linked list class in Python
Pointer Pointer Pointer Pointer
(Next) (Next) (Next) (Next) if (head == nullptr)
Data Data Data Data
{
Element Element Element Element
}
head = new_node; 3. Hash table
// else, make the new_node the head and its next, the previous
// head
A hash table is an unordered collection of key-value pairs where a
Doubly-linked List else hash key is mapped to a hash value (data element), typically as an
{ array of linked lists. A hash function takes arbitrary-length data as
Node Node Node Node new_node->next = head; an input and generates a fixed-length output. The output is the
head = new_node;
Pointer Pointer Pointer Pointer }
hash key of the given data. A value is stored at a location based on
(Next) (Next) (Next) (Next)
} its hash key. This process is known as hashing.
Data Data Data Data
Element Element Element Element
Printer
(Previous)
Printer
(Previous)
Printer
(Previous)
Printer
(Previous) void display() In summary
{
Node* temp = head; Hash function: Takes an arbitrary length input and produces a
while(temp != nullptr)
Circular Singly-linked List {
fixed-length output
cout << temp->data << " "; Hash value: Input of a hash function
Node Node Node Node temp = temp->next; Hash key: Output of a hash function
}
Pointer Pointer Pointer Pointer cout << endl; If the hash function generates the same hash keys for multiple hash
(Next) (Next) (Next) (Next)
} values, then a conflict known as a hash collision occurs, where two
Data Data Data Data };
Element Element Element Element
int main()
pieces of data in a hash table share the same hash value.
{
LinkedList l;
// inserting elements
l.insert(6);
l.insert(9);
l.insert(1);
l.insert(3);
l.insert(7);
cout << "Current Linked List: ";
l.display();
}

Linked list class in C++

Singly-Linked and Doubly-Linked


Stack example 6. Heap
Pros Cons
LIFO (Last In, First Out) A heap is a complete binary tree where each node is associated
Constant time lookup, Complex to implement with a key that satisfies a heap property. Heap data structures are
insertion and deletion (as Data Element Data Element particularly useful for finding the minimum or maximum value in a
Hash collisions can cause data set, and are effectively used as priority queues.
long as there is no hash performance issues when
collision) accessing or searching
Data Element Data Element
Max Heap Property: In the case of a max heap, the keyof a parent
May store heterogeneous items in a hash table Data Element Data Element node must be greater than or equal to the keyof the child node.
Push Pop
data Hash keys require some Data Element Data Element
The push() operation The pop() operation Min Heap Property: In the case of a min heap, the keyof a parent
extra computational stores an element on removes an element
top of the stack. Data Element Data Element from the top of the node must be less than or equal to the keyof the child node.
stack.
Stack Stack
Hash table example
Pros Cons
Movie Data Record Hash Table Time complexity of Not the best data structure
insertion or deletion is just to traverse or search data
Groundhog Day Index (Key) Year (Hash Value) O(log n)
Hash
Function 0 2008 A binary heap is a
My Neighbor Totoro
complete binary tree
1 2014 Simple to implement, can
The Grand
be done with just an array
Budapest Hotel
2 1988

Ip Man
3 1993 5. Queue Max Heap Binary Tree
Queues store elements in a First-In, First-Out (FIFO) order, meaning Index: 0
that elements are removed in the order they arrived.
900

1 2
Pros Cons
600 300
Great for breadth-first Limited use cases
search (BFS) 3 4 5 6
compared to other data
550 50 220 80
Efficient add/removal of
items 7 8 9

400 150 10
Queue example
Array Representation

4. Stack LIFO (Last In, First Out)


Elements
Index
900
0
600
1
300
2
550
3
50
4
220
5
80
6
400
7
150
8
10
9
Stack and queue data structures are often mentioned in the same Front Back
breath because of their similar characteristics, but they behave Removal Data Data Data Data Data Insertion
differently when adding or removing data. Element Element Element Element Element

Stacks store elements in a Last-In, First-Out (LIFO) order, meaning


Data Data
that the last element added to the stack is the first one removed. Element
Dequeue Enqueue
Element
The dequeue() The enqueue()
operation forms an operation stores an
element from the element at the
Pros Cons front of the queue back of the queue

Great for depth-first search Limited use cases


(DFS) compared to some other
Efficient addition/removal data structures
of items
Used in recursive function
calls and also by the
call-stack of programming
languages
Advanced Data Structures
Min Heap Binary Tree Pros Cons
We've covered 7 essential data structures that every developer should
Index: 0
Insertion and deletion can Implementing a balanced learn.
1 be fast and efficient binary search tree is
Some advanced data structures that software engineers can get
Supports range queries - necessary to avoid
1 2 familiar with include:
Relatively simple degradation of
3 4 compared to other data performance 1. Tries
structures 2. Self-Balancing BSTs
Accessing elements from a
3 4 5 6 3. Disjoint Sets
Easy to implement BST is slower than in an
25 66 8 12 4. Segment Trees
array
5. Queaps
7 8 9 6. Binary Indexed Trees
Binary search tree example 7. Succinct Data Structures
98 124 14
Array Representation
Elements 1 3 4 25 66 8 12 98 124 14 Binary Search Tree
Index 0 1 2 3 4 5 6 7 8 9 Root

22(key)

12 25

10 20 22 32
Leaf Leaf

8 11 14 34
Application of Heap Data Structures Leaf Leaf Leaf Leaf

Priority queues
Heapsort
Order statistics

7. Binary Search Trees


Binary search trees (BST) are non-linear data structures that store
data elements in nodes. Each node contains one or more data items
and two pointers that branch off to child nodes called the left child
and the right child.

A key issue with BST is that they are not self-balancing hence
The key of the left child must be less than or equal to the key of
leading to compromised time-complexity. To mitigate this,
the parent node.
several self-balancing BST variants can be used, such as AVL
The key of the right child must be greater than the key of the
Trees and Red Black Trees.
parent node.

This allows you to use relational operators to efficiently find items


in a binary search tree.

That is, we compare a key (x) stored in a node x with the value to
search y, using the following three conditions:
1. When x is equal to y, x==y, end the search
2. When x is less than or equal to y, x<=y, go to the right child
3. When x is greater than y, x>y, go to the left child

You might also like