Detect Cycle in Linked List with Floyd's Algorithm

🔁 Coding Question of the Day: Detect Cycle in a Linked List One of the most elegant problems in data structures — simple to understand, but powerful in interviews. 💡 Problem: Given the head of a linked list, determine if it contains a cycle. 👉 A cycle occurs when a node points back to a previous node instead of "null". --- 🚀 Optimal Approach: Floyd’s Cycle Detection (Tortoise & Hare) Use two pointers: • Slow → moves 1 step • Fast → moves 2 steps If there’s a cycle, they will eventually meet! --- 💻 Python Solution: def hasCycle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False --- ⏱ Complexity: Time: O(n) Space: O(1) --- 🔥 Interview Tip: Want to stand out? Don’t stop at detection. Try finding the starting point of the cycle — a common follow-up! --- #DataStructures #CodingInterview #LeetCode #100DaysOfCode #SoftwareEngineering #TechCareers

To view or add a comment, sign in

Explore content categories