Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions code_to_optimize_js/string_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
* @returns {string} - The reversed string
*/
function reverseString(str) {
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
result += str[i]; // Inefficient string concatenation
// Efficient O(n) implementation using a single allocation and one join
const len = str.length;
const result = new Array(len);
for (let i = 0; i < len; i++) {
result[i] = str[len - 1 - i];
}
return result;
return result.join('');
}

/**
Expand Down
Loading