← DiffPush

Search element in linked list

Baseline Linked List · Single Linked List O(N) · O(1)

Checking the Manifest One Car at a Time

A yard clerk must confirm whether a shipment code rides anywhere on a one-way chained train. There is no index to jump to — the only option is to step through each car and compare its label with the code, answering yes the moment one matches and no when the chain runs out.

Input: An integer n, an array arr of n node values, and an integer key.

Output: true when key appears in the list, false otherwise.

Constraints

Examples

Example 1

Input: {"n":4,"arr":[1,2,3,4],"key":3}
Output: true
The walk reaches the third car and finds 3.

Example 2

Input: {"n":3,"arr":[1,2,3],"key":9}
Output: false
The chain ends without a single match, so the answer is false.

Solve this in your browser →

Also on LeetCode ↗