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.
(1 → 2 → 3), 2 // → true
(1 → 2 → 3), 9 // → false
(empty), 5 // → false
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.
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.
true immediately — no need to look further.false.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.
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."
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.
def linked_list_find(head, target):
node = head
while node is not None:
if node.val == target:
return True
node = node.next
return False
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.