Brute Force Algorithms
Brute Force Algorithms refers to a programming style that does not include any shortcuts to improve performance, but instead relies on sheer computing power to try all possibilities until the solution to a problem is found.
A classic example is the traveling salesman problem (TSP). Suppose a salesman needs to visit 10 cities across the country. How does one determine the order in which cities should be visited such that the total distance traveled is minimized? The brute force solution is simply to calculate the total distance for every possible route and then select the shortest one. This is not particularly efficient because it is possible to eliminate many possible routes through clever algorithms.
Some more examples of brute force algorithms are:
- A 5-digit password, in the worst case scenario, would take 105 tries to crack.
- A brute-force algorithm to find the divisors of a natural number n would enumerate all integers from 1 to n, and check whether each of them divides n without remainder.
The time complexity of brute force is O(nm) . So, if we were to search for a string of ‘n’ characters in a string of ‘m’ characters using brute force, it would take O(nm) time.
Generally, brute force approaches should be avoided for more optimal algorithms, especially when the functions using these algorithms will scale to larger and larger numbers. The difference between brute force and optimized algorithms may not be immediately apparent when dealing with smaller numbers and lesser chunks of time, but the difference between a brute-force O(n^3) algorithm and an optimized O(nlog(n)) algorithm becomes very apparent for problems of larger scales.
An example from YouTube HERE .