0% found this document useful (0 votes)
63 views11 pages

Brute Force Approach

The document discusses brute force algorithms, which solve problems by exhaustively exploring all possible options, exemplified by scenarios like unlocking a 5-digit code and solving the magic square problem. It also covers linear search, the rain terraces problem, recursive staircase climbing, maximum subarray sum, and the traveling salesman problem, detailing their approaches and time complexities. Each problem illustrates the principles of brute force and provides algorithms for their solutions.

Uploaded by

manojpatil
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)
63 views11 pages

Brute Force Approach

The document discusses brute force algorithms, which solve problems by exhaustively exploring all possible options, exemplified by scenarios like unlocking a 5-digit code and solving the magic square problem. It also covers linear search, the rain terraces problem, recursive staircase climbing, maximum subarray sum, and the traveling salesman problem, detailing their approaches and time complexities. Each problem illustrates the principles of brute force and provides algorithms for their solutions.

Uploaded by

manojpatil
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/ 11

Brute Force Paradigms

A brute force algorithm straightforward methods of solving a problem through exhaustion: it


goes through all possible choices until a solution is found.

The time complexity of a brute force algorithm is often proportional to the input size.

Brute force algorithms are simple and consistent, but very slow.

It simply means that try out all the alternatives until you are exhausted of options. If the problem
is solvable, you will eventually find an answer.

Example 1 of brute force

Let us understand it with a very easy example. Suppose you have a locked folder that can be
opened by a 5-digit lock code. You have no hint about the lock code, but you just want to see
what is behind that lock, what would you do? You would start from 00000 and go all the way
to 99999. If the lock is working correctly, one of the combination would definitely open the lock.
Although it would take some time, but eventually you would be able to solve the problem.
So that is Brute force solution that we applied on above problem.

Example 2 of brute force

Given a 3 * 3 grid, you need to fill in numbers from 1-9 such that sum of all diagonals, rows and
columns is the same. Also note that none of the numbers should be repeated.
We also call it the magic square problem.

You can start of by trying numbers in any fashion, and keep on verifying the sum in all
directions.
Eventually you will reach the correct answer. The sum of every row, column and diagonal is
equal to 15 in this combination of numbers.

There are a total of 362880 total possible ways to fill up the grid.

Linear Search
Linear search is also called as sequential search algorithm. It is the simplest searching algorithm.
In Linear search, we simply traverse the list completely and match each element of the list with
the item whose location is to be found. If the match is found, then the location of the item is
returned; otherwise, the algorithm returns NULL.

It is widely used to search an element from the unordered list, i.e., the list in which items are not
sorted.

Example

Time Complexity:

Best Case: O(1)


Worst Case: O(N)
Average Case: O(N)

Linear Search Algorithm


Rain Terraces
Rain Terraces is a brute force problem where you have to determine the amount of water that can
be trapped in a series of terraces.

Given an array of non-negative integers representing terraces in an elevation map where the
width of each bar is 1, compute how much water it is able to trap after raining.

Examples:

Input: arr[] = {2, 0, 2}

Output: 2
We can trap 2 units of water in the middle gap.
Example
Input: arr[] = {3, 0, 2, 0, 4}
Output: 7
We can trap “3 units” of water between 3 and 2,
“1 unit” on top of bar 2 and “3 units” between 2 and 4.

Example

Input: arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}

Output: 6
Explanation: The structure is like below.
Trap “1 unit” between first 1 and 2, “4 units” between
first 2 and 3 and “1 unit” between second last 1 and last 2

Brute Approach to solve above problem

Traverse every array element and find the highest bars on the left and right sides. Take the
smaller of two heights. The difference between the smaller height and the height of the current
element is the amount of water that can be stored in this array element.

Algorithm
Input : array
Step 1: Traverse the array from start to end:
Step 2 :For every element:
 Traverse the array from start to that index and find the
maximum height (a) and
 Traverse the array from the current index to the end, and
find the maximum height (b).
Step 3: The amount of water that will be stored in this column is
min(a,b) – array[i], add this value to the total amount of water stored
Step 4: Print the total amount of water stored.
Javascript program

Recursive Staircase
There are n stairs, a person standing at the bottom wants to climb stairs to reach the nth stair.
The person can climb either 1 stair or 2 stairs at a time, the task is to count the number of ways
that a person can reach at the top.

The value of n is 3 (i.e. Number of stairs are 3).


There are 3 ways to reach the top.

Input: n = 1
Output: 1 There is only one way to climb 1 stair
Input: n=2
Output: 2 There are two ways: (1, 1) and (2)

Input: n=3
Output:3 There are 3 ways: (1,1,1) and (2,1) and (1,2)

Input: n = 4
Output: 5 (1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2)

Input: n = 5
Output: 8 (1, 1, 1, 1), (1,1, 1, 2), (1,1,2, 1), (1, 2, 1,1),
(2,1,1,1,) , (1,2,2) , (2,1,2) , (2,2,1)

This is also the relation followed by the Fibonacci sequence.


Now we know that our solution follows a Fibonacci sequence , we just need to find out the
termination case or base case, i.e. when recursion end.
The recursion can END if N becomes 0 or 1 , it will return 1 .

Time complexity :O(2^n)


Space complexity O(n)
Algorithm

Program
Maximum Subarray

What is a Subarray?
A subarray is a continuous part of the array which can be made by deleting zero or more
elements from the beginning or can be made by deleting zero or more elements from the end or
both sides.

Example:
Array: [1,3,5,6,2] Example of some subarrays: [1,3,5], [5,6,2], [3,5,6,2], [1], [1,3,5,6,2]

Understanding the problem


You are given an array A[] with n elements. You need to find the maximum sum of a subarray
among all subarrays of that array. A subarray of array A[] of length n is a contiguous segment
from A[i] through A[j] where 0<= i <= j <= n.
Some properties of this problem are:
 If the array contains all non-negative numbers, the maximum subarray is the entire array.
 Several different sub-arrays may have the same maximum sum.

For Example :
Input: A[] = {-5, 8, 9, -6, 10, -15, 3}
Output: 21, the subarray {8, 9, -6, 10} has the maximum sum among all subarrays

Input: A[] = { -4, -7, -1, 5,-2}


Output: 4, the subarray {-1, 5} has the maximum sum

Steps to find Maximum Subarray


1. Generate all subarrays
2. Calculate their sum
3. Print maximum
Algorithm
Input :array A
maxSubarraySum(A,n)
{
max_sum=0
for (i=0 to n-1)
{
sum=0
for (j=i to n-1)
{
sum=sum+A[j]
if(sum>max_sum)
max_sum=sum
}
}
return max_sum

Program
Travelling Salesman Problem
Travelling Salesman Problem is based on a real life scenario, where a salesman from a company
has to start from his own city and visit all the assigned cities exactly once and return to his home
till the end of the day.
The exact problem statement goes like this,

"Given a set of cities and distance between every pair of cities, the problem is to find the shortest
possible route that visits every city and returns to the starting point."

Let us consider a graph G=(V,E), where V is a set of cities and E is a set of weighted edges.
An edge e(u,v) represents that vertices u &v are connected.
Distance between vertex u & v is d(u,v) which should be non-negative.
Examine all possible permutations of cities and keep the one that is shortest.
It turns out that there are exactly
n!=1*2*3…*n different permutations.
Since we only care about permutations that start with 0 , to solve an city TSP instance with brute
force requires exactly
n-1 different permutations
For example
N=4 , so we require (n-1)!
(n-1)!=(4-1)!=3!=1*2*3=6 permutations

Example 1
Example 2

TSP Algorithm

TSP Algorithm

You might also like