Cycle Detection in a Singly Linked List

You have given a Singly Linked List of integers, determine if it forms a cycle or not.

A cycle occurs when a node's next points back to a previous node in the list. The linked list is no longer linear with a beginning and end—instead, it cycles through a loop of nodes.

Note: Since, it is binary problem, there is no partial marking. Marks will only be awarded if you get all the test cases correct.

Input format :
The first line of each test case contains the elements of the singly linked list separated by a single space and terminated by -1 and hence -1 would never be a list element.

The second line contains the integer position "pos" which represents the position (0-indexed) in the linked list where tail connects to. If "pos" is -1, then there is no cycle in the linked list.
Output format :
The only line of output contains 'true' if linked list has a cycle or 'false' otherwise.

You don't have to explicitly print by yourself. It has been taken care of.
Constraints :
0 <= N <= 10^6
-1 <= pos < N
-10^9 <= data <= 10^9 and data != -1

Where 'N' is the size of the singly linked list, "pos" represents the position (0-indexed) in the linked list where tail connects to and "data" is the Integer data of singly linked list.

Time Limit: 1 sec
Note :
Try to solve this problem in O(N) Time Complexity and O(1) space Complexity
CodingNinjas
author
2y

It is a standard problem in the linked list we can solve it using two pointers one moves one step at a time and the other two steps at a time. For each time we check whether they are the same. And thi...read more

CodingNinjas
author
2y
Outer And Inner Loop

We are going to have two loops outer-loop and inner-loop

  1. Maintain a count of the number of nodes visited in outer-loop.
  2. For every node of the outer-loop, start the inner loop from h...read more
CodingNinjas
author
2y
Look Up Table Approach

We are going to maintain a lookup table(a Hashmap) that basically tells if we have already visited a node or not, during the course of traversal.

  1. Visit every node one by one, unti...read more
CodingNinjas
author
2y
Slow And Fast Pointer Approach
  1. The idea is to have 2 pointers: slow and fast. Slow pointer takes a single jump and corresponding to every jump slow pointer takes, fast pointer takes 2 jumps. If there e...read more
Add answer anonymously...
42Gears Mobility Systems Mts1 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
Get AmbitionBox app

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