Brute Force
Definition
Brute Force is the most straightforward, simple approach to solving a problem. It tries every single possible solution until it finds the correct one. It is guaranteed to find the answer, but it is often very slow. 
How it Works
- List every possibility.
- Check each one.
- If it works, print it. If not, move to the next.
Real-World Analogy
Cracking a 4-Digit Padlock: You forgot your code.
- You try 0000. Doesn’t work.
- You try 0001. Doesn’t work.
- You try 9999. Eventually, you will open the lock, but it might take forever.
Example
Problem: Find if the number 7 exists in an array. Array: [10, 50, 7, 9, 2] Logic: Check index 0 (10? No). Check index 1 (50? No). Check index 2 (7? Yes!).
Code Example
PythonJavaCC++
# Linear (Brute Force) Search
def brute_force_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return f"Found at index {i}"
return "Not found"
nums = [10, 20, 30, 40]
print(brute_force_search(nums, 30))
public class LinearSearch {
static String bruteForceSearch(int arr[], int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target)
return "Found at index " + i;
}
return "Not found";
}
public static void main(String[] args) {
int nums[] = {10, 20, 30, 40};
System.out.println(bruteForceSearch(nums, 30));
}
}
#include <stdio.h>
void bruteForceSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
printf("Found at index %d\n", i);
return;
}
}
printf("Not found\n");
}
int main() {
int nums[] = {10, 20, 30, 40};
bruteForceSearch(nums, 4, 30);
return 0;
}
#include <iostream>
using namespace std;
string bruteForceSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target)
return "Found at index " + to_string(i);
}
return "Not found";
}
int main() {
int nums[] = {10,20,30,40};
cout << bruteForceSearch(nums, 4, 30);
return 0;
}
Complexity Analysis
- Time Complexity: O(N) for linear search, but often O(N^2) (nested loops) or O(2^N) (exponential) for complex problems.
- Space Complexity: O(1) usually.
Use Cases
- Testing: Used as a baseline to check if an optimized algorithm is correct.
- Small Data: Perfect for small inputs (e.g., an array of size 10) where optimization is unnecessary.