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.
(10 → 20 → 30), 0 // → 10
(10 → 20 → 30), 2 // → 30
(10 → 20 → 30), 5 // → -1
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.
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.
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.
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.
def get_node_value(head, index):
if index < 0:
return -1
node = head
while node is not None:
if index == 0:
return node.val
index -= 1
node = node.next
return -1
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.