Simple solution in possibly O(0) space. No extra variable or space required.


  • 0
    A

    Another java specific code without using any other variable or space. However this solution is not recommended as it depends on runtime error "stackoverflow"

    public class Solution {
    public boolean hasCycle(ListNode head) {
    try{
    while(head!=null){
    return hasCycle(head.next);
    }
    return false;
    }catch(Throwable e){
    return true;
    }
    }
    }


  • 0

    Um... stack overflow literally means you're using too much space. So definitely not "O(0) space".


  • 0
    A

    @ManuelP Isnt O(anything) about the variables? I was thinking about it when I wrote the thing.

    Space taken by methods via recursions isnt counted as space, as far as I have seen.

    I might be wrong.


  • 0
    A
    This post is deleted!

  • 0

    Stack space does count as space. Why wouldn't it?

    Interesting idea, though. Just a shame that you made it hard to read.

    Shorter implementation:

    public boolean hasCycle(ListNode head) {
        try {
            return head != null && hasCycle(head.next);
        } catch (Throwable e) {
            return true;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.