Genetic Algorithm (Knapsack) Theory Guide

Try the Genetic Algorithm (Knapsack) Solver →
Intermediate12 min readLast Updated June 26, 2026
Prerequisites:Genetic Algorithm Basics, Constraint Logic
Genetic AlgorithmKnapsack ProblemConstrained OptimizationPenalty FunctionFitnessChromosomes

Picture being a thief breaking into a vault with a single backpack. The goal is stealing the most valuable items possible, but the bag has a strict physical weight limit. Pack too much, and the bag rips, leaving nothing at all. This algorithm breeds entire populations of packing lists to discover the absolute most profitable survival combination.

  • Binary Decisions: Every candidate solution is encoded as a binary string. A 11 means that specific item gets packed into the bag, and a 00 means it stays behind, left out of the heist entirely.
  • The Brutal Constraint: Unlike One Max, simply having more 11s is dangerous here. If a string's total item weight exceeds the limit, it receives a massive penalty or a fitness of 00, instantly killing it off from the breeding pool.
  • Evolutionary Breeding: The algorithm takes the most profitable, surviving bags and mixes their item lists together through crossover, occasionally swapping a random item in or out through mutation, continuously hunting for the perfect balance.

One Max taught the basic evolutionary engine, but Knapsack is the real exam. Mastering this shows exactly how algorithms handle strict, real-world constraints without breaking down entirely.

How to Trace a Knapsack Generation by Hand

1

Decode & Evaluate Initial Fitness: Counting the 11s no longer works here. For every 11 in the binary string, look at the item table, add its physical weight to a running total, and check it against the bag's constraint limit. If the total weight exceeds capacity, instantly cross it out and write down a fitness of 00. Only if the weight is valid can the financial benefits be summed up to get the actual fitness score for that chromosome.

2

Selection (Rank Descending): The population must be re-ordered strictly from highest fitness to lowest to build the new mating pool. Any overweight bags that received a 00 fitness automatically sink to the absolute bottom of the list. They are structurally dead and will not be selected for primary crossover, ensuring only valid, genuinely profitable genetic traits get passed forward into the next generation's breeding pool.

3

Execute Crossover (Mating): Look at the explicit rules provided, like 'Cross New #1 and #2 after Bit 3.' Draw a hard vertical line down through both chosen strings on the scratch paper at the exact cut point. Physically swap the tail ends to create two brand new children. The crossover logic itself is mathematically identical to One Max, completely blind to the weights and benefits hiding underneath each bit.

4

Apply Targeted Mutation: Locate the exact child and bit position specified by the rule. Cross out the old number and flip it (010\rightarrow1 or 101\rightarrow0). Exam Trap: flipping a 00 to a 11 means magically packing an extra item into the bag without warning. This can instantly turn a perfectly valid, profitable child into an overweight failure on the very next step of the trace.

5

Final Constraint Check & Fitness: The brand new children strings must be decoded all over again from scratch. Map every 11 back to the item table, calculate the new total weights, and enforce the constraint limit one more time. Any mutated child that is now overweight gets ruthlessly assigned a 00. This proves exactly how fragile highly optimized solutions can be against random genetic mutations introduced late in the process.

The Gatekeeper Rule: Fitness & Penalties

f(x)={BiifWiWmax0ifWi>Wmaxf(x)=\begin{cases}\sum B_i&\text{if}\sum W_i\leq W_{max}\\0&\text{if}\sum W_i>W_{max}\end{cases}

Breaking Down the Formula

  • Bi\sum B_i is the heist value, and Wi\sum W_i is the bag load. Both are calculated using only the items flagged with a 11 in the binary string — a 00 means that item stays behind entirely. Adding up every 11-flagged item's benefit produces the total heist value; adding up every 11-flagged item's weight produces the total bag load carried.
  • WmaxW_{max} represents the bag capacity, the hard physical limit nothing can exceed. The formula first checks whether the bag load, Wi\sum W_i, stays at or below that capacity. If the check passes, the fitness score simply becomes the heist value, Bi\sum B_i. No bonus, no penalty — just a straightforward sum of whatever made it into the bag legally.
  • The Overweight Penalty is the brutal half of this formula. If the bag load exceeds WmaxW_{max}, the bag physically rips, and the algorithm assigns a fitness of exactly 00. Even a bag worth a million dollars in benefit is worth nothing the moment it tears. There is no partial credit here — overweight bags die instantly, regardless of how profitable they could have been.

Solved Example: Tracing a Knapsack Generation

Assume an exam gives a Knapsack problem with 4 items and a strict max weight limit of 15. The items are: Item 1 (Benefit 10, Weight 5), Item 2 (B:15, W:10), Item 3 (B:8, W:4), and Item 4 (B:5, W:3). The starting population is P1=1100P_1=1100, P2=0111P_2=0111, P3=1010P_3=1010, and P4=0011P_4=0011. The rules: sort descending, cross the top two parents after Bit 2, and mutate Child 1 at Bit 4 (using 1-based indexing).

Step 1: Evaluate Initial Fitness

Decode P1P_1 (11001100) to get Weight 15, Benefit 25 — exactly at the limit, so it survives. Decode P2P_2 (01110111) to get Weight 17. Since 17 exceeds the 15 limit, P2P_2 is overweight and instantly receives a fitness of 00. Decode P3P_3 (10101010) for Weight 9, Benefit 18. Decode P4P_4 (00110011) for Weight 7, Benefit 13.

Step 2: Selection (Rank Descending)

Re-order the population from highest to lowest fitness. P1P_1 (fitness 25) becomes New #1. P3P_3 (fitness 18) becomes New #2. P4P_4 (fitness 13) becomes New #3. The overweight P2P_2 (fitness 00) mathematically sinks to the absolute bottom of the breeding pool and gets completely ignored for the primary crossover step.

Step 3: Execute Crossover

Cross New #1 (110011|00) and New #2 (101010|10) right after Bit 2. Child 1 (C1C_1) takes the front of Parent 1 and the tail of Parent 2, becoming 11101110. Child 2 (C2C_2) takes the front of Parent 2 and the tail of Parent 1, becoming 10001000. Both children are produced purely mechanically, blind to weight or benefit.

Step 4: Apply Targeted Mutation

Look at the specific mutation rule: 'Mutate Child 1 at Bit 4.' Take C1C_1, currently 11101110. The very last bit is a 00. Cross it out on the scratch paper and manually flip it to a 11. The newly mutated C1C_1 becomes 11111111, now attempting to pack every single item in the table.

Step 5: Calculate Final Fitness

Decode the brand new children. C1C_1 (11111111) now attempts to pack every single item, creating a massive weight of 22. This shatters the limit, dropping its fitness strictly to 00. C2C_2 (10001000) packs only Item 1, scoring a valid fitness of 10. The mutation trap successfully ruined C1C_1 entirely.

Watch the Evolution Unfold

Manual tracing is the best way to learn, but the visual solver is the best way to verify speed. Watch how the algorithm naturally kills off overweight bags and breeds profit in real time.

Rules & Common Mistakes

  • Exam Trap: Children Do Not Inherit Their Parents' Fitness
    A common mistake is assuming a child inherits its parents' fitness score directly. Every single child must be re-decoded from scratch, with weight and benefit calculated entirely fresh. A parent being 'Valid' has zero bearing on the child — the moment a mutation flips a single bit, that same child could become instantly 'Overweight' and collapse straight to a fitness of 00.
  • Lab Trap: Don't Confuse Bit Position with Item Index
    Mixing up the bit position with the item index is a silent, sneaky error. If the rule says 'Bit 3,' the correct row to check is 'Item 3' in the table — nothing else. Looking at the wrong table row makes the benefit and weight math 100% wrong, silently corrupting the entire rest of the trace without ever throwing an obvious error to catch it.
  • Pro Tip: Don't 'Fix' a Zero Fitness Score
    Seeing a fitness score of 00 often triggers panic, leading students to assume they calculated incorrectly and start adjusting bits to fix it. A 00 is a completely valid, correct score for an overweight bag — nothing needs fixing. Own that 00 confidently, write it down exactly as calculated, and move on to the next generation without doubting the underlying math.
  • Pro Tip: Draw the 'Capacity Line' Before Tallying Anything
    Losing track of the max weight limit mid-tally is an easy way to lose marks. Write the 'Max Weight Limit' at the top of the scratch paper in a big box before starting any calculations. For every chromosome, write the total weight calculation right next to its binary string. If the total exceeds the limit, circle the resulting 00 in bold ink to avoid accidentally reselecting that parent later.

Strengths, Weaknesses & When To Use It

When to use it:Reach for this when constraint satisfaction is the entire game — a massive item table paired with a strict weight limit where trying every single combination would crash the computer. On an exam, this is the right tool when the question asks for a 'near-optimal' selection of items that respects the bag's capacity, rather than demanding an exact mathematical proof of the single best possible answer.

Advantages

  • Penalty-Based Constraint Handling: Standard solvers need fancy calculus to handle a weight limit; this algorithm just assigns a fitness of 00 to any bag that breaks the rules. It turns a hard mathematical constraint into a simple biological filter, letting the algorithm naturally learn to avoid heavy items without ever needing to understand the underlying complex algebra driving the actual optimization problem.
  • Naturally Handles Combinatorial Complexity: With nn items, there are 2n2^n possible combinations to consider. As nn grows, brute force becomes flatly impossible. This algorithm thrives here precisely because it never tries to check every combination. It navigates the profit-versus-weight trade-off by keeping only the survivors, filtering through billions of packing possibilities to find high-value bags that fit perfectly within the limit.

Disadvantages

  • The 'Invalid Bag' Waste: A huge portion of the algorithm's computation gets spent killing off overweight bags. Because mutation randomly adds items, children that are instantly invalid get created constantly. On an exam, remember this inefficiency: the algorithm often spends more effort generating broken bags than it does actually improving the profitable ones, making it a genuinely messy process compared to cleaner dynamic programming approaches.
  • High Sensitivity to Weight-to-Benefit Ratios: If item benefits correlate perfectly with weight, where heavy items are always worth more, the algorithm can get lazy and consistently pick the same boring items. It struggles to find the 'hidden gem' items that are light but highly valuable if the initial population doesn't happen to sample them early. It isn't smart about the items — it's only as smart as the population diversity allows.

Genetic Algorithm vs. Dynamic Programming

Genetic Algorithms are the fast and flexible survivor; Dynamic Programming is the mathematically perfect but slow specialist. Both solve the exact same Knapsack problem, but they approach it from entirely opposite philosophies. DP methodically explores every possible state to guarantee the single best answer exists somewhere in its table. GA breeds, mutates, and gambles its way toward a 'good enough' answer, trading mathematical certainty for raw speed and scalability.

  • Guarantees — Good Enough vs. Provably Optimal: A Genetic Algorithm finds 'good enough' solutions quickly through trial and error, breeding toward improvement over generations. Dynamic Programming guarantees the single, absolute optimal solution by methodically exploring every possible state combination. On an exam, if the question demands certainty, DP wins outright. If the question accepts a strong approximation in exchange for speed, GA becomes the practical choice instead.
  • Computational Scaling — Memory Wall vs. Graceful Degradation: Dynamic Programming hits a brutal memory wall as the bag's weight capacity and item count grow, since its table size explodes combinatorially. A Genetic Algorithm can handle massive item tables where DP would run out of RAM entirely, by sacrificing mathematical perfection for raw speed and a fixed, predictable memory footprint regardless of problem size.
  • Problem Flexibility — Messy Rules vs. Rigid Formulas: A Genetic Algorithm handles messy real-world constraints, like minimum profit requirements or item dependencies, with relative ease — just adjust the fitness function. Dynamic Programming requires building a completely new, complex state-transition formula for every tiny change in the problem rules, making it brittle and labor-intensive whenever the underlying constraints shift even slightly.
  • Exam Context — Which One Does the Question Want? If the question explicitly asks for the 'optimal value' or proof of correctness, Dynamic Programming is the intended answer. If the question instead asks how to scale to 1,000-plus items or manage changing, messy constraints, Genetic Algorithms become the expected and correct response on the exam paper.

Implementation Pseudocode

// GENETIC ALGORITHM — Solving the Knapsack Problem
// Goal: evolve bit-strings representing packed items toward maximum
// profit, without ever exceeding the bag's maximum weight limit.

FUNCTION knapsackGA(popSize, itemTable, maxWeight, maxGenerations):

    // ── INITIALIZATION ──
    population = []
    FOR i = 1 TO popSize:
        chromosome = generateRandomBitString(LENGTH(itemTable))
        population.add(chromosome)
    END FOR
    // Each chromosome is a random pack/leave decision for every item.
    // No smart packing yet — evolution figures that out over time.

    generation = 0

    // ── MAIN GENERATION LOOP ──
    WHILE generation < maxGenerations:

        // ── STEP 1: FITNESS EVALUATION (THE GATEKEEPER) ──
        FOR EACH chromosome IN population:

            totalWeight = 0
            totalBenefit = 0

            FOR EACH bit, index IN chromosome:
                IF bit == 1:
                    totalWeight  = totalWeight  + itemTable[index].weight
                    totalBenefit = totalBenefit + itemTable[index].benefit
                END IF
            END FOR
            // Map every 1 back to the item table to find its weight
            // and benefit. A 0 means that item never gets touched.

            // Exam Trap: ALWAYS check capacity before trusting benefit.
            IF totalWeight > maxWeight:
                chromosome.fitness = 0
                // The bag physically rips. It does not matter how high
                // totalBenefit is — overweight bags get a flat 0, no
                // partial credit, no exceptions, no rounding mercy.
            ELSE:
                chromosome.fitness = totalBenefit
            END IF

        END FOR

        // ── STEP 2: SELECTION ──
        SORT population BY fitness DESCENDING
        // Overweight chromosomes (fitness 0) sink straight to the bottom
        // and effectively get excluded from the primary mating pool.

        // ── STEP 3: CROSSOVER ──
        newPopulation = []
        FOR EACH pair of top parents IN population:
            cutPoint = chooseCutPoint(LENGTH(itemTable))
            child1 = parent1.head(cutPoint) + parent2.tail(cutPoint)
            child2 = parent2.head(cutPoint) + parent1.tail(cutPoint)
            // Crossover is mechanically identical to One Max — it swaps
            // tails blindly, with zero awareness of weight or benefit.
            newPopulation.add(child1)
            newPopulation.add(child2)
        END FOR

        // ── STEP 4: MUTATION ──
        FOR EACH child IN newPopulation:
            FOR EACH bit IN child:
                IF randomChance() < mutationRate:
                    FLIP bit (0 becomes 1, or 1 becomes 0)
                END IF
            END FOR
        END FOR
        // Exam Trap: flipping a 0 to a 1 silently adds an item to the
        // bag. A child that was perfectly valid before mutation can become
        // instantly overweight. Never assume a child's fitness carries
        // over from its parent — it must be re-evaluated from scratch.

        // ── STEP 5: POPULATION REPLACEMENT ──
        population = newPopulation
        generation = generation + 1

    END WHILE

    RETURN the chromosome WITH the highest fitness FOUND across all generations

END FUNCTION

Time & Space Complexity

ScenarioTime ComplexitySpace ComplexityNotes
Overall Time (Generations)O(GPL)O(G\cdot P\cdot L)O(PL)O(P\cdot L)Here GG is generations, PP is population, and LL is chromosome length. Unlike One Max, every fitness check now requires iterating through the item table to sum weights and benefits. While the big-O looks identical to simpler problems, the hidden constant factor is much higher because decoding each bag takes extra work.
Memory Efficiency (Space)O(PL)O(P\cdot L)O(PL)O(P\cdot L)The Genetic Algorithm remains a hero for system RAM. It only ever stores the current generation and the new children, regardless of how many items sit in the table. While Dynamic Programming would crash system memory building a massive table, this algorithm keeps the memory footprint perfectly flat, stable, and predictable.
The Selection BottleneckO(PlogP)O(P\log P)O(P)O(P)Just like in One Max, the biggest physical speed bump is sorting the population to choose parents. Even with lightning-fast fitness decoding, once population size PP gets massive, the sorting algorithm dominates total execution time. It remains the silent killer of performance in every Genetic Algorithm implementation.

Summary

Knapsack proved exactly how to turn a hard constraint into a biological filter, simply assigning a fitness of 00 to any invalid, overweight bag. The evolutionary engine stays identical to One Max underneath, but the penalty mechanism for breaking the rules is what actually solves real-world engineering problems. Moving from simple bit-counting to navigating complex, constrained optimization means full readiness for any real-world optimization exam now lies within reach.

Knapsack Genetic Algorithm Questions Students Always Get Wrong

  • Why do I give an overweight bag a fitness of 0 instead of just removing it?

    The algorithm needs a fixed population size to maintain the breeding structure throughout every generation. Removing it would break the loop logic entirely. A 00 acts as a dead chromosome that naturally gets filtered out by the selection sort, keeping the trace consistent with the required population count.

  • My mutation flip turned a valid bag into an overweight one. Did I make a mistake?

    This is a classic mutation trap, not a calculation error. Mutation is blind and has no awareness of weights whatsoever. If a manual trace shows a valid bag turning overweight after a single bit-flip, the trace is being done perfectly. Keep going and trust the process.

  • Do I really need to decode the child's fitness if I already know the parents?

    Yes, always. Crossover and mutation change which items get packed, so every child must be treated as a fresh, unknown entity. Re-decoding from the item table for every single child is the only reliable way to catch mutations that secretly cross the capacity threshold unnoticed.

  • I keep using the wrong item weight — what's the best way to avoid this?

    Looking at the wrong table row is a common slip. Physically point at the item table with a pen for every bit that reads a 11. Never do the lookups purely in the head. Cross-reference the bit-index with the table index carefully before adding any numbers together.

  • If two bags have the same weight, how do I break the tie?

    If weights tie, the tie-breaker becomes the benefit score. If both weight and benefit tie exactly, keep them in their original presented order. Never invent new rules on the fly. If the professor provides no tie-break rule, document the assumption clearly on the exam paper.

Core University Curriculum

This algorithm and its manual calculation methods are foundational requirements in leading Computer Science and Software Engineering programs worldwide. You will find this topic heavily featured in the syllabi of these standard AI courses:

Explore Related Algorithms