Arrays & Strings
Learn contiguous-memory structures from the ground up: how arrays are laid out and indexed, how dynamic arrays grow, how matrices are stored and traversed, and how strings are represented and manipulated across languages. Interviewers probe this layer constantly because almost every coding problem starts from an array or a string, and your reasoning about costs here reveals whether you understand memory, not just APIs.
part ofData structures & algorithmsoverview, primer and where to startread it →on this pageshowhide
explore
- Static Arrays10 questions
- Memory Layout & Indexing3 questions
- Operation Costs & Shifting4 questions
- Cache Locality3 questions
- Dynamic Arrays8 questions
- Growth Factor & Amortized Append4 questions
- Capacity, Invalidation & Shrinking4 questions
- Matrices & 2D Arrays8 questions
- Representation & Memory Order4 questions
- Traversal Orders & Transformations4 questions
- String Representation & Memory12 questions
- Characters & Encodings4 questions
- Immutability & Interning4 questions
- Builders & Concatenation Cost4 questions
- String Algorithms13 questions
- Naive Matching & Rabin-Karp5 questions
- KMP & the Failure Function4 questions
- Palindrome & Anagram Reasoning4 questions
- In-Place Manipulation8 questions
- Swap, Reverse & Rotation4 questions
- Partition & Compaction4 questions
- Computer Scienceskillanchors this topic
- Data Structures & Algorithmsskillanchors this topic
- AI & Data Scientistrole
- AI Engineerrole
- AI Red Teamingrole
- Android Developerrole
- Backend Developerrole
- Blockchain Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Frontend Developerrole
- Full Stack Developerrole
- Game Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- Network Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- Software Architectrole
- iOS Developerrole
questions
page 2 of 2What is the worst-case cost of a single append to a growable character buffer?
basics
~20 sOne append is usually constant time, but the append that finds the buffer full is O(n): it allocates a larger block and copies every buffered character across. Amortized over many appends the total is still O(n).
Why does an in-place code-unit swap loop mangle text with emoji or accents?
basics
~20 sSwapping code units also flips the internal order of multi-unit characters: a surrogate pair comes out low half first and becomes invalid, and a combining accent lands before the letter it belonged to. Correct order-reversal walks grapheme clusters.
Why does reading every 16th value of a contiguous capture buffer take nearly as long as reading all of them?
basics
~20 sMemory is fetched in whole cache lines, not single values. A 16-element stride over 4-byte values lands on a new line every step, exactly as many lines as the full scan touches, so traffic is unchanged and only the arithmetic gets cheaper.
Removing one element from an array: when may you swap with the last instead of shifting?
basics
~20 sOnly when the array's order carries no meaning. Swapping the last element into the vacated slot is constant time but permutes the array; shifting the tail left costs Θ(n − i) and is the only order-preserving option.
Why must Rabin-Karp compare symbols after two window hashes turn out to be equal?
basics
~20 sEqual hashes do not mean equal text. The hash compresses m symbols into one bounded value, so different windows can collide. Rabin-Karp treats a hash match as a candidate only and confirms it with an O(m) comparison.
In expand-around-center symmetry checks, why are there 2n-1 centers rather than n?
basics
~20 sOdd-length symmetric spans center on a character; even-length spans center between two characters. That is n on-character centers plus n-1 gaps, so 2n-1 in total, and scanning only the n characters misses every even-length span.
Before a bulk load, what does pre-allocating a growable array's capacity actually buy you?
basics
~20 sPre-allocating removes the repeated allocate-copy-release cycles during the load: fewer allocator round-trips, no moment holding two blocks at once, no growth-driven invalidation, and a flatter latency profile. It does not change the asymptotic cost of appending n elements.
Why does a log-ingest service see p99 append spikes even though appends are amortized O(1)?
basics
~20 sAmortized O(1) bounds the total cost of a run of appends, not any single one. The appends that trigger growth copy the whole buffer, and those copies get slower as it grows — exactly the rare stalls a p99 measures.
When is swap-with-last array removal wrong despite costing only O(1) per element?
basics
~20 sSwap-with-last removal teleports the final live element into the hole, destroying the relative order of what remains. It is wrong whenever a consumer depends on that order — an arrival-ordered log, or any downstream search assuming sortedness.
For a spreadsheet-like grid, when does one flat buffer beat an array of separate row arrays?
basics
~20 sOne flat buffer wins when whole-grid passes dominate: a single allocation, contiguous scans, no per-access indirection. Separate row arrays win when the structure changes at row granularity — reordering, inserting or sharing rows costs a handle move instead of copying every cell.
When joining thousands of text fragments into one document, why compute the total length first?
basics
~20 sSumming the fragment lengths first lets you allocate the result exactly once and fill it in one pass: no reallocation copies, no slack, no growth pause. A growable buffer ties asymptotically but loses on peak memory and tail latency.
Why is a byte offset into UTF-8 O(1) but a character offset not?
basics
~20 sBytes are fixed size, so byte N is one address computation away. Characters are not: UTF-8 spends one to four bytes each, so reaching the Nth character means scanning from a known boundary — O(n) unless you keep an index.
In a log pipeline, when does interning repeated strings pay off — and when does the table become the leak?
basics
~20 sInterning keeps one canonical instance per distinct value, so it pays when cardinality is small and bounded while occurrences are enormous. It backfires on high-cardinality fields: the table retains every distinct value forever, turning short-lived garbage into a permanent leak.
A teammate calls your fixed-capacity array of 16-bit sensor samples primitive and says hardware bounds-checks it for free — how do you defend the design and correct the claim?
basics
~20 sA fixed-capacity contiguous buffer gives a provable memory budget, no allocation in the hot path, and O(1) indexing — exactly what a constrained device needs. The hardware claim is false: memory protection is page-granular, so most out-of-bounds accesses land in mapped memory and trap nothing.
A diff inserts each match result into a sorted score array per event — what do you flag in review?
basics
~20 sEach insert opens a hole mid-array, so it costs linear time in the scores already stored. Across m events that compounds to quadratic total work — invisible at fifty players, a stall at fifty thousand.
When is KMP not worth using over a naive substring scan in production?
basics
~20 sOn varied text with short patterns a naive scan already runs close to linear with a tighter inner loop, so KMP's table build and extra memory rarely pay off. Pay for it when inputs are repetitive or attacker-chosen.
Rabin-Karp is quoted as expected O(n+m) — what input forces O(n*m), and how do you defend against it?
basics
~20 sAny input that makes a fingerprint hit fire at nearly every offset forces an O(m) confirmation each time, giving O(n*m). Either an attacker crafts collisions against your fixed hash parameters, or the pattern genuinely occurs almost everywhere.
What normalization rules must an anagram check agree on before any code is written?
basics
~20 sState the canonicalization first: case folding, whether whitespace and punctuation are dropped, whether digits count, and which characters are in scope at all. Two phrases are anagrams only relative to that rule, so leaving it unstated leaves the behaviour undefined.
Growth factor 2x or 1.5x for a buffer in a service with a hard memory cap — how do you decide?
basics
~20 sDecide on the transient peak, not the copy count. Both blocks are live during a growth, so 2x peaks near three times the data and 1.5x near two and a half; factors under about 1.618 also permit reuse of freed blocks.
Rotating a 10^9-entry memory-mapped log by k: is an O(1)-space in-place rotation the right call?
basics
~20 sOften not. The cheapest rotation of a huge log is logical: keep a base offset and index modulo n, moving nothing. A physical in-place rotation saves memory but rewrites every page and is not crash-safe.
For a quarter-turn board rotation on memory-tight devices, how do you choose in-place cycling over a fresh copy?
basics
~20 sAsk first whether the original must survive and whether the board is square: those two answers usually decide it outright. Only when peak memory is genuinely the binding constraint is the harder in-place ring cycle worth its review cost, and transpose-plus-reverse is already in-place anyway.
In a jagged schedule table with a different slot count per day, which grid operations silently break?
basics
~20 sAnything that treats one row's length as the table's width: column reads, per-column aggregates, transposition, and neighbour lookups. A jagged table has no single column count, so those operations either read past a short row or quietly ignore the tail of a long one.
How do you mask the leading digits of a fixed-length record when strings are immutable?
basics
~20 sCopy the record once into a mutable character array, overwrite the digits in place at O(1) each, then convert back once. That is two copies per record instead of one full copy per masked character.
The juggling rotation writes each element once — why does three-reversal often still win?
basics
~20 sBoth are O(n) time and O(1) extra space, so asymptotics cannot separate them. Juggling halves the writes but strides through memory in gcd-sized cycles, and those scattered touches cost more than the extra sequential pass reversal pays for.
Why can a 10-character substring keep a 2 GB document alive in memory?
basics
~20 sA substring can be a view — an offset and length over the parent's buffer — rather than a copy. Extraction is then O(1), but the view references the whole parent buffer, so all 2 GB stays reachable while the slice lives.
Structure-of-arrays vs array-of-records: why does splitting telemetry records into parallel field arrays speed up a one-field hot loop?
basics
~20 sOne array per field means a loop reading a single field gets only that field's values in each fetched cache line, instead of dragging along every unused field of every record. Fewer lines touched, far less wasted bandwidth, same O(n).
Why does KMP suit scanning a non-rewindable byte stream for a fixed signature?
basics
~20 sKMP's whole state is the prefix table plus the current matched length, and its text pointer never moves backward, so it consumes each byte once, in order, with memory proportional to the signature and a work bound hostile traffic cannot inflate.
Should a growable array's capacity ever shrink automatically in a service whose catalog peaks each December?
basics
~20 sIt depends on whether holding the December peak actually costs you anything measurable. Shrinking copies survivors into a smaller block and invalidates positions, so any automatic policy needs hysteresis: shrink only far below capacity, and to a size that leaves headroom.
Rabin-Karp or a linear-guarantee matcher per pattern: how do you screen submissions against 50,000 known snippets?
basics
~20 sOne rolling-hash pass fingerprints every window once and tests it against a set holding all 50,000 snippet fingerprints, so needle count barely touches scan time. A single-pattern matcher per snippet costs 50,000 passes per submission — no latency budget survives that.
showing 31–59 of 59