We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Create Hello World Function

Number: 2809

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Microsoft, Meta, Bloomberg, Apple, Adobe, Uber, Yahoo


Problem Description

Write a function createHelloWorld that returns a new function. Regardless of the input arguments provided to the returned function, it should always return "Hello World".


Key Insights

  • The returned function does not depend on any input parameters.
  • Always returns a constant string "Hello World".
  • The solution leverages a closure: a function is created within createHelloWorld and captured for later use.

Space and Time Complexity

Time Complexity: O(1) for both creating the function and for each call. Space Complexity: O(1) since no additional space scales with input size.


Solution

We solve the problem by defining a function createHelloWorld which returns another function. The returned function ignores its arguments and always returns the string "Hello World". There is no need for iterating, handling inputs, or complex data structures. The mental leap here is recognizing that a closure with a hardcoded return value simplifies the solution.


Code Solutions

# Define the function createHelloWorld that returns a new function
def createHelloWorld():
    # The returned lambda function ignores any arguments and returns "Hello World"
    return lambda *args, **kwargs: "Hello World"

# Example usage
if __name__ == "__main__":
    hello_func = createHelloWorld()
    print(hello_func())  # Expected output: "Hello World"
← Back to All Questions