DEV Community

Christopher Coffee
Christopher Coffee

Posted on

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
    }
}
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay