Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
| 133. Clone Graph | [Link](https://leetcode.com/problems/clone-graph/) | [Link](./lib/medium/133_clone_graph.rb) |
| 134. Gas Station | [Link](https://leetcode.com/problems/gas-station/) | [Link](./lib/medium/134_gas_station.rb) |
| 138. Copy List with Random Pointer | [Link](https://leetcode.com/problems/copy-list-with-random-pointer/) | [Link](./lib/medium/138_copy_list_with_random_pointer.rb) |
| 142. Linked List Cycle II | [Link](https://leetcode.com/problems/linked-list-cycle-ii/) | [Link](./lib/medium/142_linked_list_cycle_ii.rb) |
2 changes: 1 addition & 1 deletion leetcode-ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ require 'English'
::Gem::Specification.new do |s|
s.required_ruby_version = '>= 3.0'
s.name = 'leetcode-ruby'
s.version = '6.5.1.2'
s.version = '6.5.2'
s.license = 'MIT'
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
s.executable = 'leetcode-ruby'
Expand Down
30 changes: 30 additions & 0 deletions lib/medium/142_linked_list_cycle_ii.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

# https://leetcode.com/problems/linked-list-cycle-ii/
# @param {ListNode} head
# @return {ListNode}
def detect_cycle(head)
tort = head
hare = head
is_cycle = false
while tort && hare && hare.next
tort = tort.next
hare = hare.next.next

next unless hare == tort

is_cycle = true

break
end

return unless is_cycle

tort = head
until tort == hare
tort = tort.next
hare = hare.next
end

tort
end
45 changes: 45 additions & 0 deletions test/medium/test_142_linked_list_cycle_ii.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# frozen_string_literal: true

require_relative '../test_helper'
require_relative '../../lib/common/linked_list'
require_relative '../../lib/medium/142_linked_list_cycle_ii'
require 'minitest/autorun'

class LinkedListCycleIITest < ::Minitest::Test
def test_default_one
start = ::ListNode.new(2)
middle = ::ListNode.new(0)
start.next = middle
middle.next = ::ListNode.new(-4, start)
head = ::ListNode.new(3, start)

assert_equal(
start,
detect_cycle(
head
)
)
end

def test_default_two
start = ::ListNode.new(1)
nd = ::ListNode.new(2)
start.next = nd
nd.next = start

assert_equal(
start,
detect_cycle(
start
)
)
end

def test_default_three
assert_nil(
detect_cycle(
::ListNode.new(1)
)
)
end
end
Loading