0% found this document useful (0 votes)
30 views50 pages

Project Explanation

Uploaded by

Govand Zangana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views50 pages

Project Explanation

Uploaded by

Govand Zangana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

The projects cover a range of topics, including searching, dynamic programming, graph theory,

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.

1. Find the k-th Smallest Element in an Array

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

• Time Complexity: O(n log n)

Approach 2: Quickselect (similar to Quicksort)

• Time Complexity: O(n) on average.

Example 1:

• Input: arr = [7, 10, 4, 3, 20, 15], k = 3


• Output: 7 (The 3rd smallest element is 7)

Example 2:

• Input: arr = [7, 10, 4, 20, 15], k = 4


• Output: 15

2. Find the Median of Two Sorted Arrays


Explanation: Given two sorted arrays, the goal is to find the median value. The naive approach
would be to merge both arrays and then find the median. However, an optimal approach uses a
binary search on the smaller array to partition the arrays efficiently.

Approach:

• Time Complexity: O(log(min(n, m))), where n and m are the sizes of the arrays.

Example 1:

• Input: arr1 = [1, 3], arr2 = [2]


• Output: 2.0 (Median is 2)

Example 2:

• Input: arr1 = [1, 2], arr2 = [3, 4]


• Output: 2.5 (Median is 2.5)

3. Find First and Last Occurrence of an Element in a Sorted Array

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:

• Time Complexity: O(log n)

Example 1:

• Input: arr = [5, 7, 7, 8, 8, 10], target = 8


• Output: First occurrence = 3, Last occurrence = 4

Example 2:

• Input: arr = [5, 7, 7, 8, 8, 10], target = 6


• Output: [-1, -1] (Element not found)

4. Find the Peak Element in an Array

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:

• Time Complexity: O(log n)

Example 1:

• Input: arr = [1, 2, 3, 1]


• Output: 2 (Index 2 is a peak because 3 is greater than both neighbors)

Example 2:

• Input: arr = [1, 2, 1, 3, 5, 6, 4]


• Output: 5 (Index 5 is a peak because 6 is greater than neighbors 5 and 4)

5. Reverse a String Using Recursion

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:

• Input: str = "hello"


• Output: "olleh"

Example 2:

• Input: str = "algorithm"


• Output: "mhtirogla"

6. Check if a String is a Palindrome

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.

Approach 1: Using Two Pointers

• Time Complexity: O(n)


Approach 2: Using Recursion

• Time Complexity: O(n)

Example 1:

• Input: str = "madam"


• Output: true

Example 2:

• Input: str = "hello"


• Output: false

7. Find the Longest Common Prefix Among Strings

Explanation: Given an array of strings, the task is to find the longest common prefix (if any).

Approach: Vertical scanning or binary search.

• Time Complexity: O(S), where S is the sum of all characters in all strings.

Example 1:

• Input: strs = ["flower", "flow", "flight"]


• Output: "fl"

Example 2:

• Input: strs = ["dog", "racecar", "car"]


• Output: "" (No common prefix)

8. Longest Palindromic Substring

Explanation: Given a string, the task is to find the longest substring that is a palindrome.

Approach: Dynamic Programming or Expand Around Center.

• Time Complexity: O(n^2)


Example 1:

• Input: str = "babad"


• Output: "bab" or "aba"

Example 2:

• Input: str = "cbbd"


• Output: "bb"

9. Find if Two Strings Are Anagrams

Explanation: Two strings are anagrams if they contain the same characters with the same
frequencies.

Approach: Use a frequency counter or sorting.

• Time Complexity: O(n)

Example 1:

• Input: str1 = "listen", str2 = "silent"


• Output: true

Example 2:

• Input: str1 = "hello", str2 = "world"


• Output: false

10. String Matching Using KMP Algorithm

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.

Approach: Precompute the "Longest Prefix Suffix" (LPS) array.

• Time Complexity: O(n + m), where n is the length of the text, and m is the length of the pattern.
Example 1:

• Input: text = "abcxabcdabcdabcy", pattern = "abcdabcy"


• Output: Pattern found at index 8

Example 2:

• Input: text = "aaaaaaa", pattern = "aaa"


• Output: Pattern found at indices 0, 1, 2, 3, 4

11. Rabin-Karp Algorithm for Substring Search

Explanation: Rabin-Karp is a rolling hash-based algorithm used for pattern searching. It


compares the hash values of the pattern and substrings in the text, which allows skipping most
comparisons.

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:

• Average case: O(n + m)


• Worst case: O(n * m) (when all hashes match)

Example 1:

• Input: text = "abcdef", pattern = "bcd"


• Output: Pattern found at index 1

Example 2:

• Input: text = "abcdef", pattern = "xyz"


• Output: Pattern not found

12. Z-Algorithm for Pattern Matching

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:

1. Concatenate the pattern and the text.


2. Compute the Z-array.
3. Find positions where the Z-value equals the length of the pattern.

Time Complexity: O(n + m)


Example 1:

• Input: text = "abcxabcdabcdabcy", pattern = "abcdabcy"


• Output: Pattern found at index 8

Example 2:

• Input: text = "aabxaayaab", pattern = "aab"


• Output: Pattern found at index 0 and 7

13. Find All Permutations of a String

Explanation: The task is to find all possible permutations of a given string. This is typically
solved using backtracking.

Approach:

1. Swap characters recursively to generate all possible permutations.


2. Base case: When the string is completely traversed, store the result.

Time Complexity: O(n!)


Example 1:

• Input: str = "abc"


• Output: ["abc", "acb", "bac", "bca", "cab", "cba"]

Example 2:

• Input: str = "ab"


• Output: ["ab", "ba"]

14. Find the First Non-Repeating Character in a String

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.

Time Complexity: O(n)


Example 1:

• Input: str = "geeksforgeeks"


• Output: f (First non-repeating character)

Example 2:

• Input: str = "aabb"


• Output: None (No non-repeating characters)

15. Fibonacci Sequence Using Dynamic Programming

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:

1. Use an array to store Fibonacci numbers.


2. Compute each Fibonacci number by using the two previous numbers.

Time Complexity: O(n)


Example 1:

• 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

16. Longest Increasing Subsequence (LIS)


Explanation: The task is to find the length of the longest subsequence in an array such that all
elements of the subsequence are in increasing order.

Approach:

• Use dynamic programming to store the length of the LIS ending at each element.
• Update the length based on previous elements.

Time Complexity: O(n²)


Example 1:

• Input: arr = [10, 22, 9, 33, 21, 50, 41, 60, 80]
• Output: 6 (The LIS is [10, 22, 33, 50, 60, 80])

Example 2:

• Input: arr = [3, 10, 2, 1, 20]


• Output: 3 (The LIS is [3, 10, 20])

17. Longest Common Subsequence (LCS)

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.

Time Complexity: O(n * m)


Example 1:

• Input: str1 = "ABCBDAB", str2 = "BDCAB"


• Output: 4 (The LCS is "BDAB")

Example 2:

• Input: str1 = "AGGTAB", str2 = "GXTXAYB"


• Output: 4 (The LCS is "GTAB")

18. Edit Distance Problem


Explanation: Edit Distance measures how many operations (insertions, deletions, or
substitutions) are needed to convert one string into another.

Approach:

• Use dynamic programming to store the edit distances in a 2D table.

Time Complexity: O(n * m)


Example 1:

• Input: str1 = "kitten", str2 = "sitting"


• Output: 3 (Convert "kitten" to "sitting" by substituting 'k' with 's', 'e' with 'i', and adding 'g')

Example 2:

• Input: str1 = "flaw", str2 = "lawn"


• Output: 2 (Convert "flaw" to "lawn" by deleting 'f' and substituting 'w' with 'n')

19. Minimum Number of Coins for a Given Sum

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:

• Input: coins = [1, 2, 5], sum = 11


• Output: 3 (11 can be made with three coins: 5, 5, 1)

Example 2:

• Input: coins = [2, 5, 10], sum = 6


• Output: None (It's not possible to make 6)

20. Word Break Problem


Explanation: Given a string and a dictionary of words, the task is to determine if the string can
be segmented into a space-separated sequence of dictionary words.

Approach:

• Use dynamic programming to check if each substring can be formed using words from the
dictionary.

Time Complexity: O(n²)


Example 1:

• Input: str = "leetcode", dict = ["leet", "code"]


• Output: true ("leetcode" can be segmented as "leet code")

Example 2:

• Input: str = "applepenapple", dict = ["apple", "pen"]


• Output: true ("applepenapple" can be segmented as "apple pen apple")

21. Partition Problem (Subset Sum)

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:

• If the total sum is odd, it’s impossible to partition the set.


• Use dynamic programming to check if there exists a subset with a sum equal to half of the total
sum.

Time Complexity: O(n * sum), where n is the number of elements, and sum is the total sum of the array.
Example 1:

• Input: arr = [1, 5, 11, 5]


• Output: true (The array can be partitioned into subsets [1, 5, 5] and [11])

Example 2:

• Input: arr = [1, 2, 3, 5]


• Output: false (No equal partition)
22. Egg Dropping Problem

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:

• Use dynamic programming to solve this problem.


• The recursive relation is based on trying every possible floor and determining if the egg breaks
or doesn't break.

Time Complexity: O(k * n²)


Example 1:

• Input: k = 2, n = 6
• Output: 3 (You need at least 3 attempts)

Example 2:

• Input: k = 3, n = 14
• Output: 4

23. Maximum Subarray Sum (Kadane's Algorithm)

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.

Time Complexity: O(n)


Example 1:

• Input: arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]


• Output: 6 (Maximum subarray is [4, -1, 2, 1])

Example 2:

• Input: arr = [1]


• Output: 1
24. Minimum Path Sum in a Grid

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:

• Input: grid = [[1,3,1], [1,5,1], [4,2,1]]


• Output: 7 (The minimum path is 1 → 3 → 1 → 1 → 1, sum = 7)

Example 2:

• Input: grid = [[1,2,3], [4,5,6]]


• Output: 12 (The minimum path is 1 → 2 → 3 → 6, sum = 12)

25. Unique Paths in a Grid

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:

• Use dynamic programming or combinatorics to calculate the number of unique paths.

Time Complexity: O(m * n)


Example 1:

• 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.

Time Complexity: O(n²)


Example 1:

• Input: lengths = [1, 2, 3, 4], prices = [2, 5, 7, 8], n = 4


• Output: 10 (Best cut is 2 + 2, total price = 5 + 5)

Example 2:

• Input: lengths = [1, 2, 3, 4, 5], prices = [2, 5, 7, 8, 9], n = 5


• Output: 12

27. Implement Depth-First Search (DFS)

Explanation: Depth-First Search is a graph traversal algorithm that explores as far as possible
along a branch before backtracking.

Approach:

• Implement DFS using either recursion or an explicit stack.

Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
Example 1:

• Input: Graph: 0 → 1 → 2 → 3, start vertex = 0


• Output: 0 1 2 3

Example 2:

• Input: Graph: 1 → 2 → 0 → 3, start vertex = 2


• Output: 2 0 3 1
28. Implement Breadth-First Search (BFS)

Explanation: BFS is a graph traversal algorithm that explores all neighbors of a vertex before
moving to the next level of vertices.

Approach:

• Implement BFS using a queue.

Time Complexity: O(V + E)


Example 1:

• Input: Graph: 0 → 1 → 2 → 3, start vertex = 0


• Output: 0 1 2 3

Example 2:

• Input: Graph: 1 → 2 → 0 → 3, start vertex = 2


• Output: 2 0 3 1

29. Find Connected Components in a Graph

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.

Time Complexity: O(V + E)


Example 1:

• Input: Graph with edges 0-1, 1-2, 3-4


• Output: 2 (Two connected components: {0,1,2} and {3,4})

Example 2:

• Input: Graph with edges 0-1, 2-3


• Output: 2 (Two connected components: {0,1} and {2,3})

30. Detect a Cycle in a Graph (DFS/BFS)


Explanation: The task is to detect if there is a cycle in an undirected or directed graph.

Approach:

• For undirected graphs, use DFS and track the parent of each vertex.
• For directed graphs, use DFS and maintain a recursion stack.

Time Complexity: O(V + E)


Example 1:

• Input: Graph with edges 0-1, 1-2, 2-0


• Output: true (Cycle exists)

Example 2:

• Input: Graph with edges 0-1, 1-2


• Output: false (No cycle)

31. Topological Sort of a Directed Acyclic Graph (DAG)

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.

Time Complexity: O(V + E)


Example 1:

• Input: graph = [[1, 2], [2, 3], [3], []]


• Output: 0 1 2 3 (Topological order)

Example 2:

• Input: graph = [[1], [2], []]


• Output: 0 1 2

32. Dijkstra's Algorithm for Shortest Path


Explanation: Dijkstra’s algorithm is used to find the shortest path from a source node to all
other nodes in a weighted graph with non-negative weights.

Approach:

• Use a priority queue to explore the graph, always expanding the node with the smallest known
distance first.

Time Complexity: O((V + E) * logV)


Example 1:

• 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]

33. Bellman-Ford Algorithm for Shortest Path

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.

Time Complexity: O(V * E)


Example 1:

• 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.

Time Complexity: O(V³)


Example 1:

• 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:

• Input: graph = [[0, 2, INF], [INF, 0, 1], [3, INF, 0]]


• Output:

[[0, 2, 3],
[4, 0, 1],
[3, 5, 0]]

35. Prim's Algorithm for Minimum Spanning Tree

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.

Time Complexity: O((V + E) * logV)


Example 1:

• 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)]

36. Kruskal's Algorithm for Minimum Spanning Tree

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.

Time Complexity: O(E * logE)


Example 1:

• Input: edges = [(0, 1, 10), (0, 2, 6), (1, 2, 5)]


• Output: MST edges: [(1, 2), (0, 2)]

Example 2:

• Input: edges = [(0, 1, 2), (1, 2, 3), (0, 2, 4)]


• Output: MST edges: [(0, 1), (1, 2)]

37. Find Strongly Connected Components (Tarjan's Algorithm)

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.

Time Complexity: O(V + E)


Example 1:

• Input: graph = {0: [1], 1: [2], 2: [0], 1: [3], 3: [4]}


• Output: SCCs: [[4], [3], [0, 1, 2]]
Example 2:

• Input: graph = {0: [1], 1: [2], 2: []}


• Output: SCCs: [[0], [1], [2]]

38. Find Bridges in a Graph

Explanation: A bridge (or cut-edge) is an edge in an undirected graph whose removal increases
the number of connected components.

Approach:

• Use DFS to find bridges based on discovery and low values.

Time Complexity: O(V + E)


Example 1:

• Input: graph = {0: [1], 1: [2], 2: [3], 3: [4], 4: []}


• Output: Bridges: [(2, 3), (3, 4)]

Example 2:

• Input: graph = {0: [1], 1: [2], 2: [0]}


• Output: Bridges: [] (No bridges)

39. Find Articulation Points in a Graph

Explanation: An articulation point is a vertex in an undirected graph that, if removed, increases


the number of connected components.

Approach:

• Use DFS to compute discovery and low values to find articulation points.

Time Complexity: O(V + E)


Example 1:

• Input: graph = {0: [1, 2], 1: [0, 2], 2: [0, 3], 3: [2]}
• Output: Articulation points: [2]
Example 2:

• Input: graph = {0: [1], 1: [0, 2], 2: [1]}


• Output: Articulation points: [1]

40. Bipartite Graph Checking

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.

Time Complexity: O(V + E)


Example 1:

• Input: graph = {0: [1], 1: [0, 2], 2: [1]}


• Output: true (Graph is bipartite)

Example 2:

• Input: graph = {0: [1, 2], 1: [0, 2], 2: [0, 1]}


• Output: false (Graph is not bipartite)

41. Network Flow Problem (Ford-Fulkerson Algorithm)

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

42. Find the Shortest Path in a Maze

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

43. Binary Tree Traversal (In-order, Pre-order, Post-order)

Explanation: Tree traversal means visiting all nodes in a tree in a specific order.

Approach:

• In-order: Left → Root → Right


• Pre-order: Root → Left → Right
• Post-order: Left → Right → Root

Time Complexity: O(n)


Example 1 (In-order):

• Input: tree = [1, 2, 3, 4, 5, 6, 7]

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

44. Level Order Traversal of a Binary Tree

Explanation: Level order traversal visits nodes level by level starting from the root.

Approach:

• Use a queue to process each level of the tree in order.

Time Complexity: O(n)


Example 1:

• Input: tree = [1, 2, 3, 4, 5, 6, 7]

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.

Time Complexity: O(n)


Example 1:

• Input:

markdown
1
/ \
2 3
/
4

• Output: true (Tree is balanced)

Example 2:

• Input:

markdown
1
/
2
/
3

• Output: false (Tree is not balanced)

46. Find the Height of a Binary Tree

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

47. Find the Diameter of a Binary Tree

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.

Time Complexity: O(n)


Example 1:

• Input:

markdown
1
/ \
2 3
/ \
4 5
• Output: Diameter = 4 (path: 4 → 2 → 1 → 3)

Example 2:

• Input:

markdown
1
/
2
/ \
3 4

• Output: Diameter = 3 (path: 3 → 2 → 1)

48. Lowest Common Ancestor in a Binary Tree

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.

Time Complexity: O(n)


Example 1:

• 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

49. Check if a Binary Tree is a Binary Search Tree (BST)

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).

Time Complexity: O(n)


Example 1:

• Input:

markdown
2
/ \
1 3

• Output: true (Tree is a BST)

Example 2:

• Input:

markdown
5
/ \
2 4

• Output: false (Tree is not a BST)

50. Find the Kth Smallest/Largest Element in a BST


Explanation: The k-th smallest/largest element in a BST can be found by performing an in-order
traversal (for smallest) or reverse in-order traversal (for largest).

Approach:

• Perform an in-order traversal and keep track of the count of nodes visited.

Time Complexity: O(k)


Example 1 (k-th smallest):

• Input:

markdown
3
/ \
1 4
\
2

k=2

• Output: 2

Example 2 (k-th largest):

• Input:

markdown
5
/ \
3 7
/ \
2 4

k=3

• Output: 5

51. Convert a Binary Tree into a Doubly Linked List

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.

Time Complexity: O(n)


Example:

• Input:

markdown
1
/ \
2 3
/ \
4 5

• Output: Doubly linked list: 4 ⇄ 2 ⇄ 5 ⇄ 1 ⇄ 3

52. Serialize and Deserialize a Binary Tree

Explanation: Serialization is converting a binary tree into a string, and deserialization is


converting that string back into the original tree.

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.

Time Complexity: O(n)


Example:

• Input:

markdown
1
/ \
2 3
/ \
4 5

• Serialized Output: 1,2,4,#,#,5,#,#,3,#,#


• Deserialized Output: Tree structure as given.
53. Find the Maximum Path Sum in a Binary Tree

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.

Time Complexity: O(n)


Example:

• Input:

markdown
-10
/ \
9 20
/ \
15 7

• Output: Maximum path sum = 42 (path: 15 → 20 → 7)

54. Inorder Successor in a Binary Search Tree (BST)

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.

Time Complexity: O(h) where h is the height of the tree.


Example 1:

• Input:

markdown
20
/ \
8 22
/ \
4 12

Node = 8

• Output: In-order successor = 12

Example 2:

• Input: Node = 12
• Output: In-order successor = 20

55. Check if a Number is Prime

Explanation: A number is prime if it has no divisors other than 1 and itself.

Approach:

• Check divisibility by numbers from 2 to √n. If divisible by any of these, it’s not prime.

Time Complexity: O(√n)


Example 1:

• Input: n = 11
• Output: true (11 is prime)

Example 2:

• Input: n = 12
• Output: false (12 is not prime)

56. Generate Prime Numbers Using Sieve of Eratosthenes

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:

• GCD(a, b) = GCD(b, a % b) until b = 0.

Time Complexity: O(log(min(a, b)))


Example 1:

• Input: a = 56, b = 98
• Output: GCD = 14

Example 2:

• Input: a = 14, b = 49
• Output: GCD = 7

58. Find the Least Common Multiple (LCM)

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

59. Find All Factors of a Number

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.

Time Complexity: O(√n)


Example 1:

• 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]

60. Check if a Number is a Perfect Square

Explanation: A number is a perfect square if there exists an integer x such that x * x = n.

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)

61. Implement a Factorial Function

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:

• Use recursion: n! = n * (n-1)! with base case 0! = 1.


• Alternatively, you can implement it using an iterative loop.

Time Complexity: O(n)


Example 1:

• Input: n = 5
• Output: 5! = 5 * 4 * 3 * 2 * 1 = 120

Example 2:

• Input: n = 3
• Output: 3! = 6

62. Find nth Catalan Number

Explanation: Catalan numbers are a sequence of natural numbers with applications in


combinatorial mathematics. The nth Catalan number is given by the formula:
C(n)=(2n)!(n+1)!n!C(n) = \frac{(2n)!}{(n+1)!n!}C(n)=(n+1)!n!(2n)!

Approach:

• Use the direct formula or dynamic programming to avoid recomputation.


Time Complexity: O(n)
Example 1:

• Input: n = 4
• Output: C(4) = 14

Example 2:

• Input: n = 5
• Output: C(5) = 42

63. Find nth Fibonacci Number Using Matrix Exponentiation

Explanation: The Fibonacci sequence is defined as:


F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1.

Matrix exponentiation can be used to find the nth Fibonacci number in logarithmic time using
the transformation matrix:

[1110]\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}[1110]

Approach:

• Use matrix exponentiation to calculate Fibonacci numbers in O(log n).

Time Complexity: O(log n)


Example 1:

• Input: n = 5
• Output: Fibonacci(5) = 5

Example 2:

• Input: n = 10
• Output: Fibonacci(10) = 55

64. Modular Exponentiation

Explanation: Modular exponentiation calculates (base^exponent) % mod efficiently,


especially for large numbers.
Approach:

• Use the method of exponentiation by squaring. If exponent is even, use:


baseexponent=(baseexponent/2)2mod modbase^{exponent} = (base^{exponent/2})^2 \mod
modbaseexponent=(baseexponent/2)2modmod If odd:
baseexponent=base×baseexponent−1mod modbase^{exponent} = base \times base^{exponent-
1} \mod modbaseexponent=base×baseexponent−1modmod

Time Complexity: O(log exponent)


Example 1:

• Input: base = 3, exponent = 5, mod = 7


• Output: Result = (3^5) % 7 = 5

Example 2:

• Input: base = 2, exponent = 10, mod = 1000


• Output: Result = 24

65. Find the Number of Trailing Zeroes in a Factorial

Explanation: The number of trailing zeroes in n! is determined by the number of times 10 is a


factor in n!. Since 10 = 2 × 5, and there are always more factors of 2 than 5, the problem reduces
to counting the number of factors of 5 in n!.

Approach:

• Count the number of multiples of 5, 25, 125, etc., in the factorial.

Time Complexity: O(log n)


Example 1:

• Input: n = 10
• Output: Trailing Zeroes = 2

Example 2:

• Input: n = 100
• Output: Trailing Zeroes = 24

66. Chinese Remainder Theorem Implementation


Explanation: The Chinese Remainder Theorem provides a way to solve systems of simultaneous
congruences with different moduli.

Given a system of congruences: x≡a1(modm1), x≡a2(modm2),… x≡ak(modmk)x \equiv a_1


\pmod{m_1}, \, x \equiv a_2 \pmod{m_2}, \dots \, x \equiv a_k \pmod{m_k}x≡a1(modm1
),x≡a2(modm2),…x≡ak(modmk)

It finds the unique solution x modulo the product of all moduli.

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.

Time Complexity: O(k log m)


Example:

• Input: x≡2(mod3), x≡3(mod5), x≡2(mod7)x \equiv 2 \pmod{3}, \, x \equiv 3 \pmod{5}, \, x \equiv


2 \pmod{7}x≡2(mod3),x≡3(mod5),x≡2(mod7)
• Output: x = 23 (Solution mod 105)

67. Activity Selection Problem

Explanation: Given a set of activities with start and end times, select the maximum number of
activities that don't overlap.

Approach:

• Sort activities by their finishing times.


• Select the first activity, and for each subsequent activity, if its start time is greater than or equal
to the end time of the last selected activity, select it.

Time Complexity: O(n log n)


Example 1:

• Input: Activities = [(1, 3), (2, 5), (4, 6), (6, 8)]
• Output: Maximum activities = 3

Example 2:

• Input: Activities = [(1, 2), (3, 4), (5, 6)]


• Output: Maximum activities = 3
68. Huffman Coding for File Compression

Explanation: Huffman coding is a lossless data compression algorithm that assigns variable-
length binary codes to characters based on their frequencies.

Approach:

• Build a frequency table for characters.


• Construct a binary tree where each character is a leaf node, and the path from the root to the
leaf determines the character's code.
• Use a priority queue to build the tree.

Time Complexity: O(n log n)


Example 1:

• Input: String = "abbccc"


• Output: Huffman codes: {'a': '00', 'b': '01', 'c': '1'}

Example 2:

• Input: String = "aaaabbc"


• Output: Huffman codes: {'a': '0', 'b': '10', 'c': '11'}

69. Job Sequencing Problem

Explanation: Given jobs with deadlines and profits, schedule the jobs to maximize the total
profit such that no two jobs overlap.

Approach:

• Sort the jobs in decreasing order of profit.


• Use a greedy algorithm to find the latest possible time slot for each job.

Time Complexity: O(n log n)


Example 1:

• 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

70. Minimum Number of Platforms Needed at a Railway Station

Explanation: Given arrival and departure times of trains, determine the minimum number of
platforms required so that no train waits.

Approach:

• Sort the arrival and departure times.


• Use a greedy approach to count the maximum number of trains at the station at any given time.

Time Complexity: O(n log n)


Example 1:

• Input: Arrivals = [9:00, 9:40, 9:50], Departures = [9:10, 12:00, 11:20]


• Output: Minimum platforms = 2

Example 2:

• Input: Arrivals = [9:00, 9:05], Departures = [9:10, 9:15]


• Output: Minimum platforms = 1

71. Coin Change Problem (Minimum Coins)

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:

• Input: coins = [1, 2, 5], amount = 11


• Output: Minimum coins = 3 (5 + 5 + 1)

Example 2:

• Input: coins = [2], amount = 3


• Output: Minimum coins = -1 (not possible)

72. Interval Scheduling Maximization

Explanation: Given a set of intervals, the goal is to select the maximum number of non-
overlapping intervals.

Approach:

• Sort the intervals by their end times.


• Use a greedy algorithm to select intervals, ensuring that each selected interval starts after the
last selected one ends.

Time Complexity: O(n log n)


Example 1:

• Input: Intervals = [(1, 2), (2, 3), (3, 4), (0, 6)]
• Output: Maximum intervals = 4

Example 2:

• Input: Intervals = [(1, 3), (2, 4), (3, 5)]


• Output: Maximum intervals = 2

73. N-Queens Problem

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.

Time Complexity: O(N!)


Example 1:

• Input: N = 4
• Output: Solutions = 2 (different arrangements)

Example 2:

• Input: N = 8
• Output: Solutions = 92 (different arrangements)

74. Sudoku Solver

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.

Time Complexity: O(9^(n^2)) in the worst case


Example 1:

• Input: Partially filled Sudoku


• Output: Completed Sudoku solution

Example 2:

• Input: Another partially filled Sudoku


• Output: Completed Sudoku solution

75. Generate All Subsets of a Set

Explanation: Given a set of elements, the goal is to generate all possible subsets (the power set).
Approach:

• Use backtracking or iterative methods to generate subsets by including or excluding each


element.

Time Complexity: O(2^n)


Example 1:

• Input: Set = {1, 2}


• Output: Subsets = { {}, {1}, {2}, {1, 2} }

Example 2:

• Input: Set = {a, b, c}


• Output: Subsets = { {}, {a}, {b}, {c}, {a, b}, {a, c}, {b, c}, {a, b, c} }

76. Generate All Permutations of a Set

Explanation: Given a set of distinct elements, generate all possible arrangements


(permutations).

Approach:

• Use backtracking to swap elements and generate permutations recursively.

Time Complexity: O(n!)


Example 1:

• Input: Set = {1, 2}


• Output: Permutations = { {1, 2}, {2, 1} }

Example 2:

• Input: Set = {a, b, c}


• Output: Permutations = { {a, b, c}, {a, c, b}, {b, a, c}, {b, c, a}, {c, a, b}, {c, b, a} }

77. Rat in a Maze Problem

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.

Time Complexity: O(4^(n^2)) in the worst case


Example 1:

• 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:

• Input: Another maze with no path


• Output: No path exists

78. Word Search in a Grid

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.

Time Complexity: O(m * n * 4^L) where L is the length of the word


Example 1:

• 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

79. Knight's Tour Problem

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.

Time Complexity: O(8^(n^2))


Example 1:

• Input: Board size = 8


• Output: Solution exists

Example 2:

• Input: Smaller board size = 5


• Output: Solution exists

80. Subset Sum Problem Using Backtracking

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.

Time Complexity: O(2^n)


Example 1:

• Input: Set = {3, 34, 4, 12, 5, 2}, Target = 9


• Output: Subset found = {4, 5}

Example 2:

• Input: Set = {1, 2, 3, 4, 5}, Target = 10


• Output: Subset found = {2, 3, 5}

81. M-Coloring Problem (Graph Coloring)

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.

Time Complexity: O(M^V) where V is the number of vertices.


Example 1:

• Input: Graph with 4 vertices and M = 3 colors.


• Output: Coloring possible = true (e.g., 1: Red, 2: Green, 3: Red, 4: Green)

Example 2:

• Input: Graph with 4 vertices and M = 2 colors.


• Output: Coloring possible = false

82. Hamiltonian Path Problem

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.

Time Complexity: O(n!)


Example 1:

• Input: Graph with vertices {A, B, C, D}.


• Output: Hamiltonian path found = A -> B -> C -> D

Example 2:

• Input: Graph that cannot be traversed in a single path.


• Output: Hamiltonian path found = false

83. Find Duplicates in an Array

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.

Time Complexity: O(n)


Example 1:

• Input: Array = [1, 2, 3, 1, 2]


• Output: Duplicates = [1, 2]

Example 2:

• Input: Array = [5, 6, 7, 8]


• Output: Duplicates = []

84. Find the Intersection of Two Arrays

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.

Time Complexity: O(n + m)


Example 1:

• Input: Array 1 = [1, 2, 2, 1], Array 2 = [2, 2]


• Output: Intersection = [2]

Example 2:

• Input: Array 1 = [4, 9, 5], Array 2 = [9, 4, 9, 8, 4]


• Output: Intersection = [4, 9]

85. Find Missing Number in an Array of n-1 Elements

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.

Time Complexity: O(n)


Example 1:

• Input: Array = [3, 7, 1, 2, 8, 4], n = 8


• Output: Missing number = 5

Example 2:

• Input: Array = [1], n = 2


• Output: Missing number = 2

86. Find the Majority Element in an Array

Explanation: Given an array of size n, the majority element is the element that appears more
than n/2 times.

Approach:

• Use the Boyer-Moore Voting Algorithm or a hash map to count occurrences.

Time Complexity: O(n)


Example 1:

• Input: Array = [3, 2, 3]


• Output: Majority element = 3

Example 2:

• Input: Array = [2, 2, 1, 1, 1, 2, 2]


• Output: Majority element = 2

87. Count the Number of Set Bits in a Number

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.

Time Complexity: O(log n)


Example 1:

• Input: n = 5 (binary: 101)


• Output: Set bits = 2

Example 2:

• Input: n = 7 (binary: 111)


• Output: Set bits = 3

88. Find the Smallest Missing Positive Integer

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.

Time Complexity: O(n)


Example 1:

• Input: Array = [3, 4, -1, 1]


• Output: Smallest missing positive integer = 2

Example 2:

• Input: Array = [1, 2, 0]


• Output: Smallest missing positive integer = 3

89. Generate Pascal’s Triangle

Explanation: Pascal's Triangle is a triangular array of the binomial coefficients.

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]
]

90. Reservoir Sampling Algorithm

Explanation: Reservoir sampling is a randomized algorithm for selecting a sample of k items


from a population of size n.

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.

Time Complexity: O(n)


Example 1:

• Input: Stream = [1, 2, 3, 4, 5], k = 3


• Output: Random sample of size 3, e.g., [2, 4, 5]

Example 2:

• Input: Stream = [5, 6, 7, 8, 9], k = 2


• Output: Random sample of size 2, e.g., [5, 7]

91. Find the Intersection Point of Two Linked Lists

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:

• Input: List 1: 1 -> 2 -> 3 -> 4, List 2: 6 -> 3 -> 4 (intersection at 3)


• Output: Intersection point = 3

Example 2:

• Input: List 1: 1 -> 2 -> 3, List 2: 4 -> 5


• Output: Intersection point = null

You might also like