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

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

Capgemini Engineering Software Engineer interview questions & answers

A Software Engineer was asked Q. Given an array of integers nums and an integer target, return indices of the two...read more
A Software Engineer was asked Q. Given an array of characters, find the first non-repeating character in the arra...read more
A Software Engineer was asked Q. What is destructuring in JavaScript?

Popular interview questions of Software Engineer

A Software Engineer was asked Q1. Given an array of characters, find the first non-repeating character in the arra...read more
A Software Engineer was asked Q2. What is destructuring in JavaScript?
A Software Engineer was asked Q3. Is there an MCQ-based technical test in Round 1?
Capgemini Engineering Software Engineer 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