Skip to content

Commit

Permalink
adding problem set + solution
Browse files Browse the repository at this point in the history
  • Loading branch information
one-m1nd committed Dec 11, 2023
1 parent 567f745 commit 17287d5
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/leetcode.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require 'leetcode/merge_k_sorted_lists'
require 'leetcode/reverse_nodes_in_k_group'
require 'leetcode/median_of_two_sorted_arrays'
require 'leetcode/regular_expression_matching'

Expand Down
25 changes: 25 additions & 0 deletions lib/leetcode/reverse_nodes_in_k_group.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module Leetcode
# https://leetcode.com/problems/reverse-nodes-in-k-group/
class ReverseNodesInKGroup
# @param head [Array<Integer>]
# @param k [Integer]
# @return [Array<Integer>]
def execute(head, k)
return head if k <= 1

iterations = (head.length / k)
iterations.downto(1) do |iteration|
terminus_index = (iteration * k) - 1
start_index = terminus_index - k + 1 <= 0 ? 0 : terminus_index - k + 1

slice = head[start_index..terminus_index].reverse

terminus_index.downto(start_index) do |swap_index|
head[swap_index] = slice.pop
end
end

head
end
end
end
28 changes: 28 additions & 0 deletions spec/leetcode/reverse_nodes_in_k_group_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
RSpec.describe Leetcode::ReverseNodesInKGroup do
describe '#execute' do
let(:head) { [] }
let(:k) { [] }

subject { Leetcode::ReverseNodesInKGroup.new.execute(head, k) }

context '[1, 2, 3, 4 ,5], 2' do
let(:head) { [1, 2, 3, 4 ,5] }
let(:k) { 2 }

it do
expect(subject).to be_instance_of(Array)
expect(subject).to eql([2, 1, 4, 3, 5])
end
end

context '[1, 2, 3, 4, 5], 3' do
let(:head) { [1, 2, 3, 4, 5] }
let(:k) { 3 }

it do
expect(subject).to be_instance_of(Array)
expect(subject).to eql([3, 2, 1, 4, 5])
end
end
end
end

0 comments on commit 17287d5

Please sign in to comment.