U

52. Search in Linked List

Easy

Problem Description

Given a linked list of NN integers and a target TT, find the 1-based node position where TT first appears. If TT is not present, output -1.

Input Format

  • •Line 1: Two space-separated integers NN and TT.
  • •Line 2: NN space-separated integers.

Output Format

Print the 1-based position or -1.

Example 1:
Input:
4 30
10 20 30 40
Output:
3
Explanation: 30 is at 1-based position 3.
Example 2:
Input:
3 99
1 2 3
Output:
-1
Explanation: 99 not present in list.
Example 3:
Input:
1 5
5
Output:
1
Explanation: 5 is at position 1.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online