Detect Loop in Singly Linked List

Determine if a given singly linked list of integers contains a cycle.

Explanation:

A cycle in a linked list occurs when a node's next points back to a previous node in the list, creating a loop.

For this problem, there is no partial marking; all test cases must be accurately handled.

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 (which is not a valid list element).
The second line contains an integer "pos" indicating the 0-indexed position in the linked list where the tail connects. If "pos" is -1, the linked list has no cycle.

Output:

Output 'true' if the linked list has a cycle, or 'false' otherwise.
Explicit printing is not required; it is managed for you.

Example:

Input: [3, 2, 0, -4, -1], pos = 1
Output: true

Constraints:

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

Note:

Try to solve this problem in O(N) Time Complexity and O(1) Space Complexity.
AnswerBot
4d

Detect if a singly linked list has a cycle by using Floyd's Cycle Detection Algorithm.

  • Use Floyd's Cycle Detection Algorithm to detect a cycle in a singly linked list.

  • Maintain two pointers, one moving ...read more

Help your peers!
Add answer anonymously...
NetApp Software Developer 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