Get Node Value

Get Node Value

Return the value of the node at a given 0-based index. If the index is out of range (negative, or past the end), return -1.

getNodeValue(head, index)

Input format: list | index — space-separated node values, a pipe, then the index.

Examples

(10 → 20 → 30), 0   // → 10
(10 → 20 → 30), 2   // → 30
(10 → 20 → 30), 5   // → -1

Walkthrough

Thinking it through

A linked list can't jump straight to "the node at position 5" the way an array indexes directly — there's no offset arithmetic that gets you there. The only way to reach the Nth node is to start at the head and take N steps, one at a time. This problem is really about implementing that step-counting walk correctly, edge cases included.

Building the approach

  1. Handle a clearly invalid input first: a negative index can never be a real position, so reject it immediately without even looking at the list.
  2. Otherwise, start a pointer at the head and treat the index as a countdown — that many steps before you arrive.
  3. At each node, ask: "have I taken enough steps yet?" If the countdown hit zero, you've arrived — this is the node you want.
  4. If not, advance the pointer and decrement the countdown.
  5. If the pointer runs off the end before the countdown hits zero, the requested index was beyond the list's length — return the "not found" sentinel.

Why checking "is this the target?" has to happen before advancing

You must check whether the current node is the one you want before moving past it. Check-then-advance, not the other way around, or you'll skip the correct node or misalign your count by one.

Two distinct ways to be "out of range"

There are two separate invalid cases, worth keeping conceptually distinct even though they produce the same output: a negative index is invalid before you even start walking, while an index that's too large only becomes invalid once you've walked off the end and found nothing left. Handling the negative case up front keeps the traversal logic focused on just the "too large" case.

Why this is optimal

Since there's no way to know the list's length without walking it, and no way to jump directly to a position, visiting up to index + 1 nodes is the minimum necessary work — you can't do better than linear time in the worst case for singly linked list indexing.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.