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
4mo

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!
Select
Add answer anonymously...

NetApp Software Developer interview questions & answers

A Software Developer was asked Q. What extracurricular activities did you participate in during college?
A Software Developer was asked Q. If we use a heap in Q6, what are the disadvantages of that approach?
A Software Developer was asked Q. How do you calculate the square root of a number without using math.h?

Popular interview questions of Software Developer

A Software Developer was asked Q1. What extracurricular activities did you participate in during college?
A Software Developer was asked Q2. If we use a heap in Q6, what are the disadvantages of that approach?
A Software Developer was asked Q3. How do you calculate the square root of a number without using math.h?
NetApp Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits