Skip to content

Commit

Permalink
Solution
Browse files Browse the repository at this point in the history
Linked List Cycle
  • Loading branch information
obzva committed Oct 7, 2024
1 parent bfe247c commit eac930d
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions linked-list-cycle/flynn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* ํ’€์ด
* - Floyd's Tortoise and Hare Algorithm์„ ์ด์šฉํ•œ ํ’€์ด์ž…๋‹ˆ๋‹ค.
* ์ฐธ๊ณ : https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare
*
* Big O
* - N: ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
* - L: ๋ฃจํ”„ ๊ตฌ๊ฐ„์— ์†ํ•˜๋Š” ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
*
* Time Complexity: O(N)
* - ๋ฃจํ”„๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ:
* - fast ํฌ์ธํ„ฐ๊ฐ€ ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ์˜ ๋๊นŒ์ง€ ์ด๋™ํ•˜๋ฉด ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.
* - ์ด ๋•Œ fast ํฌ์ธํ„ฐ์˜ ํƒ์ƒ‰ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:
* O(N / 2) = O(N)
* - ๋ฃจํ”„๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ:
* - slow ํฌ์ธํ„ฐ์™€ fast ํฌ์ธํ„ฐ๊ฐ€ ๋ฃจํ”„ ์•ˆ์—์„œ ๋งŒ๋‚˜๋ฉด ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.
* - ์ด ๋•Œ slow ํฌ์ธํ„ฐ์˜ ํƒ์ƒ‰ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:
* O((N - L) + L * c) (c๋Š” slow๊ฐ€ fast๋ฅผ ๋งŒ๋‚  ๋•Œ๊นŒ์ง€ ๋ฃจํ”„๋ฅผ ๋ฐ˜๋ณตํ•œ ํšŸ์ˆ˜)
* = O(r + (N - r) * c) (L์€ 0 <= r <= N์ธ r์— ๋Œ€ํ•ด N - r๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค)
* = O(N)
*
* Space Complexity: O(1)
* - ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜์— ์ƒ๊ด€์—†์ด ์ผ์ •ํ•œ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
*/

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
if head == nil {
return false
}

slow := head
fast := head

for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next

if slow == fast {
return true
}
}

return false
}

0 comments on commit eac930d

Please sign in to comment.