Problem

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

Examples

Example 1

1
2
3
4
5
6
7
Input: args = []
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f(); // "Hello World"

The function returned by createHelloWorld should always return "Hello World".

Example 2

1
2
3
4
5
6
7
Input: args = [{},null,42]
Output: "Hello World"
Explanation:
const f = createHelloWorld();
f({}, null, 42); // "Hello World"

Any arguments could be passed to the function but it should still always return "Hello World".

Constraints

  • 0 <= args.length <= 10

Solution

Method 1 – Closure Returning Constant

Intuition

The key idea is to use a closure that ignores its arguments and always returns the string “Hello World”. This leverages JavaScript/TypeScript’s ability to return a function from another function, capturing the desired behavior.

Approach

  1. Define a function createHelloWorld that returns a new function.
  2. The returned function accepts any arguments (using rest parameters) but always returns the string “Hello World”.
  3. The closure ensures the returned function always produces the same output, regardless of input.

Code

1
2
3
4
5
function createHelloWorld() {
    return function(...args) {
        return "Hello World";
    };
}
1
2
3
4
5
function createHelloWorld(): (...args: any[]) => string {
    return function(...args: any[]): string {
        return "Hello World";
    };
}

Complexity

  • ⏰ Time complexity: O(1), as the function always returns a constant string.
  • 🧺 Space complexity: O(1), as no extra space is used beyond the closure.