Detect Cycle in a Linked List

Given a singly linked list of integers, determine whether it contains a cycle. A cycle exists if any node in the list can be traversed more than once, forming a loop.

Input:

The first line of each test case contains the elements of the singly linked list, separated by a single space, and terminated by -1. Hence, -1 would never be a list element.
The second line contains an integer 'pos', which represents the 0-indexed position in the linked list where the tail connects. If 'pos' is -1, then there is no cycle in the linked list.

Output:

Output 'true' if the linked list contains a cycle, otherwise 'false'.

Example:

Input:
3 2 0 -4 -1
1
Output:
true
Input:
1 2 3 4 -1
-1
Output:
false

Constraints:

  • 0 <= N <= 106
  • -1 <= pos < N
  • -109 <= data <= 109 and data ≠ -1
  • Time Limit: 1 second

Note:

Attempt to solve this problem with a time complexity of O(N) and space complexity of O(1).

AnswerBot
4d

Detect cycle in a singly linked list by using Floyd's Tortoise and Hare algorithm.

  • Use two pointers, slow and fast, to traverse the linked list.

  • If there is a cycle, the fast pointer will eventually mee...read more

Help your peers!
Add answer anonymously...
Capgemini Engineering Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter