? 15 Algorithms Every Programmer Should Know ?
? 15 Algorithms Every Programmer Should Know ?
Searching Algorithms
Linear Search:
Linear search is a simple searching algorithm that sequentially
checks each element in a list or array until it nds the target
value or reaches the end o the list. It is also known as a
sequential search.
Time Complexity: O(n)
2|Page
Sample Problems:
• Kth Missing Positive Number
Given an array arr o positive integers sorted in a strictly
increasing order, and an integer k.
Return the kth positive integer that is missing rom this array.
Input: arr = [2,3,4,7,11], k = 5
Output: 9
• Searching a number
Given an array Arr o N elements and a integer K. Your task is
to return the position o rst occurence o K in the given array.
Input: N = 5, K = 16
Arr [ ] = {9, 7, 2, 16, 4}
Output: 4
3|Page
Binary Search:
Binary search is an efcient searching algorithm that works on
sorted lists or arrays. It ollows a divide-and-conquer
approach, repeatedly dividing the search space in hal until the
target element is ound or determined to be absent.
4|Page
Sample Problems:
• Binary Search
Given an array o integers nums which is sorted in ascending
order, and an integer target, write a unction to search target in
nums. I target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
5|Page
Sorting Algorithms
Bubble Sort Algorithms:
Bubble sort is a simple sorting algorithm that repeatedly steps
through the list or array, compares adjacent elements, and
swaps them i they are in the wrong order. The algorithm gets
its name rom the way smaller elements "bubble" to the top o
the list with each iteration.
6|Page
Sample Problems:
• Sort Colors
Given an array nums with n objects colored red, white, or blue,
sort them in-place so that objects o the same color are
adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red,
white, and blue, respectively.
You must solve this problem without using the library's sort
unction.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
• Bubble Sort
Given an Integer N and a list arr. Sort the array using bubble
sort algorithm.
Input: N = 5
arr[ ] = {4, 1, 3, 9, 7}
Output: 1 3 4 7 9
7|Page
Insertion Sort Algorithms:
Insertion sort is a simple sorting algorithm that builds the nal
sorted array one element at a time. It iterates through the input
list or array and gradually expands a sorted portion o the list
by inserting each new element in its proper place.
8|Page
Sample Problems:
• Insertion Sort
The task is to complete the insert() unction which is used to
implement Insertion Sort.
Input:
N = 5, arr[ ] = { 4, 1, 3, 9, 7}
Output: 1 3 4 7 9
• Insertion Sort ||
The rst line contains one space separated integer N denoting
the number o elements.
The Second line contains N space separated integers
denoting the elements o the array.
You need to complete insertionSort unction which contains a
array o size n and print the nal sorted array in this unction
only.
Input: 7 6 8 5 4 9
Output: 4 5 6 7 8 9
9|Page
Selection Sort Algorithms:
Selection sort is a simple sorting algorithm that divides the
input list into two parts: the sorted portion at the beginning
and the unsorted portion at the end. It repeatedly selects the
smallest element rom the unsorted portion and swaps it with
the element at the beginning o the unsorted portion, thus
expanding the sorted portion by one element.
10 | P a g e
Sample Problems:
• Selection Sort
Given an unsorted array o size N, use selection sort to sort
arr[ ] in increasing order.
Example 1:
Input:
N = 5, arr[ ] = {4, 1, 3, 9, 7}
Output: 1 3 4 7 9
• Selection Sort ||
Implement Selection Sort on a given array, and make it sorted.
Input Format
First line o the input contains an integer, N, which denotes the
length o the array. Next N inputs are elements o the array that
is to be sorted in ascending order.
Output Format
Sorted output where each element is space separated
Example 1:
Input: 1 2 7 3 4
Output: 1 2 3 4 7
11 | P a g e
Heap Sort Algorithms:
Heap sort is a comparison-based sorting algorithm that uses
a binary heap data structure to sort elements. It involves
building a heap rom the input list and repeatedly extracting
the maximum (or ascending order) or minimum (or
descending order) element rom the heap and placing it at the
end o the sorted portion o the list.
• Heap Sort ||
Given an array o size N. The task is to sort the array elements
by implementing Heap Sort.
• Hint: Make two unctions heapiy() and heapSort().
• The passed array needs to be sorted
Input Format
The rst line contains an integer N, the size o the array.
The second line contains N spaced integers, the elements o
the array.
Output Format
Print the sorted array.
Input: 4 1 3 9 7
Output: 1 3 4 7 9
13 | P a g e
Merge Sort Algorithms:
Merge sort is a recursive sorting algorithm that ollows the
divide-and-conquer principle. It divides the input list or array
into smaller subproblems, sorts them independently, and then
merges them to obtain a sorted result.
14 | P a g e
Sample Problems:
• Merge Sort
Given an array arr[ ], its starting position l and its ending
position r. Sort the array using merge sort algorithm.
Input: N = 5, arr[ ] = {4 1 3 9 7}
Output: 1 3 4 7 9
15 | P a g e
Quick Sort Algorithms:
Quick sort is a highly efcient, comparison-based sorting
algorithm that ollows the divide-and-conquer principle. It
works by partitioning the input list or array into two subarrays
based on a chosen pivot element, and recursively sorting the
subarrays.
16 | P a g e
17 | P a g e
Graph Algorithms
Breadth-frst search:
Breadth-rst search is an algorithm or searching a tree data
structure or a node that satises a given property. It starts at
the tree root and explores all nodes at the present depth prior
to moving on to the nodes at the next depth level
18 | P a g e
Sample Problems:
• Symmetric Tree
Given the root o a binary tree, check whether it is a mirror o
itsel (i.e., symmetric around its center).
Example 1:
19 | P a g e
Depth-frst search:
Depth-rst search is an algorithm or traversing or searching
tree or graph data structures. The algorithm starts at the root
node and explores as ar as possible along each branch beore
backtracking.
20 | P a g e
Sample Problems:
• Binary Tree Inorder Traversal
Given the root o a binary tree, return the inorder traversal o
its nodes' values.
Input: root = [1,null,2,3]
Output: [1,3,2]
• X Total Shapes
Given a grid o n*m consisting o O's and X's. The task is to
nd the number o 'X' total shapes.
Note: 'X' shape consists o one or more adjacent X's
(diagonals not included).
Input: grid = {{X,O,X},{O,X,O},{X,X,X}}
Output: 3
• Select Nodes
Given N nodes o a tree and a list o edges. Find the minimum
number o nodes to be selected to light up all the edges o the
tree.
An edge lights up when at least one node at the end o the
edge is selected.
Input: N = 6
Edges [ ] = {(1,2), (1,3), (2,4), (3,5), (3,6)}
Output: 2
21 | P a g e
Dijkstra's algorithm
Dijkstra's algorithm is an algorithm or nding the shortest
paths between nodes in a weighted graph, which may
represent, or example, road networks. It was conceived by
computer scientist Edsger W. Dijkstra in 1956 and published
three years later. The algorithm exists in many variants
22 | P a g e
Sample Problems:
• Implementing Dijkstra Algorithm
Given a weighted, undirected and connected graph o V
vertices and an adjacency list adj where adj[i] is a list o lists
containing two integers where the rst integer o each list j
denotes there is edge between i and j , second integers
corresponds to the weight o that edge . You are given the
source vertex S and You to Find the shortest distance o all the
vertex's rom the source vertex S. You have to return a list o
integers denoting shortest distance between each node and
Source vertex S.
Input: V = 2
adj [ ] = {{{1, 9}}, {{0, 9}}}, S = 0
Output: 0 9
• Path with Maximum Probability
You are given an undirected weighted graph o n nodes (0-
indexed), represented by an edge list where edges[i] = [a, b] is
an undirected edge connecting the nodes a and b with a
probability o success o traversing that edge succProb[i].
Given two nodes start and end, nd the path with the
maximum probability o success to go rom start to end and
return its success probability.
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2],
start = 0, end = 2
Output: 0.25000
23 | P a g e
Kadane’s Algorithm
Kadane’s Algorithm:
Kadane's algorithm is an efcient algorithm used to nd the
maximum sum o a contiguous subarray within a given array
o numbers. It is oten used to solve the maximum subarray
problem.
24 | P a g e
Sample Problems:
• Maximum Subarray
Given an integer array nums, nd the subarray with the largest
sum, and return its sum.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
• Max Sum
Find max sum contiguous subarray.
Input: [-3, -4, 5, -1, 2, -4, 6, -1]
Output: 8
25 | P a g e
Tree Algorithm
Inorder Traversal:
• In an inorder traversal, the let subtree is visited rst,
ollowed by the root node, and then the right subtree.
• The inorder traversal visits the nodes o a binary tree in
ascending order when applied to a binary search tree
(BST).
• The pseudocode or inorder traversal is as ollows:
Output: 3 1 2
• Inorder Traversal ||
Given the root o a binary tree, return the inorder traversal o
its nodes' values.
Input:
27 | P a g e
Preorder Traversal:
• In a preorder traversal, the root node is visited rst,
ollowed by the let subtree, and then the right subtree.
• The preorder traversal is useul or creating a copy o a
tree, as the nodes are visited in the order they appear in
the original tree.
• The pseudocode or preorder traversal is as ollows:
28 | P a g e
Sample Problems:
• Preorder Traversal
Given a binary tree, nd its preorder traversal.
Input:
Output: 1 4 4 2
• Preorder Traversal ||
Given the root o a binary tree, return the preorder traversal o
its nodes' values.
29 | P a g e
Postorder Traversal:
• In a postorder traversal, the let subtree is visited rst,
ollowed by the right subtree, and nally the root node.
• The postorder traversal is commonly used to delete
nodes rom a tree since it ensures that a node's children
are deleted beore the node itsel.
• The pseudocode or postorder traversal is as ollows:
30 | P a g e
Sample Problems:
• Postorder Traversal
Given a binary tree, nd the Postorder Traversal o it.
Input:
Output: 11 13 10 8 19
• Postorder Traversal ||
Given the root o a binary tree, return the postorder traversal o
its nodes' values.
31 | P a g e