Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node.
Note: The linked list does not contain any internal loops.
[Expected Approach-1] By Traversing each node - O(n) time and O(1) space
The main idea is to traverse through the each node of linked list and check if the head->next pointer points back to the starting node (temp). If it does, that means the linked list is circular.
Code Implementation:
Output
No
Yes
Time Complexity: O(n), We traverse the linked list in the worst case once, therefore, the time complexity here is linear. Auxiliary Space: O(1), We are not using any extra space.
[Expected Approach-2] By Maintaining Slow & Fast Pointers - O(n) time and O(1) space
The idea is to use two pointers, slow and fast, to traverse the linked list. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. If the list is circular, the fast pointer will eventually meet the slow pointer; otherwise, the fast pointer will reach NULL indicating the list is not circular.
Code Implementation:
Output
false
Time Complexity: O(n), We traverse the linked list in the worst case once, therefore, the time complexity here is linear. Auxiliary Space: O(1), We use two Node pointers, slow and fast, so the extra space is constant.