Workspace

Problem workspace

3 day streakD

Traversal & Search

EasyLinked ListsBasics

The challenge

Find the first node with a target value and return its zero-based index, or −1 if absent.

The input is an acyclic singly linked list.

Example

[4, 7, 2, 9], target 2 → index 2.

Use the walkthrough below to inspect the input and each state change.

See Traversal, step by step

Follow the pointers. Watch each link change.

4 nodes · singly linkedIDs = node identity · ∅ = null
Target found: Read the inputIDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links. Node positions stay fixed while arrows change. The pointer strip and node table below give the same state in text.head4A17A22A39A4∅
CurrentResultYellow arrow: changed next link
headA1
Inspect node links
Each row is a distinct node object. D is the dummy sentinel.
NodeValueNext
A14A2
A27A3
A32A4
A49null
Step 01 / 5

Read the input

IDs label node objects. Equal values can belong to different nodes. Solid arrows are next links; dashed arrows are random links.

Start from the input head pointers.
View original input

A: 4 (A1) → 7 (A2) → 2 (A3) → 9 (A4); parameters: {"target":2}

Parameter indices are zero-based, except n from the end, which is one-based. Node IDs remain fixed when links change.

Put it into code

Keep a current pointer and a position counter. Each next link advances by one.

Node stores val and next; the random-pointer lesson adds random. C++ uses C++17 or later.

class Node:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def search(head, target):
    curr, index = head, 0
    while curr:
        if curr.val == target:
            return index
        curr = curr.next
        index += 1
    return -1

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap