Project Explanation
Project Explanation
and more. The student will select from the following projects and make it into an appropriate
coding and analyze the code within their presentation.
The students are free to have a PowerPoint slides for further explanation of their project and also
must be able to provide a suitable explanation and the way that they solved the problem.
In the presentation day (24/11/2024 and the time is from 10:30 to 14:30) there is no further
extension of the projects. Each group must be in a pair of two students and each student will
have a separate mark. They must provide the supervisors with the way they solved the problem.
Select the algorithm and write it down in the spreadsheet provided in the LMS system. Each
group can only take one algorithm. The student must work in group and carefully read the
algorithm and extract the useful information in give the correct solution for each projects.
Total Marks is 10 for each student and the supervisors are free to ask any type of questions.
Explanation: The task is to find the k-th smallest element in an unsorted array. There are
multiple approaches, such as sorting the array and selecting the k-th element or using more
efficient methods like Quickselect.
Approach 1: Sorting
Example 1:
Example 2:
Approach:
• Time Complexity: O(log(min(n, m))), where n and m are the sizes of the arrays.
Example 1:
Example 2:
Explanation: In a sorted array, the task is to find the first and last positions of a target element.
This can be done using binary search.
Approach:
Example 1:
Example 2:
Explanation: A peak element in an array is one that is greater than its neighbors. The goal is to
find any peak element. This can be solved using a binary search-like approach.
Approach:
Example 1:
Example 2:
Explanation: The task is to reverse a given string using recursion, rather than iteration.
Approach:
1. Base case: If the string is empty or has one character, return it.
2. Recursive case: Return the last character + recursive call on the rest of the string.
Example 1:
Example 2:
Explanation: A palindrome is a string that reads the same forwards and backward. The task is to
check if a given string is a palindrome.
Example 1:
Example 2:
Explanation: Given an array of strings, the task is to find the longest common prefix (if any).
• Time Complexity: O(S), where S is the sum of all characters in all strings.
Example 1:
Example 2:
Explanation: Given a string, the task is to find the longest substring that is a palindrome.
Example 2:
Explanation: Two strings are anagrams if they contain the same characters with the same
frequencies.
Example 1:
Example 2:
Explanation: The KMP (Knuth-Morris-Pratt) algorithm is used for pattern searching in strings.
It preprocesses the pattern to build a partial match table, which helps in skipping redundant
comparisons.
• Time Complexity: O(n + m), where n is the length of the text, and m is the length of the pattern.
Example 1:
Example 2:
Approach:
1. Compute the hash value for the pattern and the first window of text.
2. Slide the window one position at a time, updating the hash incrementally.
3. If the hash matches, compare the actual substring with the pattern.
Time Complexity:
Example 1:
Example 2:
Explanation: The Z-Algorithm is used to find occurrences of a pattern in a text in linear time. It
computes a Z-array, where each entry represents the length of the longest substring starting from
that position that matches the prefix of the combined string (pattern + text).
Approach:
Example 2:
Explanation: The task is to find all possible permutations of a given string. This is typically
solved using backtracking.
Approach:
Example 2:
Explanation: The task is to find the first character that does not repeat in a string.
Approach 1: Using a Frequency Counter
• Traverse the string twice: Once to count frequencies and once to find the first character with a
frequency of 1.
Example 2:
Explanation: Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones. Dynamic programming helps in solving it efficiently by storing previously
computed results.
Approach:
• Input: n = 5
• Output: Fibonacci sequence = 0, 1, 1, 2, 3
Example 2:
• Input: n = 10
• Output: Fibonacci sequence = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Approach:
• Use dynamic programming to store the length of the LIS ending at each element.
• Update the length based on previous elements.
• Input: arr = [10, 22, 9, 33, 21, 50, 41, 60, 80]
• Output: 6 (The LIS is [10, 22, 33, 50, 60, 80])
Example 2:
Explanation: The task is to find the longest subsequence common to two given sequences.
Approach:
• Use dynamic programming to store the LCS lengths in a 2D table, and build the result by
comparing characters from both strings.
Example 2:
Approach:
Example 2:
Explanation: The task is to find the minimum number of coins needed to make a given sum
using a set of coin denominations.
Approach:
• Use dynamic programming to compute the minimum number of coins required for each amount
up to the target sum.
Time Complexity: O(n * S), where n is the number of coin denominations and S is the target sum.
Example 1:
Example 2:
Approach:
• Use dynamic programming to check if each substring can be formed using words from the
dictionary.
Example 2:
Explanation: The Partition problem is a special case of the subset sum problem. The goal is to
determine if a given set can be partitioned into two subsets such that the sum of elements in both
subsets is equal.
Approach:
Time Complexity: O(n * sum), where n is the number of elements, and sum is the total sum of the array.
Example 1:
Example 2:
Explanation: The task is to determine the minimum number of attempts needed to find the
critical floor (the highest floor from which an egg can be dropped without breaking) in a building
with k eggs and n floors.
Approach:
• Input: k = 2, n = 6
• Output: 3 (You need at least 3 attempts)
Example 2:
• Input: k = 3, n = 14
• Output: 4
Explanation: Kadane’s algorithm is used to find the maximum sum of a contiguous subarray in
an array of integers (including negative numbers).
Approach:
• Keep track of the maximum sum ending at the current position and update the global maximum
if the current sum exceeds it.
Example 2:
Explanation: The task is to find the minimum sum of a path from the top-left corner to the
bottom-right corner of a grid. You can only move right or down.
Approach:
• Use dynamic programming to compute the minimum path sum by filling a table based on the
costs at each cell.
Time Complexity: O(m * n), where m is the number of rows, and n is the number of columns.
Example 1:
Example 2:
Explanation: The task is to find the number of unique paths from the top-left corner to the
bottom-right corner of a grid, moving only right or down.
Approach:
• Input: m = 3, n = 7
• Output: 28 (There are 28 unique paths)
Example 2:
• Input: m = 3, n = 2
• Output: 3
26. Rod Cutting Problem
Explanation: The task is to maximize the profit obtained by cutting a rod of length n into
smaller pieces, where each piece has a price associated with its length.
Approach:
• Use dynamic programming to calculate the maximum revenue by considering all possible cuts.
Example 2:
Explanation: Depth-First Search is a graph traversal algorithm that explores as far as possible
along a branch before backtracking.
Approach:
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
Example 1:
Example 2:
Explanation: BFS is a graph traversal algorithm that explores all neighbors of a vertex before
moving to the next level of vertices.
Approach:
Example 2:
Explanation: A connected component is a set of vertices in an undirected graph such that there
is a path between any pair of vertices in the component.
Approach:
• Use DFS or BFS to find all vertices in a connected component and mark them as visited.
Example 2:
Approach:
• For undirected graphs, use DFS and track the parent of each vertex.
• For directed graphs, use DFS and maintain a recursion stack.
Example 2:
Explanation: Topological sort is the linear ordering of vertices in a Directed Acyclic Graph
(DAG) such that for every directed edge u → v, vertex u comes before v in the ordering.
Approach:
• Use Depth-First Search (DFS) and a stack. For each node, after visiting all its neighbors, push it to
the stack. At the end, the stack will contain the topologically sorted vertices.
Example 2:
Approach:
• Use a priority queue to explore the graph, always expanding the node with the smallest known
distance first.
• Input: graph = {0: [(1, 1), (2, 4)], 1: [(2, 2), (3, 5)], 2: [(3, 1)], 3:
[]}, start vertex = 0
• Output: Distances: [0, 1, 3, 4]
Example 2:
• Input: graph = {0: [(1, 2)], 1: [(2, 2)], 2: []}, start vertex = 0
• Output: Distances: [0, 2, 4]
Explanation: Bellman-Ford algorithm computes shortest paths from a single source vertex to all
other vertices in a weighted graph. It can handle graphs with negative weight edges.
Approach:
• Relax all edges up to V - 1 times, where V is the number of vertices. If you can relax an edge
after V - 1 iterations, then a negative-weight cycle exists.
• Input: graph = {0: [(1, -1), (2, 4)], 1: [(2, 3), (3, 2)], 2: [(3, 5)], 3:
[]}, start vertex = 0
• Output: Distances: [0, -1, 2, 1]
Example 2:
• Input: graph = {0: [(1, 4), (2, 5)], 1: [(2, -3)], 2: []}, start vertex = 0
• Output: Distances: [0, 4, 1]
34. Floyd-Warshall Algorithm for All-Pairs Shortest Path
Explanation: The Floyd-Warshall algorithm finds the shortest paths between all pairs of vertices
in a graph. It can handle negative weights but not negative cycles.
Approach:
• Use dynamic programming to iteratively improve the shortest path by considering intermediate
vertices.
• Input: graph = [[0, 3, INF, 5], [2, 0, INF, 4], [INF, 1, 0, INF], [INF,
INF, 2, 0]]
• Output: Shortest distances matrix:
[[0, 3, 7, 5],
[2, 0, 6, 4],
[3, 1, 0, 5],
[5, 4, 2, 0]]
Example 2:
[[0, 2, 3],
[4, 0, 1],
[3, 5, 0]]
Explanation: Prim’s algorithm is used to find the minimum spanning tree (MST) of a graph. The
MST connects all vertices with the minimum total edge weight.
Approach:
• Start from any vertex and grow the MST by selecting the smallest edge that connects a vertex in
the MST to a vertex outside the MST.
• Input: graph = {0: [(1, 2), (3, 6)], 1: [(0, 2), (2, 3), (3, 8)], 2: [(1,
3), (3, 7)], 3: [(0, 6), (1, 8), (2, 7)]}
• Output: MST edges: [(0, 1), (1, 2), (0, 3)]
Example 2:
• Input: graph = {0: [(1, 10), (2, 6)], 1: [(2, 5)], 2: [(1, 5), (0, 6)]}
• Output: MST edges: [(1, 2), (0, 2)]
Explanation: Kruskal’s algorithm is another method to find the MST by sorting all edges and
adding the smallest edge that doesn’t form a cycle.
Approach:
• Sort edges by weight and use the Union-Find data structure to check for cycles.
Example 2:
Explanation: Tarjan's algorithm finds all strongly connected components (SCCs) in a directed
graph. A strongly connected component is a maximal set of vertices such that each vertex is
reachable from every other vertex in the set.
Approach:
• Use DFS to assign discovery times and low-link values, and identify SCCs based on those values.
Explanation: A bridge (or cut-edge) is an edge in an undirected graph whose removal increases
the number of connected components.
Approach:
Example 2:
Approach:
• Use DFS to compute discovery and low values to find articulation points.
• Input: graph = {0: [1, 2], 1: [0, 2], 2: [0, 3], 3: [2]}
• Output: Articulation points: [2]
Example 2:
Explanation: A bipartite graph is a graph where you can divide vertices into two sets such that
no two vertices in the same set are adjacent.
Approach:
• Use BFS or DFS to try to color the graph with two colors. If you find a conflict (two adjacent
vertices with the same color), the graph is not bipartite.
Example 2:
Explanation: The Ford-Fulkerson algorithm solves the maximum flow problem in a flow
network. The idea is to find the maximum possible flow from a source node to a sink node by
repeatedly finding augmenting paths.
Approach:
• Use Depth-First Search (DFS) to find paths with available capacity (residual graph) and augment
the flow along these paths until no more augmenting paths exist.
Time Complexity: O(E * max flow)
Example 1:
• Input: graph = {0: [(1, 16), (2, 13)], 1: [(2, 10), (3, 12)], 2: [(1, 4),
(3, 14)], 3: []}, source = 0, sink = 3
• Output: Maximum flow = 23
Example 2:
• Input: graph = {0: [(1, 3), (2, 2)], 1: [(2, 5), (3, 2)], 2: [(3, 3)], 3:
[]}, source = 0, sink = 3
• Output: Maximum flow = 5
Explanation: The problem involves finding the shortest path from a starting point to a
destination in a 2D grid maze, where certain cells are blocked.
Approach:
• Use Breadth-First Search (BFS), as it finds the shortest path in an unweighted grid. BFS explores
all possible paths level by level.
Time Complexity: O(n * m) where n and m are the dimensions of the grid.
Example 1:
• Input: maze = [[0, 0, 1], [0, 0, 1], [1, 0, 0]], start = (0, 0), end = (2, 2)
• Output: Shortest path = 4
Example 2:
• Input: maze = [[0, 1], [0, 0]], start = (0, 0), end = (1, 1)
• Output: Shortest path = 2
Explanation: Tree traversal means visiting all nodes in a tree in a specific order.
Approach:
markdown
1
/ \
2 3
/ \
4 5
• Output: 4 2 5 1 3
Example 2 (Pre-order):
• Output: 1 2 4 5 3
Example 3 (Post-order):
• Output: 4 5 2 3 1
Explanation: Level order traversal visits nodes level by level starting from the root.
Approach:
1
/ \
2 3
/ \
4 5
• Output: 1 2 3 4 5
45. Check if a Binary Tree is Balanced
Explanation: A binary tree is balanced if, for each node, the difference in height between the left
and right subtrees is at most 1.
Approach:
• Use DFS to check the height of left and right subtrees recursively.
• Input:
markdown
1
/ \
2 3
/
4
Example 2:
• Input:
markdown
1
/
2
/
3
Explanation: The height of a binary tree is the number of edges on the longest path from the
root to a leaf.
Approach:
• Use recursion to compute the height of the left and right subtrees, then return the maximum.
Time Complexity: O(n)
Example 1:
• Input:
markdown
1
/ \
2 3
/ \
4 5
• Output: 3
Example 2:
• Input:
markdown
1
/ \
2 3
• Output: 2
Explanation: The diameter of a binary tree is the length of the longest path between any two
nodes in the tree. This path may or may not pass through the root.
Approach:
• Use recursion to calculate the height of subtrees and keep track of the maximum diameter
found.
• Input:
markdown
1
/ \
2 3
/ \
4 5
• Output: Diameter = 4 (path: 4 → 2 → 1 → 3)
Example 2:
• Input:
markdown
1
/
2
/ \
3 4
Explanation: The Lowest Common Ancestor (LCA) of two nodes in a binary tree is the deepest
node that has both nodes as descendants.
Approach:
• Use recursion to search for the two nodes in the tree. Once both nodes are found in different
subtrees, the current node is the LCA.
• Input:
markdown
1
/ \
2 3
/ \
4 5
Nodes: 4 and 5
• Output: LCA = 2
Example 2:
• Input:
markdown
1
/ \
2 3
/
4
Nodes: 2 and 4
• Output: LCA = 2
Explanation: A binary search tree is a binary tree in which the left child is smaller than the
node, and the right child is larger than the node.
Approach:
• Use recursion to validate that every node satisfies the BST property (left < node < right).
• Input:
markdown
2
/ \
1 3
Example 2:
• Input:
markdown
5
/ \
2 4
Approach:
• Perform an in-order traversal and keep track of the count of nodes visited.
• Input:
markdown
3
/ \
1 4
\
2
k=2
• Output: 2
• Input:
markdown
5
/ \
3 7
/ \
2 4
k=3
• Output: 5
Explanation: This problem involves converting a binary tree to a doubly linked list (DLL),
where the in-order traversal of the binary tree corresponds to the order of nodes in the DLL.
Approach:
• Perform in-order traversal and adjust the left pointer of each node to point to the previous node
(previous DLL node) and the right pointer to the next node (next DLL node).
• Recursion or iterative stack-based approach can be used.
• Input:
markdown
1
/ \
2 3
/ \
4 5
Approach:
• For serialization, use pre-order or level-order traversal and store values, using special characters
(e.g., #) to represent null nodes.
• For deserialization, reconstruct the tree from the serialized string using a queue.
• Input:
markdown
1
/ \
2 3
/ \
4 5
Explanation: The maximum path sum is the largest sum of values from any path in a binary tree.
A path can start and end at any node, and must contain at least one node.
Approach:
• Use recursion to calculate the maximum path sum for the left and right subtrees. At each node,
track the maximum sum that can be achieved passing through it.
• Input:
markdown
-10
/ \
9 20
/ \
15 7
Explanation: The in-order successor of a node in a BST is the next node in the in-order traversal
of the BST. If the node has a right child, the successor is the leftmost node in the right subtree;
otherwise, it is the lowest ancestor for which the node is in its left subtree.
Approach:
• If the node has a right child, the successor is the minimum value in the right subtree.
• If there’s no right child, the successor is the nearest ancestor for which the node is in its left
subtree.
• Input:
markdown
20
/ \
8 22
/ \
4 12
Node = 8
Example 2:
• Input: Node = 12
• Output: In-order successor = 20
Approach:
• Check divisibility by numbers from 2 to √n. If divisible by any of these, it’s not prime.
• Input: n = 11
• Output: true (11 is prime)
Example 2:
• Input: n = 12
• Output: false (12 is not prime)
Explanation: The Sieve of Eratosthenes is an efficient algorithm for generating all prime
numbers up to a given number n. It iteratively marks the multiples of each prime starting from 2.
Approach:
• Create a boolean array and mark all numbers as prime initially. Starting from 2, mark all its
multiples as non-prime.
Time Complexity: O(n log log n)
Example 1:
• Input: n = 10
• Output: Prime numbers = [2, 3, 5, 7]
Example 2:
• Input: n = 20
• Output: Prime numbers = [2, 3, 5, 7, 11, 13, 17, 19]
57. Find the Greatest Common Divisor (GCD) Using Euclid's Algorithm
Explanation: Euclid's algorithm computes the GCD of two numbers by repeatedly replacing the
larger number with its remainder when divided by the smaller number, until one of the numbers
becomes zero.
Approach:
• Input: a = 56, b = 98
• Output: GCD = 14
Example 2:
• Input: a = 14, b = 49
• Output: GCD = 7
Explanation: The least common multiple of two numbers is the smallest number that is divisible
by both. It can be calculated using the relation LCM(a, b) = (a * b) / GCD(a, b).
Approach:
• Compute the GCD of two numbers using Euclid's algorithm, then compute the LCM using the
formula.
Time Complexity: O(log(min(a, b)))
Example 1:
• Input: a = 12, b = 15
• Output: LCM = 60
Example 2:
• Input: a = 9, b = 6
• Output: LCM = 18
Explanation: The factors of a number n are the numbers that divide n completely. To find all
factors, we iterate from 1 to √n and for every i that divides n, both i and n/i are factors.
Approach:
• For every i from 1 to √n, check if n % i == 0. If true, both i and n/i are factors.
• Input: n = 28
• Output: Factors = [1, 2, 4, 7, 14, 28]
Example 2:
• Input: n = 36
• Output: Factors = [1, 2, 3, 4, 6, 9, 12, 18, 36]
Approach:
• Use binary search to find if there exists an integer x such that x^2 == n, or use a mathematical
check like sqrt(n).
Time Complexity: O(log n) using binary search or O(1) using sqrt.
Example 1:
• Input: n = 25
• Output: true (25 is a perfect square)
Example 2:
• Input: n = 20
• Output: false (20 is not a perfect square)
Explanation: The factorial of a number n is the product of all positive integers less than or equal
to n. It is represented as n!.
Approach:
• Input: n = 5
• Output: 5! = 5 * 4 * 3 * 2 * 1 = 120
Example 2:
• Input: n = 3
• Output: 3! = 6
Approach:
• Input: n = 4
• Output: C(4) = 14
Example 2:
• Input: n = 5
• Output: C(5) = 42
Matrix exponentiation can be used to find the nth Fibonacci number in logarithmic time using
the transformation matrix:
Approach:
• Input: n = 5
• Output: Fibonacci(5) = 5
Example 2:
• Input: n = 10
• Output: Fibonacci(10) = 55
Example 2:
Approach:
• Input: n = 10
• Output: Trailing Zeroes = 2
Example 2:
• Input: n = 100
• Output: Trailing Zeroes = 24
Approach:
• Compute x using the formula: x=∑(ai⋅Mi⋅Ni)mod Mx = \sum (a_i \cdot M_i \cdot N_i) \mod
Mx=∑(ai⋅Mi⋅Ni)modM where Mi=MmiM_i = \frac{M}{m_i}Mi=miM, and NiN_iNi is the modular
inverse of MiM_iMi modulo mim_imi.
Explanation: Given a set of activities with start and end times, select the maximum number of
activities that don't overlap.
Approach:
• Input: Activities = [(1, 3), (2, 5), (4, 6), (6, 8)]
• Output: Maximum activities = 3
Example 2:
Explanation: Huffman coding is a lossless data compression algorithm that assigns variable-
length binary codes to characters based on their frequencies.
Approach:
Example 2:
Explanation: Given jobs with deadlines and profits, schedule the jobs to maximize the total
profit such that no two jobs overlap.
Approach:
• Input: Jobs = [(profit = 20, deadline = 2), (profit = 15, deadline = 2), (profit = 10, deadline = 1)]
• Output: Maximum profit = 35
Example 2:
• Input: Jobs = [(profit = 100, deadline = 2), (profit = 19, deadline = 1)]
• Output: Maximum profit = 100
Explanation: Given arrival and departure times of trains, determine the minimum number of
platforms required so that no train waits.
Approach:
Example 2:
Explanation: Given a set of coin denominations and a total amount, the problem is to find the
minimum number of coins needed to make up that amount. If it’s not possible to make that
amount, return -1.
Approach:
• Use dynamic programming to create an array where each index represents the minimum coins
required for that amount.
• For each coin, update the array based on previous values.
Time Complexity: O(n * m) where n is the amount and m is the number of coin types.
Example 1:
Example 2:
Explanation: Given a set of intervals, the goal is to select the maximum number of non-
overlapping intervals.
Approach:
• Input: Intervals = [(1, 2), (2, 3), (3, 4), (0, 6)]
• Output: Maximum intervals = 4
Example 2:
Explanation: The N-Queens problem is to place N queens on an N×N chessboard so that no two
queens threaten each other.
Approach:
• Use backtracking to place queens in a column-by-column fashion, checking for conflicts with
previously placed queens.
• Input: N = 4
• Output: Solutions = 2 (different arrangements)
Example 2:
• Input: N = 8
• Output: Solutions = 92 (different arrangements)
Explanation: The Sudoku puzzle is a 9×9 grid that needs to be filled with digits from 1 to 9 such
that each row, column, and 3×3 subgrid contains all digits without repetition.
Approach:
• Use backtracking to try filling the grid. If you find a valid configuration, continue; if not,
backtrack.
Example 2:
Explanation: Given a set of elements, the goal is to generate all possible subsets (the power set).
Approach:
Example 2:
Approach:
Example 2:
Explanation: Given a maze represented as a grid, where 1s represent paths and 0s represent
walls, find a path from the top-left corner to the bottom-right corner.
Approach:
• Use backtracking to explore all possible paths. Keep track of the visited cells to avoid cycles.
• Input: Maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [0, 1, 1, 1]]
• Output: Path = [(0,0), (1,0), (1,1), (2,1), (3,1), (3,2), (3,3)]
Example 2:
Explanation: Given a 2D board of letters and a word, determine if the word exists in the grid by
moving horizontally or vertically.
Approach:
• Use backtracking to explore all possible paths in the grid starting from each cell.
• Input: Board = [['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']], Word = "ABCCED"
• Output: Word found = true
Example 2:
• Input: Board = [['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']], Word = "SEE"
• Output: Word found = true
Explanation: The Knight's Tour is a classic problem where a knight must visit every square on a
chessboard exactly once.
Approach:
• Use backtracking to move the knight across the board, ensuring it doesn’t revisit any square.
Example 2:
Explanation: Given a set of integers, determine if there is a subset whose sum equals a given
target.
Approach:
• Use backtracking to explore all possible subsets and check if their sum matches the target.
Example 2:
Explanation: The M-coloring problem involves coloring the vertices of a graph using at most M
colors such that no two adjacent vertices share the same color.
Approach:
• Use backtracking to assign colors to vertices. For each vertex, try each color and recursively
check if it leads to a solution.
Example 2:
Explanation: The Hamiltonian Path problem seeks a path in a graph that visits each vertex
exactly once.
Approach:
• Use backtracking to explore paths from the starting vertex. If you visit all vertices, you've found a
Hamiltonian path.
Example 2:
Explanation: Given an array, the task is to find duplicates and return them.
Approach:
• Use a hash set to keep track of seen elements. For each element, check if it’s already in the set.
Example 2:
Explanation: Given two arrays, the goal is to find the common elements (intersection) between
them.
Approach:
• Use a hash set to store elements of the first array, then iterate through the second array to check
for common elements.
Example 2:
Explanation: Given an array containing n-1 integers in the range from 1 to n, find the missing
integer.
Approach:
• Use the formula for the sum of the first n integers and subtract the sum of the elements in the
array from it.
Example 2:
Explanation: Given an array of size n, the majority element is the element that appears more
than n/2 times.
Approach:
Example 2:
Explanation: The task is to count the number of 1s in the binary representation of a number.
Approach:
• Use bit manipulation. Continuously check if the last bit is 1 and right shift the number.
Example 2:
Explanation: Given an unsorted integer array, find the smallest positive integer that is missing.
Approach:
• Use a hash set to store positive integers and check for the smallest missing one.
Example 2:
Approach:
• Use a nested loop to construct each row based on the values from the previous row.
Time Complexity: O(n^2)
Example 1:
• Input: numRows = 5
• Output:
csharp
Copy code
[
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]
]
Example 2:
• Input: numRows = 3
• Output:
csharp
Copy code
[
[1],
[1, 1],
[1, 2, 1]
]
Approach:
• Iterate through the stream and maintain a reservoir of size k. For each new element, decide
whether to include it in the reservoir based on a probability.
Example 2:
Explanation: Given two linked lists, determine the node where they intersect. If they do not
intersect, return null.
Approach:
• Calculate the lengths of both lists, find the difference, and then traverse both lists in sync to find
the intersection.
Time Complexity: O(n + m) where n and m are the lengths of the lists.
Example 1:
Example 2: