File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
data_structures/hash_table Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Write a program that outputs the string representation of numbers
2
+ # from 1 to n. But for multiples of three it should output “Fizz”
3
+ # instead of the number and for the multiples of five output “Buzz”.
4
+ # For numbers which are multiples of both three and five output
5
+ # “FizzBuzz”.
6
+
7
+ #
8
+ # Approach 1: Hash it!
9
+ #
10
+
11
+ # Intuition
12
+ #
13
+ # This approach is an optimization over approach 2. When the
14
+ # number of mappings are limited, approach 2 looks good. But What
15
+ # if you decide to add too many mappings?
16
+ #
17
+ # Having a condition for every mapping is not feasible or may be
18
+ # we can say the code might get ugly and tough to maintain.
19
+ #
20
+ # What if tomorrow we have to change a mapping or maybe delete
21
+ # a mapping? Are we going to change the code every time we have a
22
+ # modification in the mappings?
23
+ #
24
+ # We don't have to. We can put all these mappings in a Hash Table.
25
+
26
+ # Complexity Analysis
27
+
28
+ # Time Complexity: O(N)
29
+ # Space Complexity: O(1)
30
+
31
+ # @param {Integer} n
32
+ # @return {String[]}
33
+ def fizz_buzz ( n )
34
+ str = [ ]
35
+ fizz_buzz = { }
36
+ fizz_buzz [ 3 ] = "Fizz"
37
+ fizz_buzz [ 5 ] = "Buzz"
38
+
39
+ n . times do |i |
40
+ i += 1
41
+ num_str = ""
42
+
43
+ fizz_buzz . each do |key , value |
44
+ num_str += value if i % key == 0
45
+ end
46
+
47
+ num_str = i . to_s if num_str == ""
48
+
49
+ str . push ( num_str )
50
+ end
51
+
52
+ str
53
+ end
54
+
55
+ n = 15
56
+ puts ( fizz_buzz ( n ) )
You can’t perform that action at this time.
0 commit comments