Introduction
Searching in a Linked List means finding whether a target value exists in the list.
The task is to:
- start from head node
- compare each node value
- return true if found
Example:
Input:
1 -> 2 -> 3 -> 4
Target:
3
Output:Found
Explanation:
Traverse nodes one by one.
1 != 3
2 != 3
3 == 3
Element found.
This problem is one of the most important basics of:
Linked List Data Structure Constraints
1 <= Number of Nodes <= 10^5-10^9 <= Node Value <= 10^9Approach 1 : Brute Force (Convert to Array)
Explanations:
Explanation:
The idea is:
- convert linked list into array
- perform linear search in array
Steps:
- Traverse linked list.
- Store values in array.
- Search target value.
This approach works but:
- uses unnecessary extra space
So direct linked list traversal is preferred.
Dry Run
Input:1 -> 2 -> 3 -> 4
Target:
3
Step 1:
Array:
[1,2,3,4]
Step 2:
Search 3
Element found
Final Output:
Found
Practice :
Complexity Analysis :
Time Complexity:- O(n)
Explanation :
Every node is visited once.
Space Complexity:- O(n)
Explanation :Extra array is used.
Approach 2 : Optimal Solution(Direct Traversal)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- traverse linked list directly
- compare node values one by one
- stop immediately if target is found
This avoids extra space usage.
Dry Run
Input:1 -> 2 -> 3 -> 4
Target:
3
Step 1:
1 != 3
Move next
Step 2:
2 != 3
Move next
Step 3:
3 == 3
Element Found
Traversal Stops
Practice :