Launch your tech mastery with us—your coding journey starts now!
Course Content
Data Structure

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.

Simple illustration of Brute Force approach showing a robotic hammer smashing locks, representing trying all possible combinations to find the correct solution.

How it Works

  1. List every possibility.
  2. Check each one.
  3. 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 (Python)

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))

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.