Back to practice

Minimize a wrong-match reproduction

Difficulty: Easy

Python

Try your first run

No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.

  1. Read the examples and the required return value.
  2. Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
  3. Use the test feedback to try again. Hints are available without replacing your code.

Sign in to save items for review and keep private notes.

Repair solve(values, target) to return the last zero-based index whose value equals target, or -1 if no value matches. Preserve the input sequence and return an index rather than the matching value.

Understand the failure

The starter finds the first occurrence. A sequence with only one match cannot expose the error because its first and last matching indices are identical. To reproduce the bug, keep at least two occurrences of the target.

Work through an example

For [2, 1, 2] with target 2, matching indices are 0 and 2. The required result is 2; returning 0 finds the wrong occurrence. Shrink the input to [2, 2]: the expected result becomes 1, and the same defect remains.

Edge cases to check

  • An empty sequence returns -1.
  • A nonempty sequence with no match also returns -1.
  • A match at index zero is a successful result.
  • Repeated targets and targets at the final position distinguish first-match from last-match behavior.

Python details

list.index returns the first matching index and raises ValueError when the value is absent. The starter guards against absence but still chooses the wrong occurrence. Python equality uses ==; preserve original index positions rather than reversing the input list in place.

Regression task

Predict the starter result for [7, 7] with target 7, then compare it with the contract. After repairing, retain that minimal failing example alongside empty, absent, and index-zero cases.

Examples

[2, 1, 2], 22
[], 1-1
[0], 00

Constraints

Inputs are JSON-compatible. Unless a tighter bound is stated, lists have at most 200 elements, strings at most 1000 characters, and integers are within -1000000..1000000. Do not mutate inputs. Use only the browser runner; no file or network access. Preserve the required function signature.

Review lesson: Build a minimal reproduction
Python

Ready when you are

Write your solution, then run it against the practice tests.

Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.

Reset your code?

This replaces your current code with the starter and stops any running tests.