def min_len(a) h = Hash.new { |h,k| h[k] = [] } array.each.with_object(h) .with_index { |(i, h), idx| h[i] << idx } .values.map { |a| [a.size, a.last - a.first] } .sort { |i1, i2| [i1.first, i1.last] <=> [i2.first, i2.last] } .last.last end def min_len(a) a.each.with_object({}).with_index{|(i,h),x|h[i]=(h[i]||[])<[b[0],b[-1]]}[-1][-1]+1 end