impl
impl
Sort
Merge Sort
public void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
arr[k++] = leftArray[i++];
} else {
arr[k++] = rightArray[j++];
Implementation 1
}
}
Quick Sort
Implementation 2
return i + 1;
}
Graph
Adj List
Adj Mat
Implementation 3
import java.util.Arrays;
TRAVELLING SALESMAN
class GfG {
Implementation 4
// Try visiting every city that has not been visited
// yet
for (int i = 0; i < n; i++) {
if ((mask & (1 << i))
== 0) {
BackTrack
N - Queen Problem
Heaps
Maxheap
Merge k sorted arrays insert 1st in min heap then next during extract min
Implementation 5
private static class HeapNode
implements Comparable<HeapNode> {
int x;
int y;
int value;
Implementation 6
}
return result;
}
}
k largest(or smallest) elements in an array Largest use min heap store only
k elements then extract and heaping
class BinaryHeap {
static int capacity; /*Maximum elements that can be stored in heap*/
static int size; /*Current no of elements in heap*/
static int arr[]; /*array for storing the keys*/
BinaryHeap(int cap) {
capacity = cap; /*Assigning the capacity*/
size = 0; /*Intailly size of hepa is zero*/
arr = new int[capacity]; /*Creating a array*/
}
Implementation 7
static int parent(int i) {
return (i - 1) / 2;
}
/*returns the left child of ith Node*/
static int left(int i) {
return 2 * i + 1;
}
/*Returns the right child of the ith Node*/
static int right(int i) {
return 2 * i + 2;
}
Implementation 8
smallest = li;
if (ri < size && arr[ri] < arr[smallest])
smallest = ri;
/*smallest will store the minvalue index*/
/*If the Minimum among the three nodes is the parent itself,
that is Heap property satisfied so stop else call function recursively on Min
if (smallest != ind) {
int temp = arr[ind];
arr[ind] = arr[smallest];
arr[smallest] = temp;
Heapify(smallest);
}
}
static int getMin() {
return arr[0];
}
static int ExtractMin() {
if (size <= 0)
return Integer.MAX_VALUE;
if (size == 1) {
size--;
return arr[0];
}
int mini = arr[0];
arr[0] = arr[size - 1]; /*Copy last Node value to root Node value*/
size--;
Heapify(0); /*Call heapify on root node*/
return mini;
}
static void Decreasekey(int i, int val) {
arr[i] = val; /*Updating the new_val*/
while (i != 0 && arr[parent(i)] > arr[i]) /*Fixing the Min heap*/ {
int temp = arr[parent(i)];
arr[parent(i)] = arr[i];
arr[i] = temp;
i = parent(i);
Implementation 9
}
}
static void Delete(int i) {
Decreasekey(i, Integer.MIN_VALUE);
ExtractMin();
}
static void print() {
for (int i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}
Sorting
count inversions in array - for every 2 sorted arrays cout inversions using
merge sort
median of 2 sorted arrays - how many from 1st array and second array
until n
Implementation 10
// If only a[] has remaining elements
else if (i < n)
m1 = a[i++];
Trees
Morris
// TreeNode structure
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) {
val = x;
left = null;
right = null;
}
}
Implementation 11
// inorder traversal of a binary tree
public List<Integer> getInorder(TreeNode root) {
// List to store the
// inorder traversal result
List<Integer> inorder = new ArrayList<>();
// Pointer to the current node,
// starting from the root
TreeNode cur = root;
Implementation 12
// If the predecessor's right child
// is already linked, remove the link,
// add current node to inorder list,
// and move to the right child
prev.right = null;
inorder.add(cur.val);
cur = cur.right;
}
}
}
Implementation 13
PreOrder Stack
class BinaryTree {
Node root;
void iterativePreorder()
{
iterativePreorder(root);
}
void iterativePreorder(Node node)
{
// Base Case
if (node == null) {
return;
}
/* Pop all items one by one. Do following for every popped item
a) print it
b) push its right child
c) push its left child
Note that right child is pushed first so that left is processed first */
}
PostOrder 2 stacks
class GfG {
Implementation 14
static ArrayList<Integer> postOrder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Implementation 15
return result;
}
Postorder 1 stack
Implementation 16
temp = stack.pop();
// Add the node's data to
// the postorder traversal list
postorder.add(temp.data);
Implementation 17
// Change the prev for subsequent node
next = node;
Implementation 18
/* If there are more than 2 elements */ mid = (low + high) / 2;
mml = getMinMax(arr, low, mid);
mmr = getMinMax(arr, mid + 1, high);
return minmax;
}
BST
https://www.geeksforgeeks.org/print-common-nodes-in-two-binary-search-
trees/
https://www.geeksforgeeks.org/construct-bst-from-given-preorder-
traversa/#efficient-pass-range-in-recursion
https://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst/#expected-
approach-using-one-traversal-on-time-and-oh-space
Linked List
Implementation 19
Remove: remove(), removeFirst(), removeLast(), clear()
Access: get(), getFirst(), getLast(), peek(), peekFirst(), peekLast()
Search: contains(), indexOf(), lastIndexOf()
Queue/Deque: offer(), offerFirst(), offerLast(), poll(), pollFirst(), pollLast()
Utility: size(), isEmpty(), toArray(), iterator()
Stacks/queue
Size: size() , isEmpty() – Check the number of elements and if the queue is
empty.
Implementation 20
Deque<String> deque = new LinkedList<>();
Peek: peekFirst() , peekLast() – View the first or last element without removing.
Size: size() , isEmpty() – Check the number of elements and if the deque is
empty.
Hashmap
Working
public MyHashMap() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}
Implementation 21
final K key;
V value;
Node<K, V> next;
Implementation 22
public V get(K key) {
int index = hash(key);
Node<K, V> node = table[index];
while (node != null) {
if (node.key.equals(key)) {
return node.value;
}
node = node.next;
}
return null;
}
Implementation 23
while (node != null) {
Node<K, V> next = node.next;
int index = hash(node.key);
node.next = newTable[index];
newTable[index] = node;
node = next;
}
}
table = newTable;
capacity = newCapacity;
}
Strings
https://www.geeksforgeeks.org/longest-palindromic-substring/
https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-
containing-all-characters-of-another-string/
Arrays
https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/
Implementation 24