mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-16 23:16:26 +00:00
57 lines
1.2 KiB
Markdown
57 lines
1.2 KiB
Markdown
## Arrays & Strings
|
|||
|
|
|
||
|
|
Ordered collections. Arrays are **mutable**, strings are **immutable** — every "edit" to a string builds a new one.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Cost model
|
||
|
|
|
||
|
|
| Operation | Array | String |
|
||
|
|
| --- | --- | --- |
|
||
|
|
| Append / pop at end | O(1)* | O(n) |
|
||
|
|
| Insert / delete in middle | O(n) | O(n) |
|
||
|
|
| Random access | O(1) | O(1) |
|
||
|
|
| Membership check | O(n) | O(n) |
|
||
|
|
|
||
|
|
*amortized — occasional resize, constant on average.
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Recognition
|
||
|
|
|
||
|
|
- Contiguous data + index arithmetic → array patterns apply
|
||
|
|
- Building a string piece by piece → collect parts, join once
|
||
|
|
- "In-place" requirement → think swap / overwrite, not rebuild
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## String building
|
||
|
|
|
||
|
|
```js
|
||
|
|
// O(n^2): each += copies the whole string
|
||
|
|
let s = "";
|
||
|
|
for (const ch of parts) s += ch;
|
||
|
|
|
||
|
|
// O(n): buffer then join
|
||
|
|
const buf = [];
|
||
|
|
for (const ch of parts) buf.push(ch);
|
||
|
|
const out = buf.join("");
|
||
|
|
```
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Recall
|
||
|
|
|
||
|
|
- Why is append amortized O(1) and not plain O(1)?
|
||
|
|
- What does immutability cost when you "modify" one character?
|
||
|
|
- Which patterns sit on top of arrays? (two pointers, sliding window, prefix sum)
|
||
|
|
|
||
|
|
---
|
||
|
|
|
||
|
|
## Drill
|
||
|
|
|
||
|
|
- 1480 Running Sum of 1d Array
|
||
|
|
- 217 Contains Duplicate
|
||
|
|
- 189 Rotate Array
|
||
|
|
- 977 Squares of a Sorted Array
|