Given the head of a sorted singly linked list and a target value, implement a function to find the target value using a binary search approach. If the target is found in the linked list, return the node; otherwise, return None.
classSolution {
public ListNode binarySearch(ListNode head, int target) {
// Step 1: Calculate the length of the linked listint length = 0;
ListNode current = head;
while (current !=null) {
length++;
current = current.next;
}
// Binary search simulation on linked listint left = 0;
int right = length - 1;
while (left <= right) {
// Find the middle nodeint mid = left + (right - left) / 2;
ListNode midNode = getNodeAtIndex(head, mid);
// Compare the middle node value with the targetif (midNode.val== target) {
return midNode; // Target found } elseif (midNode.val< target) {
left = mid + 1; // Move to the right half } else {
right = mid - 1; // Move to the left half }
}
returnnull; // Target not found }
// Helper function to get the node at a specific indexprivate ListNode getNodeAtIndex(ListNode head, int index) {
ListNode current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current;
}
}
classSolution:
defbinarySearch(self, head: ListNode, target: int) -> ListNode:
# Step 1: Calculate the length of the linked list length =0 current = head
while current:
length +=1 current = current.next
# Binary search simulation on the linked list left =0 right = length -1while left <= right:
# Find the middle node mid = left + (right - left) //2 midNode = self.getNodeAtIndex(head, mid)
# Compare the middle node value with the targetif midNode.val == target:
return midNode # Target foundelif midNode.val < target:
left = mid +1# Move to the right halfelse:
right = mid -1# Move to the left halfreturnNone# Target not found# Helper function to get the node at a specific indexdefgetNodeAtIndex(self, head: ListNode, index: int) -> ListNode:
current = head
for _ in range(index):
current = current.next
return current
The approach is not as efficient as binary search on an array because each getNodeAtIndex call may require traversing up to half the length of the linked list.
The time complexity for each getNodeAtIndex call is O(n), making the overall complexity approximately O(n log n).