DSA Factory
Free lessonsLinked lists · Stage 0 · Walking nodes · Step 2

Find first occurrence

Walk with an index counter and return the position of the first matching value. About 8 minutes.

Tracking your position

Nodes in a linked list do not know their own position. If you need to know which place a node occupies, you have to count for yourself, like counting the carriages on a train as you walk through it.

Start a counter at 0, and add 1 every time you step to the next node.

Counter starts at 0: it tracks how many hops you have made from the head.
Add one per step: it goes up with each step forward.
Search [5, 8, 3, 9] for target 3
5
0
8
1
3
2
9
3
curr

The pointer starts at the head (5), and the counter is 0. 5 is not 3. Advance.

Move 1 of 3

Returning early

When searching for the first occurrence of a value, check whether the current node holds the target. If it does, return the counter immediately and stop walking, because the problem asks for the first occurrence.

Only if the loop finishes without finding a match do you answer minus one.

Match found: return the counter right away.
Fall-through: the minus one belongs after the loop, not inside it.
In code
idx = 0
curr = head
while curr:
    if curr.val == target:
        return idx
    idx += 1
    curr = curr.next
return -1
Quick check

If target is the second node in a 5-node list, how many nodes does the loop examine?

  1. A2 nodes
  2. B5 nodes
  3. C1 node
Show the answer

2 nodes. It checks node 0, does not match, steps to node 1, matches, and returns immediately.

Your problem

Find first occurrence

Given the head of a linked list and an integer target, return the 0-based index of the first node whose value equals target. If target does not appear anywhere in the list, return -1.

Example
head = [5, 8, 3, 9], target = 3 → 2

0 ≤ number of nodes ≤ 10,000 · -1,000,000 ≤ node.val, target ≤ 1,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding