Computational Problem-Solving Methods
Computational Problem-Solving Methods
The brute-force approach is a fundamental problem-solving technique in which all possible solutions
are systematically tried until the correct one is found. It does not use shortcuts, or optimizations. Instead,
it relies on:
Brute-force is usually easy to understand and implement but becomes inefficient when the number of
possibilities grows large.
Algorithm:
1. Start with 000.
2. Increment sequentially: 001, 002, ..., 999.
3. Stop when the lock opens.
Why brute force works here
Practical understanding
If the correct combination is 572, we will find it after trying all combinations up to 572.
If it is 999, we must try almost all possibilities.
This shows brute force is reliable but may require many attempts.
1. Generating all possible combinations of characters allowed in the password (letters, numbers,
symbols).
• Length: 4 characters
If the correct password is “dbac”, then the attacker must try every combination from aaaa up to dbac.
For example:
This increases the time needed to try all possibilities, making brute-force attacks unrealistic.
Divide and Conquer Algorithm
Divide and Conquer Algorithm is a problem-solving technique used to solve problems by dividing the
main problem into sub-problems, solving them individually and then merging them to find solution to
the original problem.
The Divide and Conquer algorithmic approach consists of three main steps: Divide,
Conquer, and Merge.
1. Divide
• Goal: Break down the original problem into smaller, more manageable subproblems.
• Each subproblem represents a part of the overall problem.
• The division continues recursively until the subproblems are simple enough to solve
directly.
2. Conquer
• Goal: Combine the solutions of the subproblems to form the solution to the original
problem.
• Once the subproblems are solved, their solutions are recursively merged to resolve the
overall problem efficiently.
Example1. Finding the Maximum Element in an Array Using Divide and Conquer
The Divide and Conquer algorithm can efficiently find the maximum element in an array by
following these steps:
• Divide:
• Conquer:
• Once the subarrays have only one element, return that element as the maximum of
that subarray.
• Merge:
• Compare the maximums of the two halves and return the larger value as the maximum
for the combined array.
If the section of the array has only one number, that number is the maximum.
If it has more than one number, split it into two equal parts.
Find the biggest number in the left part (by doing the same steps again).
Find the biggest number in the right part (also by repeating the steps).
Compare the two biggest numbers from each part.
The larger of the two is the maximum for the whole array.
1. Divide: The array is divided into two halves recursively until each subarray has one
element.
2. Sort: Each sub-array is sorted individually.
3. Merge: The sorted sub-arrays are merged to produce a single sorted array.
ALGORITHM
1. Initial Array
[38, 27, 43, 3, 9, 82, 10]
2. First Split
According to the diagram:
Left part:
[38, 27, 43, 3]
Right part:
[9, 82, 10]
5. Final Merge
Now merge the two sorted parts:
• Left sorted: [3, 27, 38, 43]
• Right sorted: [9, 10, 82]
Final merging sequence:
3
9
10
27
38
43
82
Final sorted array:
[3, 9, 10, 27, 38, 43, 82]
Advantages of the Divide and Conquer Approach
1. Reduces Problem Complexity
o By breaking a large problem into smaller subproblems, it becomes easier to
understand, solve, and manage.
o Each subproblem is less complex than the original problem.
2. Improved Performance for Many Problems
o Many algorithms (e.g., Merge Sort, Quick Sort, Binary Search) achieve better
time complexity using divide and conquer.
o This approach often transforms inefficient algorithms into much faster ones.
3. Independent sub problems
o Subproblems are often independent and can be solved simultaneously on multiple
processors.
o This makes divide and conquer suitable for parallel and distributed computing.
4. Reusability of Solutions
o Solutions to subproblems can be applied to similar problems.
PREVIOUS YEAR
You are working as a financial analyst for a bank. The bank has received a list of loan interest
rates from multiple branches, and you need to identify the two lowest rates to recommend the
most cost-effective options to customers. The rates are provided as an array of positive integers,
and your task is to develop an efficient algorithm using the Divide and Conquer approach to find
the sum of the two smallest rates. Explain with a suitable example.
Final Output
Two smallest loan rates:
3 and 5
Sum:
3+5=8
Qn) Illustrate the process of sorting the array [15, 8, 3, 12, 6, 10, 4, 1] using the merge sort algorithm.
Draw a diagram showing how the array is split and merged at each stage. (Do it Yourself)
Dynamic Programming Approach
GENERAL ALORITHM
This makes it much faster than simple recursion when the same subproblems
repeat.
• Uses recursion
• Every time we solve a small problem, we store the result.
• Uses extra memory to store results
• Execution direction: Top → Down
• Avoids repeated calculation of the same subproblem. If we face the same small problem
again, we don’t solve it again — we just look up the stored answer
• Efficient for problems where only some subproblems are needed
⭐ TABULATION (Bottom-Up)
Tabulation means: Start from the easiest problem and build up the answer step
by step.
Start from the big problem (fib(5)), compute answers with recursion, save every fib(k) you
compute, and reuse saved answers so you never compute the same fib value twice.
Assume we start computing fib(5):
1. Compute fib(5) → needs fib(4) and fib(3).
2. Compute fib(4) → needs fib(3) and fib(2).
3. Compute fib(3) → needs fib(2) and fib(1).
4. Compute fib(2) → needs fib(1) and fib(0).
5. Back to fib(3):
now fib(2) is in memo, so reuse memo[2] and fib(1) to get fib(3) = 2.
Save fib(3) = 2.
6. Back to fib(4):
fib(3) is in memo, fib(2) is in memo → fib(4) = 3.
Save fib(4) = 3.
7. Back to fib(5):
fib(4) and fib(3) are now in memo → fib(5) = 5.
Save fib(5) = 5.
So each fib(k) is computed once and all later requests use the saved value.
Without memoization:
• F(3) needs to be calculated many times
• F(4) needs to be calculated many times
•
With memoization:
• Once F(3) = 2 is stored, every future call simply uses the stored value, making the
algorithm much faster.
Fib(5)
Fib(4) Fib(3)
Fib(2) Fib(1)
Fib(3) Fib(2)
Fib(1) Fib(0)
Fib(2) Fib(1) Fib(1) Fib(0)
Fib(1) Fib(0)
How the memo (table) fills for n = 5 (step by step)
Tabulation means:
Start from the smallest problem, fill a table step by step, and
working up to the final answer.
No recursion is used.
Final answer:
fib(6) = 8
Dynamic Programming
Aspect Recursion
(DP)
Solving complex
Solving a problem
problems by breaking
by calling the same
them into smaller
Definition function on smaller
subproblems and saving
parts of the
their results to avoid
problem.
repeating work.
Can be Top-down
Top-down: start
(memoization) or
from the main
Bottom-up (tabulation);
Approach problem and go
deeper into smaller
avoids recmputation by
problems.
storing results.
Essential for Same base cases, but
Base Case stopping recursion stored directly in a table
(e.g., fib(0), fib(1)). or memo.
Can be slow due to Much faster because
repeated each subproblem is
Performance
calculations of the solved only once and
same subproblems. reused.
Time Higher Lower
Complexity Often exponential Usually polynomial or
Dynamic Programming
Aspect Recursion
(DP)
linear
Uses extra table/memo
Uses recursion
Memory array, but avoids large
stack, which can
Usage recursion stacks
grow deep.
(especially in tabulation).
Less efficient when Highly efficient when
Efficiency subproblems repeat subproblems overlap and
many times. results can be reused.
Suitable for
problems with Best for problems with
natural recursive overlapping subproblems
Use Cases
structure and no and optimal
repeated substructure.
subproblems.
When performance
When simplicity is
When to matters and the problem
preferred and input
Use has repeated
size is small.
subproblems.
Fibonacci (DP), Knapsack
Fibonacci (naive problem, Longest
recursion), Tree Common Subsequence,
Examples
traversal, Factorial, Matrix Chain
Tower of Hanoi. Multiplication, Shortest
paths.
PREVIOUS YEAR
A greedy algorithm is a problem-solving approach where you make the best local
choice at each step, hoping it leads to the best overall solution.
A greedy algorithm builds a solution step by step, and at each step it chooses the
option that looks best right now — the local optimum — hoping that repeated
local choices produce a global optimum.
• Locally Optimal Choices: At each step, the algorithm optimizes for the immediate
constraint (time, cost, practicality) without revisiting earlier decisions.
• Global Solution: The sequence of locally optimal decisions leads to an efficient and
practical final solution.
Qn) Given an array of positive integers, each indicating the completion time for a
task, find the maximum number of tasks that can be completed in the limited
amount of time that you have.
Greedy Strategy
To maximize the number of tasks completed:
✔ Always choose the tasks that take the least time first.
This ensures the completion of the maximum number of tasks within your total
time.
Consider:
Completion times for tasks:
[2, 3, 1, 4, 6]
Total available time:
8
Final Answer
✔ Maximum tasks completed = 3
The tasks with times 1, 2, and 3 can be completed within the total available
time 8.
Let’s consider the task of traveling from Thiruvananthapuram to Ernakulam with multiple
available modes of transport: bike, car, bus, train, airplane, or even walking. The goal is to
select the mode of transport based on a set of constraints or objectives:
At each step, the greedy algorithm makes the locally optimal choice by filtering options
based on the immediate constraint.
• Available Options:
o Bike: 6 hours
o Car: 4.5 hours
o Bus: 5 hours
o Train: 3.5 hours
o Airplane: 1 hour
o Walking: 40 hours
Greedy Decision:
Select modes that satisfy the time constraint of reaching as quickly as possible. The airplane
(1 hour) is the fastest, followed by the train (3.5 hours).
Filter Outcome:
Airplane, Train.
Greedy Decision:
Select the train as it is cheaper and satisfies the economical constraint.
Filter Outcome:
Train.
Final Decision
The algorithm selects the train as the final mode of transport based on:
The Coin Changing Problem aims to find the minimum number of coins required to make a
specified amount using valid Indian Rupee coins.
The greedy algorithm repeatedly selects the largest denomination that fits into the remaining
amount.
1. Start with ₹10: Take one ₹10 coin (₹18 - ₹10 = ₹8 left).
2. Next, ₹5: Take one ₹5 coin (₹8 - ₹5 = ₹3 left).
3. Next, ₹2: Take one ₹2 coin (₹3 - ₹2 = ₹1 left).
4. Finally, ₹1: Take one ₹1 coin (₹1 - ₹1 = ₹0 left).
1. Local Optimization
o Makes the best possible choice at each step using only current state
information.
2. Irrevocable Decisions
o Choices are final; no backtracking or revision of earlier decisions.
3. Problem-Specific Heuristics
o Relies on heuristics tailored to the problem's properties for decision-making.
4. Optimality
o Guarantees optimal solutions for problems like coin change, Huffman coding,
and Kruskal's algorithm, but not universally applicable.
5. Efficiency
o High efficiency in time and space due to reliance on local information and
limited exploration of solutions.
Comparison between Dynamic programming and Greedy Approach
• Advantages
• Disadvantages
• Not guaranteed to find the best solution: Greedy algorithms may not find the best
solution because they don't consider all the data.
• Local optima: Greedy algorithms may get stuck in local optima and fail to find the
global optimum.
• Dependence on problem structure: Greedy algorithms may not work well for
problems that don't fit the greedy paradigm.
• Lack of rigorous proof: Greedy algorithms often lack a rigorous proof of correctness
Randomized Approach to Problem Solving
A randomized approach is a method of solving a problem where the algorithm
makes random choices during its process.
These random choices help:
• make the algorithm simpler,
• avoid worst-case situations,
• and sometimes make it faster.
A randomized approach means the algorithm uses “luck” or random numbers to decide what to do next.
• Randomized:
o Incorporates chance.
o Efficient for large, complex, or variable datasets.
o Example: Estimating customer satisfaction via random sampling.
• Deterministic:
o Yields exact, repeatable results.
o Suitable for precision-critical problems.
o Example: Exact cost calculation in shopping.
Qn) A company selling jeans gives a coupon for each pair of jeans. There are n different
coupons. Collecting n different coupons would give you free jeans. How many jeans do you
expect to buy before getting a free one? explain this using randomised approach.
Problem statement
• A company has n different coupons.
• Every time you buy a pair of jeans, you get one coupon chosen at random from the n
coupons.
• Collecting all n different coupons gives you a free pair of jeans.
• Each purchase is independent of the previous ones.
Let
• X = number of jeans needed to get the i-th new coupon after already having 𝑖 −
1coupons.
Second coupon: some coupons are repeats, so it may take a few tries to get a new
one.
E[X2]=(n−1)/n1= (n−1) / n
Third coupon: probability of getting a new one decreases, so you need even more
tries.
E[X3]=(n−2) / n
Last coupon
E[Xn]=1 / n= n
• Add them up:
1. The total expected number of jeans = sum of the expected purchases for all stages.
2. As a result, you usually need more than n purchases.
E[X]=E[X1]+E[X2]+E[X3]+⋯+E[Xn]=n(1+1/2+1/3+⋯+1/n)
E[X]=5(1+1/2+1/3+1/4+1/5)≈5×2.2833≈11.4
Qn) n people go to a party and drop off their hats to a hat-check person. When the party is over,
a different hat-check person is on duty and returns the n hats randomly back to each person.
What is the expected number of people who get back their hats? Explain this using randomized
approach
Problem Statement
• There are n people at a party.
• Each person gives a hat to the hat-check person.
• When they leave, a different hat-check person returns the hats randomly.
• Even though the hats are returned randomly, on average 1 person will get their own hat
back.
• It doesn’t matter how many people there are — the expected number is always 1.
Suppose:
• There are 4 people and 4 hats.
• Everyone gets a hat randomly.
• Check how many got their own hat → sometimes 0, sometimes 2, sometimes more.
• But on average, 1 person will get their own hat.
Person 1 → Hat 1
Person 2 → Hat 2
Person 3 → Hat 3
Person 4 → Hat 4
Person 1 → Hat 3
Person 2 → Hat 2 (correct!)
Person 3 → Hat 1
Person 4 → Hat 4 (correct!)
In this example, 2 people got their own hat, but the number can vary each time. On average
one person gets their hat.
OTHER EXAMPLES
[Link] Problem
Problem: Find the probability that at least two people in a group share the same
birthday.
Randomized Algorithm:
1. For a group of n people, assign a random birthday to each person (1–365).
2. Check if any two birthdays match.
3. Repeat this simulation many times.
4. Record how often at least two birthdays match.
5. Estimate the probability based on these simulations.
Probability ≈ count_matches / total_trials
2. Birthday Problem
• Why Randomized: Birthdays are simulated randomly in a group.
• Randomness is key: Probability is estimated by repeated random trials.
• Type: Randomized simulation to estimate combinatorial probability.