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

Value at index

Count hops from the head to reach the target position, guarding against short lists. About 8 minutes.

Moving forward k steps

To read the value at a given position, counting from 0, you need to advance across that many next pointers. Position 0 needs 0 hops, since it is the head itself. Position 1 needs 1 hop. In general, a loop running that many times takes you to the right node.

It is like walking down a corridor: to reach door 3 you pass three doors.

0 hops: the head is position 0.
k hops: leads to the node at position k.
Reach index 2 in list [10, 20, 30, 40]
10
0
20
1
30
2
40
3
curr

curr starts at head (index 0, val 10). Hop 1 of 2.

Move 1 of 3

What if the list is too short?

If the position is 5 but the list only has 3 nodes, the pointer will become null before you finish taking your hops. Trying to read anything from a null pointer is a crash.

So check that the pointer is not null before each hop, and again before reading the value. A negative position is invalid too.

Null check: if the pointer is null at any point, the position is out of bounds.
Negative position: answer minus one immediately.
In code
if index < 0:
    return -1
curr = head
for _ in range(index):
    if not curr:
        return -1
    curr = curr.next
return curr.val if curr else -1
Quick check

To reach index 3 in a list, how many times must you do curr = curr.next?

  1. A3 times
  2. B4 times
  3. C2 times
Show the answer

3 times. Starting at index 0: 1st hop lands on index 1, 2nd lands on index 2, 3rd lands on index 3.

Your problem

Value at index

Given the head of a linked list and a 0-based integer index, return the value of the node at position index. If index is negative, or is greater than or equal to the number of nodes in the list, return -1.

Example
head = [10, 20, 30, 40], index = 2 → 30

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

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