Similar Problems

Similar Problems not available

Print Foobar Alternately - Leetcode Solution

Companies:

LeetCode:  Print Foobar Alternately Leetcode Solution

Difficulty: Unknown

Topics: unknown  

The problem statement from LeetCode is as follows:

Problem Statement:

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Foo” instead of the number and for the multiples of five output “Bar”. For numbers which are multiples of both three and five output “Foobar”.

Example:

n = 15,

Return:
[
"1",
"2",
"Foo",
"4",
"Bar",
"Foo",
"7",
"8",
"Foo",
"Bar",
"11",
"Foo",
"13",
"14",
"Foobar"
]

Solution:

The problem requires us to print Foobar for numbers which are multiples of both 3 and 5, Foo for numbers which are only multiples of 3, and Bar for numbers which are only multiples of 5. For all other numbers, we just need to print the number.

One of the ways to solve this problem is to loop from 1 to n and check for each number if it is a multiple of 3, 5, or both. This can be done using the modulus operator (%).

We can use an if-else block to check if the number is a multiple of both 3 and 5, multiple of only 3, multiple of only 5 or neither of them. If the number is a multiple of both 3 and 5, we print "Foobar", else if it is a multiple of 3, we print "Foo", else if it is a multiple of 5, we print "Bar", and for other numbers, we just print the number.

Here is the Python code that implements this approach:

def foobar_alternately(n: int) -> List[str]:
    result = []
    for num in range(1, n + 1):
        if num % 3 == 0 and num % 5 == 0:
            result.append("Foobar")
        elif num % 3 == 0:
            result.append("Foo")
        elif num % 5 == 0:
            result.append("Bar")
        else:
            result.append(str(num))
    return result

This code iterates from 1 to n and checks if each number is a multiple of 3, 5, or both. We create an empty list result to store the output. If the number is a multiple of both 3 and 5, we append "Foobar" to the result list, else if it is a multiple of 3, we append "Foo" to the result list, else if it is a multiple of 5, we append "Bar" to the result list, and for other numbers, we convert the number to a string and append it to the result list.

Finally, we return the result list as the output.

This solution has a time complexity of O(n) as we are looping from 1 to n. The space complexity is also O(n) as we are creating a list of size n to store the output.

This solution is accepted on LeetCode and has good performance in terms of time and space complexity.

Print Foobar Alternately Solution Code

1