Brute Force

Melike Kilic
2 min readAug 24, 2020

--

Lately, I’ve been spending some time on Algorithm questions for the interviews, and I have decided to write about what I’ve learned about the Brute Force approach so far for this blog post.

What Is It?

Brute Force is the most straightforward approach to the algorithm questions where you go through each possibility until you find a satisfactory solution.

Let’s say you forgot your car keys in your car, and the doors got locked. (This happened to me last week, that’s where I got the inspiration from for this example.)

It would help if you had a way to unlock the doors to get the keys since you don’t own any backup keys. After some googling, you found out some ways that could help to unlock the car. Unfortunately, they didn’t work.

You were about to lose hope until you recalled you could use auto jigglers and see if they’ll fix the problem. You ordered them real quick. Now all you need to do is trying out each one of the keys until you find one that will work for your car’s door. A little troublesome, but it works. That’s how I’d describe Brute Force to someone who doesn’t have any idea about it.

Example:

Let’s take a look at an example.

LeetCode, Two Sum exercise

In this example, we are asked to return the indices of two numbers, whose sum will give us the target.

This kind of question is the perfect fit for the Brute Force approach since we can iterate over each element until we find one that matches our desired solution.

What we can do is going over each element of the numbers array using a for loop and creating another loop inside the first one so that it can check the next element in the array to see if their sum is equal to the target. (Ignore my variable naming, i & k. It’d make more sense to name them i & j.)

After that, we can push the elements that match our condition into the empty array that we created before the loops. This approach is simple and widely applicable. It doesn’t provide efficiency, though.

The Brute Force approach can be improved by using heuristics(flexibility technique for quick decisions, mainly when working with complex data) and optimization(elimination of particular possibilities without fully exploring them).

Check out the next blog post, which will be about the Binary Search approach!

--

--

Melike Kilic
Melike Kilic

No responses yet