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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay