I have a problem where, given N terms, the task is to find the k most frequent terms from given N terms. My code is correct, but I have a time limit 10 seconds and my code doesn't pass.Constraints:\$0 < N < 300000\$\$0 < \textrm{term length} < 25\$N = gets.to_iif N < 300000 and N  a=[]  (0...N).each do |i|    el = gets    el_size = el.length    if el_size < 25 and el_size      a << el    end    i+=1  end  k = gets.to_i  new_array = {}  size = a.length  count = 0  (0..size).each do |i|    (0..size).each do |j| count += 1 if a[i] == a[j] end    new_array[a[i]] = count    count = 0  end  s_l = new_array.to_a.sort{|a, b| (b.last > a.last) ? 1 : (b.last < a.last ? -1 : (a.first <=> b.first)) }  i = 0  for key, val in s_l    puts key if i < k    i += 1  endendAnd how can I print only key of hash? Currently I use for key, val in hash.
Slowly working word counter
strings;ruby;io;time limit exceeded
The solution is slow because you aren't using data structures effectively.  In particular, the nested (0..size).each loops will cause it to take \$O(N^2)\$ time, which will be very problematic for large \$N\$.You created new_array (which is actually a hash, not an array as the name suggests), but populate it the hard way.  The easy way is to loop once through all of the words; for each word you encounter, increment its count by 1.  There is no need to construct the intermediate array a.# Read N, then count occurrences of the next N lines of textword_counter = Hash.new { |count, word| count[word] = 0 }n_lines = gets.to_in_lines.times { word_counter[gets] += 1 }# Read k; limit it to the number of distinct wordsk = gets.to_ik = [k, word_counter.keys.length].min# Sort words by descending frequency, breaking ties by alphebetical orderwords_desc_freq = word_counter.sort do |a, b|  cmp = a.last - b.last                    # .last is the count  cmp != 0 ? -cmp : (a.first <=> b.first)  # .first is the wordend# Output k most frequent words(0...k).each do |i|  puts words_desc_freq[i].firstendThe solution above has complexity \$O(N \log N)\$, dominated by the time it takes to sort.Usually, when constraints are given for problems like this, it means that your program is not expected to handle input exceeding the stated limits gracefully.  It does not mean that your program needs to actively reject input that exceeds those limits.  In any case, your validation isn't quite right: in Ruby, 0 is treated as a true value.Your code is formatted reasonably well.  I would just note that the line that performs the sort is long and should be broken up.  One-line blocks are typically written using braces, like (0..size).each { |j| count += 1 if a[i] == a[j] }