Leetcode: Linked List Cycle Kotlin
Kotlin

Leetcode: Linked List Cycle Kotlin

2024-03-20
10 min read

Leetcode: Linked List Cycle (Kotlin)

This is an easy Leetcode LinkedList question. I will go over my thought process for solving this. For this, we will use Floyd’s Cycle Detection algorithm. Linked List Cycle - LeetCode

Brainstorm

  1. Define two pointers — slow and fast. Initialize both of them to the head of the linked list.

  2. Move the slow pointer one step at a time and the fast pointer two steps at a time.

  3. At each step, check if slow and fast pointers are equal. If they are equal at some point, then a cycle exists in the linked list.

  4. If the fast pointer reaches the end of the list (i.e., it becomes null), then there is no cycle in the list.

Solution

/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */

class Solution {
    fun hasCycle(head: ListNode?): Boolean {
       var slow = head
       var fast = head

       while(fast != null && fast.next != null){
           slow = slow?.next
           fast = fast?.next?.next

           if(slow == fast){
               return true
           }
       }

       return false
    }
}

We have also solved a previous problem using Floyd’s Cycle Detection algorithm:

https://medium.com/@cmcoffeedev/leetcode-middle-of-the-linked-list-kotlin-4625ef698de6