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).
Be the first one to answer
Add answer anonymously...
Top Capgemini Engineering Software Engineer interview questions & answers
Popular interview questions of Software Engineer
Top HR questions asked in Capgemini Engineering Software Engineer
>
Capgemini Engineering Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
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
Get AmbitionBox app