Intermediate Level

Implement the detectCycleLinkedListValues method that checks whether the linked list has a cycle at the given position.

The linked list is provided as an integer array nodes, its length size, and an integer pos.

The value pos represents the index where the tail connects back into the linked list. If pos is -1, the linked list has no cycle.

Your task is to return true if the linked list contains a cycle, otherwise return false.

Example 1

Input
nodes (int[]) = [3,2,0,-4]
size (int) = 4
pos (int) = 1
Returns (boolean) true

Example 2

Input
nodes (int[]) = [1,2]
size (int) = 2
pos (int) = -1
Returns (boolean) false

Example 3

Input
nodes (int[]) = [1]
size (int) = 1
pos (int) = 0
Returns (boolean) true

In a real linked list, cycle detection is commonly solved using the slow and fast pointer method. If the fast pointer meets the slow pointer, a cycle exists.

In this problem, the cycle position is provided directly as pos. If pos is a valid index inside the list, the tail connects to that node and the list has a cycle. If pos is -1, there is no cycle.

Pseudocode:

function detectCycleLinkedListValues(nodes, size, pos):
    if pos >= 0 and pos < size:
        return true
    return false
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.