Fizzbuzz Problem

Easy
0/40
profile
Contributed by
2 upvotes
Asked in companies
Birlasoft Ltd.WebCodeGenie Technology Pvt Ltd

Problem statement

You are given an integer ‘N’.

You must return an array of length ‘N’, where ‘ANSWER[i]’ is -

‘HelloWorld’, if ‘i’ is divisible by 3 and 5.

‘Hello’, if ‘i’ is divisible by 3.

‘World’, if ‘i’ is divisible by 5.

‘i’, if ‘i’ is not divisible by 3 and 5.

Example:

Input:
N = 4
Output:
1 2 Hello 4
Explanation: 1, 2, and 4 are not divisible by 3 and 5. 3 is divisible by 3, so we return ‘Hello’.
Hence, we return [‘1’, ‘2’, ‘Hello’, ‘4’].
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of the input will contain the number of test cases, 'T'.
The first line of each test case contains an integers ‘N’.
Output Format:-
Output is printed on a separate line.
Note:-
You don’t need to print anything. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10^5
The sum of N <= 10^6 over test cases 
Time Limit: 1 sec
Sample Input 1:
2
5
6
Sample Output 1:
1 2 Hello 4 World
1 2 Hello 4 World Hello
Explanation Of Sample Input 1:
For test case one:
Input:
N = 5
Output:
1 2 Hello 4 World
Explanation: 1, 2, and 4 are not divisible by 3 and 5. 3 is divisible by 3, so we return ‘Hello’. 5 is divisible by 5, so we return ‘World’.
Hence, we return [‘1’, ‘2’, ‘Hello’, ‘4’, ‘World’].

For test case two:
Input:
N = 6
Output:
1 2 Hello 4 World Hello
Explanation: 1, 2, and 4 are not divisible by 3 and 5. 3 and 6 are divisible by 3, so we return ‘Hello’. 5 is divisible by 5, so we return ‘World’.
Hence, we return [‘1’, ‘2’, ‘Hello’, ‘4’, ‘World’, ‘Hello’].
Sample Input 2:
2
10
15
Sample Output 2:
1 2 Hello 4 World Hello 7 8 Hello World
1 2 Hello 4 World Hello 7 8 Hello World 11 Hello13 14 HelloWorld    
Hint

Stimulate the problem statement.

Approaches (1)
Brute Force

Approach: 

  • We will run a loop from 1 to ‘N’ and check its divisibility by 3 and 5 to push in the answer array according to the following condition -
    • Push ‘HelloWorld’ if it is divisible by 3 and 5.
    • Push ‘Hello’ if ‘i’ is divisible by 3.
    • Push ‘World’ if ‘i’ is divisible by 5.
    • Push ‘i’ if i is not divisible by 3 and 5.
    •  

Algorithm:

Function string[] helloWorld(int  N):

  1. Initialize an empty array of string ‘answer’.
  2. For ‘i’ from 1 to ‘N’:
    • If ‘i’%3==0 and i%5==0:
      • Push ‘HelloWorld’ in ‘answer’.
    • Else If ‘i’%3==0:
      • Push ‘Hello’ in ‘answer’.
    • Else If i%5==0:
      • Push ‘World’ in ‘answer’.
    • Else :
      • Push ‘i’ in ‘answer’.
    •  
  3. Return ‘answer’.
Time Complexity

O( N ), Where ‘N’ is the array ‘A’ length.

 

We are traversing from 1 to N. Hence, the overall time complexity will be O( N ).

Space Complexity

O( 1 ). 

 

We are O(1) extra space for the variables. Hence, the overall space complexity will be O( 1 ).

Code Solution
(100% EXP penalty)
Fizzbuzz Problem
Full screen
Console