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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (you can concatenate strings using the + operator in a loop).
- Implement Logic: Handle state and transformations efficiently (initialize an empty string and append str in each iteration).
- 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.