Last Updated: 26 Dec, 2022

Fizzbuzz Problem

Easy
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’].
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

Approaches

01 Approach

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’.