Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check if absolute difference of consecutive nodes is 1 in Linked List in Python
Suppose we have a singly linked list where each node contains an integer value. We need to check if the absolute difference between every pair of consecutive nodes is exactly 1.
For example, if the input is 5?6?7?8?7?6?5?4, the output will be True because each consecutive pair has an absolute difference of 1: |5-6|=1, |6-7|=1, |7-8|=1, |8-7|=1, |7-6|=1, |6-5|=1, |5-4|=1.
Algorithm
To solve this problem, we follow these steps:
- Start with the head node as current
- While current node exists:
- If current.next is None, break (reached end)
- If |current.value - current.next.value| ? 1, return False
- Move to the next node
- Return True if all consecutive pairs satisfy the condition
Implementation
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
def create_linked_list(elements):
"""Create a linked list from a list of elements"""
if not elements:
return None
head = ListNode(elements[0])
current = head
for element in elements[1:]:
current.next = ListNode(element)
current = current.next
return head
def check_consecutive_difference(head):
"""Check if absolute difference between consecutive nodes is 1"""
current = head
while current and current.next:
if abs(current.value - current.next.value) != 1:
return False
current = current.next
return True
# Test the implementation
elements = [5, 6, 7, 8, 7, 6, 5, 4]
head = create_linked_list(elements)
result = check_consecutive_difference(head)
print(f"Input: {elements}")
print(f"Result: {result}")
Input: [5, 6, 7, 8, 7, 6, 5, 4] Result: True
Testing with Different Cases
Let's test with a case where the condition fails:
# Test case where condition fails
elements_fail = [1, 2, 4, 5] # 2 to 4 has difference of 2
head_fail = create_linked_list(elements_fail)
result_fail = check_consecutive_difference(head_fail)
print(f"Input: {elements_fail}")
print(f"Result: {result_fail}")
# Test edge case with single node
single_node = create_linked_list([5])
result_single = check_consecutive_difference(single_node)
print(f"Single node result: {result_single}")
Input: [1, 2, 4, 5] Result: False Single node result: True
Time and Space Complexity
- Time Complexity: O(n), where n is the number of nodes in the linked list
- Space Complexity: O(1), as we only use a constant amount of extra space
Conclusion
This solution efficiently checks if consecutive nodes in a linked list have an absolute difference of 1 by traversing the list once. The algorithm returns True if all consecutive pairs satisfy the condition, and False otherwise.
Advertisements
