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 @@ -610,3 +610,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
| 677. Map Sum Pairs | [Link](https://leetcode.com/problems/map-sum-pairs/) | [Link](./lib/medium/677_map_sum_pairs.rb) | [Link](./test/medium/test_677_map_sum_pairs.rb) |
| 678. Valid Parenthesis String | [Link](https://leetcode.com/problems/valid-parenthesis-string/) | [Link](./lib/medium/678_valid_parenthesis_string.rb) | [Link](./test/medium/test_678_valid_parenthesis_string.rb) |
| 687. Longest Univalue Path | [Link](https://leetcode.com/problems/longest-univalue-path/) | [Link](./lib/medium/687_longest_univalue_path.rb) | [Link](./test/medium/test_687_longest_univalue_path.rb) |
| 692. Top K Frequent Words | [Link](https://leetcode.com/problems/top-k-frequent-words/) | [Link](./lib/medium/692_top_k_frequent_words.rb) | [Link](./test/medium/test_692_top_k_frequent_words.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 = '7.4.5'
s.version = '7.4.6'
s.license = 'MIT'
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
s.executable = 'leetcode-ruby'
Expand Down
21 changes: 21 additions & 0 deletions lib/medium/692_top_k_frequent_words.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# frozen_string_literal: true

# https://leetcode.com/problems/top-k-frequent-words/
# @param {String[]} words
# @param {Integer} k
# @return {String[]}
def top_k_frequent_words(words, k)
values = words.each_with_object(::Hash.new(0)) { |e, total| total[e] += 1; }

to_sort = values.to_a
to_sort.sort! do |a, b|
diff = b[1] - a[1]
if diff.zero?
a[0] <=> b[0]
else
diff
end
end

to_sort[0...k].map(&:first)
end
27 changes: 27 additions & 0 deletions test/medium/test_692_top_k_frequent_words.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# frozen_string_literal: true

require_relative '../test_helper'
require_relative '../../lib/medium/692_top_k_frequent_words'
require 'minitest/autorun'

class TopKFrequentWordsTest < ::Minitest::Test
def test_default_one
assert_equal(
%w[i love],
top_k_frequent_words(
%w[i love leetcode i love coding],
2
)
)
end

def test_default_two
assert_equal(
%w[the is sunny day],
top_k_frequent_words(
%w[the day is sunny the the the sunny is is],
4
)
)
end
end
Loading