⚡️ Speed up function string_concat
by 36%
#59
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 36% (0.36x) speedup for
string_concat
insrc/dsa/various.py
⏱️ Runtime :
317 microseconds
→232 microseconds
(best of997
runs)📝 Explanation and details
The optimization replaces inefficient string concatenation with a list-based approach that eliminates quadratic time complexity.
Key optimization applied:
s += str(i)
in a loop, which creates a new string object on each iteration since strings are immutable in PythonWhy this leads to speedup:
The original code exhibits O(n²) time complexity because each
+=
operation must copy the entire existing string plus the new part. For n iterations, this results in copying 1 + 2 + 3 + ... + n characters, totaling O(n²) operations.The optimized version runs in O(n) time:
[str(i) for i in range(n)]
performs n string conversions and list appends''.join(parts)
concatenates all parts in a single pass through the listPerformance characteristics by test case size:
The line profiler confirms this: the original code spends 52.3% of time in the string concatenation loop, while the optimized version completes the entire operation in just two efficient steps. The optimization is particularly effective for larger inputs where the quadratic behavior of repeated string copying becomes the dominant performance bottleneck.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-string_concat-mdpc1jpr
and push.