Skip to content

Fix 0/1 Knapsack traceback crash and incorrect item selection#2109

Open
danielalanbates wants to merge 1 commit intotrekhleb:masterfrom
danielalanbates:fix/issue-248
Open

Fix 0/1 Knapsack traceback crash and incorrect item selection#2109
danielalanbates wants to merge 1 commit intotrekhleb:masterfrom
danielalanbates:fix/issue-248

Conversation

@danielalanbates
Copy link

Summary

Fixes two bugs in solveZeroOneKnapsackProblem() traceback phase:

  1. Crash: knapsackMatrix[itemIndex - 2][weightIndex] accessed out-of-bounds when itemIndex === 1, causing TypeError: Cannot read property of undefined.

  2. Wrong items selected: The traceback pushed prevItem instead of currentItem when including an item, producing incorrect results even when the crash didn't occur.

Changes

Replaced the buggy traceback logic with the standard 0/1 knapsack DP traceback:

  • If dp[i][w] !== dp[i-1][w], item i was included — push it and reduce weight.
  • Added check for item at index 0 after the loop.

Added a test case using the exact input from #248 that previously crashed.

 src/algorithms/sets/knapsack-problem/Knapsack.js              | 28 ++++-----
 src/algorithms/sets/knapsack-problem/__test__/Knapsack.test.js | 17 ++++++

Testing

All 8 tests pass (7 existing + 1 new):

  • should solve 0/1 knapsack problem
  • should solve 0/1 knapsack problem regardless of items order
  • should solve 0/1 knapsack problem with no single-weight-1 item (issue #248) [NEW]
  • should solve 0/1 knapsack problem with impossible items set
  • should solve 0/1 knapsack problem with all equal weights
  • All unbounded knapsack tests

Fixes #248


This PR was created with AI assistance to help this open-source project. Happy to make any adjustments!

The traceback phase of solveZeroOneKnapsackProblem() had two bugs:

1. Accessed knapsackMatrix[itemIndex - 2] without bounds checking,
   causing "Cannot read property of undefined" when itemIndex was 1.

2. Used incorrect logic that pushed prevItem instead of currentItem
   when an item was included, leading to wrong selected items.

Replaced with the standard DP traceback: if dp[i][w] != dp[i-1][w],
item i was included. Also added check for the first item (row 0).

Added test case from issue trekhleb#248 that previously crashed.

Fixes trekhleb#248
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Knapsack has error

1 participant

Comments