Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
1823
  • Loading branch information
theforestvn88 committed Jul 8, 2024
commit 293f5702b8e128eb364d6a59804f639e278a998b
43 changes: 43 additions & 0 deletions 1801-1900/1823_find_the_winner_of_the_circular_game.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class CircularList
class Node
attr_accessor :val, :next
def initialize(val, next_node = nil)
@val = val
@next = next_node
end
end

attr_reader :head, :tail
def initialize(n)
@head = CircularList::Node.new(1)
curr = @head
(2..n).each do |i|
curr.next = CircularList::Node.new(i)
curr = curr.next
end
curr.next = @head
@tail = curr
end

def remove_each_k(k, curr: @head, prev: @tail)
count = k
while count > 1
prev = curr
curr = curr.next
count -= 1
end

return prev if prev === curr.next

prev.next = curr.next
remove_each_k(k, curr: curr.next, prev: prev)
end
end

# @param {Integer} n
# @param {Integer} k
# @return {Integer}
def find_the_winner(n, k)
cl = CircularList.new(n)
cl.remove_each_k(k).val
end