Explorer
JavaScript

Write a function `repeatString(str, n)` that repeats the string n times without using the built-in repeat() method.

Problem Statement

<p>Write a function <code>repeatString(str, n)</code> that repeats the string n times without using the built-in repeat() method.</p>

Examples

Input: str = "abc", n = 3

Output: "abcabcabc"

Explanation: "abc" is concatenated 3 times.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: You can concatenate strings using the + operator in a loop. šŸ’” Hint 2: Initialize an empty string and append str in each iteration. šŸ’” Hint 3: let result = ""; for (let i = 0; i < n; i++) result += str; return result;

Editorial & Approach

Problem Overview & Intuition

To solve Repeat String, we consider the execution characteristics of JavaScript engines. Write a function `repeatString(str, n)` that repeats the string n times without using the built-in repeat() method. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (you can concatenate strings using the + operator in a loop).
  3. Implement Logic: Handle state and transformations efficiently (initialize an empty string and append str in each iteration).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function repeatString(str, n) {
  let result = "";
  for (let i = 0; i < n; i++) result += str;
  return result;
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Repeat String

Easy

Write a function repeatString(str, n) that repeats the string n times without using the built-in repeat() method.

Example Scenarios
1Example 1
Input: str = "abc", n = 3
Output: "abcabcabc"
Explanation:

"abc" is concatenated 3 times.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
["abcabcabc","haha",""]