Search for a Value in a Linked List
Implement searchInLinkedList
Given the
head of a singly linked list and an integer target, return true if target appears anywhere in the list, and false otherwise.
Unlike an array, a linked list gives no random access — the only way to reach any node is by walking next pointers from head, so a linear scan is unavoidable, sorted or not. Both an iterativeIterativeSolved with an explicit loop, keeping state (like a curr pointer) in local variables instead of the call stack. Runs in O(1) extra space here. pass with a curr pointer and a recursiveRecursiveSolved by having the function call itself on a smaller version of the same problem — here, "search the rest of the list" is the same problem as the original, just one node shorter. version that checks head and calls itself on head.next do exactly this walk; the recursive version just spends O(n) call-stack space doing it.
Example 1:
Input: head = [4,9,2,7], target = 2
Output: true
Example 2:
Input: head = [4,9,2,7], target = 5
Output: false
Example 3:
Input: head = [], target = 1
Output: false
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 10⁴ - ●
-10⁹ ≤ node value, target ≤ 10⁹ - ●
Searching an empty list must return false, not an error
head =
[4, 9, 2, 7]
target =
2