Simulation workbench
Editable input · deterministic traceGold cells mark the active indices; labels identify indices independently of color. Traces use bounded JavaScript teaching implementations. Complexity below describes the algorithm, excluding saved visualization frames. Java source remains authoritative for API and overflow contracts.
Reason before you code
Language-neutral solution outline
Compare the design
Run the scenario to observe the collaboration.
Several patterns may solve a problem. Choose the best fit for the stated constraints, then explain why.
Start by counting, not timing
A loop adding three array values performs three additions. Six values require six additions. Doubling the input doubles the main work: we call this linear growth, O(n). Here n means the number of elements, not their values.
Keep time and memory separate: the scan takes more steps as n grows, but one running total still uses constant extra memory, O(1). Follow the calculation below, then explore the notation when ready.
Optional: notation, growth comparisons, and advanced caveats
FOUNDATIONS · BEGINNER · 20 MINUTESBig O: count the work, account for the memory.
Prerequisite: loops, arrays, and functions. Start here before comparing algorithms. Big O is an asymptotic upper bound; Θ is a tight bound and Ω is a lower bound. State the input size and case before making a claim.
| Example | Growth | n | 2n | Auxiliary memory |
|---|
Derive the bound
- Define the dimensions: n elements; V vertices and E edges; n rows and d features.
- Count a representative operation, such as one comparison or one pair visit.
- Add sequential phases: O(n) + O(n²) becomes O(n²). Multiply independent nested loops: n × m becomes O(nm).
- A loop that halves its search interval takes O(log n) iterations. Two pointers each moving forward at most n times still take O(n), even with a nested while loop.
- Drop fixed constants and lower-order terms asymptotically: 3n + 5 is Θ(n). Constants and cache behavior still matter in practice.
Time cases, amortization, and memory
Linear search has Θ(1) best-case and Θ(n) worst-case comparisons. Average-case needs an input distribution. Hash lookup is commonly expected O(1), not an unconditional worst-case promise. Dynamic-array append is amortized O(1) across a sequence, although a resizing append can take O(n).
Auxiliary space is extra working memory, excluding the input and, when explicitly stated, the returned output. Total memory includes input, working memory, and output. Recursive depth consumes stack space: balanced tree DFS uses O(log n) stack; a chain can use O(n). Enumerating every subset requires Θ(n·2ⁿ) output elements even if the recursion path needs only O(n).
These guides save snapshots. Copying an n-cell board for O(n) frames can consume O(n²) time and memory even when the underlying algorithm uses O(1) auxiliary space. Input validation and trace construction are separate from the algorithm's displayed bound. Teaching integer arithmetic assumes bounded values; very large integers have nonconstant arithmetic costs.
Worked comparisons
- Pair sum: brute-force pairs take Θ(n²); sorting then two pointers takes O(n log n) overall; already-sorted two pointers take O(n). State whether sorting is included.
- Graph traversal: O(V + E) with adjacency lists; repeatedly scanning an adjacency matrix takes O(V²). Representation changes cost.
- Model training: one dense gradient pass takes O(nd). I iterations take O(Ind); K-fold evaluation multiplies fitting work by K.
- Heap selection: O(n log(k + 1)) time and O(k) working memory. A small k and a large n are different dimensions.
Read the design
Java-like excerpts isolate the work being analyzed. Counters below illustrate the stated cost model; they do not execute Java or measure elapsed time.
Calculate it step by step
Change the input size
Common mistake
Work it out yourself: analysis worksheet
Use the Java-like excerpt above. Write your reasoning before comparing with the worked solution. Notes are temporary and clear when you change chapters.
Check your calculation
Architecture exercise: complete an order
Intermediate · 30 minutes · Prerequisites: SOLID, Strategy, Observer, and Command.
Design an order workflow with pricing rules, persistence, and notification. Draw the boundary between domain policy and infrastructure adapters.
- Use a Pricing Strategy behind a stable contract; inject a repository and notifier into the application service.
- Specify failure behavior: payment succeeds but notification fails. Persist an outbox event in the same database transaction as the order, then retry delivery independently.
- Give the command an idempotency key. Deduplicate retries, define timeout and retry limits, and record delivery state.
- Explain why Observer's synchronous callback is not durable messaging, and why undoing a local counter is different from refunding an external payment.
- Test duplicate commands, a failed database transaction, delivery retries, and a poison message. Describe monitoring and recovery ownership.
Review criteria
A clear transaction boundary, dependency direction toward domain contracts, explicit delivery guarantees, bounded retries, and a documented compensation policy matter more than the number of patterns used. Start with one service; split deployment only when scale, ownership, or isolation requires it.