Linked List Find

Linked List Find

Return true if a target value appears anywhere in the linked list, false otherwise.

linkedListFind(head, target)

Input format: list | target — space-separated node values, a pipe, then the target.

Examples

(1 → 2 → 3), 2   // → true
(1 → 2 → 3), 9   // → false
(empty), 5       // → false

Walkthrough

Thinking it through

Searching a linked list for a target is conceptually simple, but it's worth being precise about why the straightforward approach is also the optimal one — and how "stop once you know the answer" differs from problems like sum or count, where you must visit every node.

The key insight: you can stop early

Unlike summing or counting, a search can be answered the moment you find a match — no need to keep looking once the target is confirmed present. Some traversal problems require a full pass no matter what; others let you exit early. Recognizing which kind you're facing tells you whether early-return logic is worth adding.

Building the approach

  1. Start a pointer at the head.
  2. While the pointer points to a real node, compare its value to the target.
  3. If it matches, return true immediately — no need to look further.
  4. If not, advance and try the next node.
  5. If the pointer runs off the end without a match, the target genuinely isn't in the list — return false.

Why both exit points are necessary

There are exactly two ways this can end: you find the target partway through, or you finish the whole list without finding it. You can't decide "false" halfway — the target might still appear later. "Not found" only holds once you've genuinely run out of nodes.

The empty list

An empty list can never contain the target, and this resolves automatically: the loop body never runs, so you fall straight through to "not found."

Why this is as good as it gets

In the worst case — target missing, or at the very end — you still look at every node once, so this is O(n) and there's no way around that lower bound for an unsorted, singly linked structure: without random access or ordering to exploit, you can't skip nodes you haven't examined. But the early return means best- and average-case performance is often much better in practice.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.