PPractick

DSA interview question

Search for a Value in a Linked List

Medium · Data structures · Topics: linkedlist

The problem

A contacts app stores recently called numbers in a singly linked list, most recent first. When a call comes in, the app checks whether the number is already in the list and where, so it can move that entry to the front. There's no index and no ordering to exploit, so the only option is a linear scan from the head, counting positions until the value turns up or the list ends. It's the linked-list counterpart of linear search.

Example: 1 -> 2 -> 3 -> 4, search 3 → position 3.

Function signature

int searchPosition(Node* head, int key);  // 1-indexed position of the first match, or -1

Test cases

Input (list, key)OutputExplanation
(1 -> 2 -> 3 -> 4, 3)3
(1 -> 2 -> 3 -> 4, 5)-1Not present
(empty, 1)-1
(7 -> 7, 7)1The first occurrence
(4 -> -2 -> 9, 9)3At the tail

(Confirm: positions are 1-indexed; return the first occurrence, or -1 if the key is absent.)

How interviewers phrase it

Clarifying questions to ask

  1. Return a boolean, a position, or the node?
  2. 0-indexed or 1-indexed positions?
  3. First occurrence or all occurrences?

Follow-ups to expect

  1. "Can you use binary search on a sorted linked list?"
  2. "What's the recursive version?"
  3. "How would you move a found node to the front?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in