Back to blog
Apr 26, 2024
3 min read

Create Hello World Function

Write a function createHelloWorld that returns a new function which always returns 'Hello World'.

Difficulty: Easy | Acceptance: 81.90% | Paid: No Topics: N/A

Write a function createHelloWorld. It should return a new function that always returns “Hello World”.

Examples

Input:  args = []
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f(); // "Hello World"
Input:  args = [{},null,42]
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f({}, null, 42); // "Hello World"

Constraints

0 <= args.length <= 10

Direct Function Return

Intuition Create a function that returns another function, where the inner function simply returns the string “Hello World” regardless of any arguments passed to it.

Steps

  • Define the outer function createHelloWorld
  • Inside it, define and return an inner function
  • The inner function returns “Hello World”
python
def createHelloWorld():
    def f():
        return "Hello World"
    return f

Complexity

  • Time: O(1)
  • Space: O(1)
  • Notes: This is the most straightforward approach with minimal overhead.

Arrow/Lambda Function

Intuition Use modern arrow/lambda syntax for a more concise implementation that achieves the same result with cleaner code.

Steps

  • Define createHelloWorld using arrow/lambda syntax
  • Return an arrow/lambda function that returns “Hello World”
python
def createHelloWorld():
    return lambda: "Hello World"

Complexity

  • Time: O(1)
  • Space: O(1)
  • Notes: More concise syntax, functionally identical to the direct approach.

Class-based Approach

Intuition Encapsulate the hello world functionality in a class with a callable method, demonstrating object-oriented programming principles.

Steps

  • Create a class with a method that returns “Hello World”
  • Return an instance or method reference from createHelloWorld
python
class HelloWorld:
    def __call__(self):
        return "Hello World"

def createHelloWorld():
    return HelloWorld()

Complexity

  • Time: O(1)
  • Space: O(1)
  • Notes: More verbose but demonstrates OOP patterns; useful for extending functionality.