Just like @stefan mentioned in comments to one of the posts.
You could also build a frequency hash to avoid traversing the array multiple times.
What that means is:
frequency_map = Hash.new{|h,k| h[k] = 0 }
array2.each{ |number| frequency_map[number] += 1 }
frequency_map
#=> {1=>2, 2=>2, 3=>2, 4=>1, 5=>1, 6=>1, 7=>1, 8=>1, 9=>1, 10=>1, 11=>1, 12=>1}
As you can see above, we have the frequency of each number in array2 from only one iteration, i.e. O(n) time, but has O(n) space complexity.
From the above frequency, we can easily deduce the number of times array1 appeared in array2:
frequency_of_array1 = nil
array1.each do |number|
if frequency_of_array1.nil?
frequency_of_array1 = frequency_map[number]
else
frequency_of_array1 = frequency_of_array1 > frequency_map[number] ? frequency_map[number] : frequency_of_array1
end
end
frequency_of_array1 #=> 2
Or simply this(but build another array/space - which was avoided above):
array1.map{ |num| frequency_map[num] }.min
1,2,1,2,3,3? does that count as 1 or 2? what about3,2,1? you have to properly define what you mean withappear infor all possible cases.