The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← Computer Science: Algorithms, Systems and Software

Weeks 1–4

Problem specification, algorithms and complexity

Learning objectives

  • Explain the mechanisms and distinctions in problem specification, algorithms and complexity.
  • Apply the assigned concepts to the supplied fictional record and justify each inference.
  • Revise a conclusion when evidence, assumptions or constraints change.

Develop the concepts

A computational problem specifies acceptable outputs for a class of inputs. An algorithm is a defined method for obtaining such outputs. Before writing code, state the input domain, expected result and behavior on boundary cases. “Find the best option” is incomplete until best is operationally defined. An implementation can run successfully while solving the wrong problem.

Correctness and efficiency are distinct. A loop invariant describes a property preserved through iterations and can support a correctness argument. Test cases reveal some errors but do not generally prove absence of all errors. A proof or structured argument must connect initialization, preservation and termination with the specification. Empty inputs, duplicates and extreme values often expose hidden assumptions.

Complexity describes how resource use grows with input size under a model. A linear scan examines a number of elements proportional to n. Binary search can reduce comparisons logarithmically when the data are ordered and the access model supports the required operations. Sorting solely to answer one query has its own cost. Big-O notation is an asymptotic bound, not an exact stopwatch reading or a guarantee that one implementation is faster at every input size. Choose a method using correctness requirements, data properties and realistic workload.

Worked record

A fictional catalog contains 64 sorted unique identifiers in an array. A search compares the middle identifier and repeatedly keeps only the half that could contain the target.

Reason through the record

Each unsuccessful comparison reduces the candidate range roughly by half. After six halvings, a range of 64 can be reduced to about one candidate; exact comparison counts depend on the implementation and success position. The method relies on sorted order and correct boundary updates. If the array is unsorted, discarding a half can discard the target. A linear scan remains correct without ordering but may inspect every element. This example separates the logical property enabling the algorithm from its efficiency. It also shows why an informal claim of “six operations always” is too strong without specifying what counts as an operation and how the loop terminates.

Deeper explanation: Specification, invariants and honest algorithm comparisons

An algorithm starts with a contract. Specify accepted inputs, the meaning of the result, and behavior at boundaries. Find a matching value, find its first occurrence, and find an insertion position are different tasks on the same array. A method can return a plausible index while violating the actual contract. Tests become stronger when expected behavior comes from a simple independent definition rather than a second copy of the implementation.

For lower-bound search on an ascending array, the result is the smallest index whose value is at least the target; the result may equal the array length. Maintain a half-open candidate interval [lo, hi). Values strictly before lo are below the target; values at or after hi are at least the target. Set mid to the integer midpoint. If a[mid] is below target, discard it and everything before it by setting lo = mid+1. Otherwise set hi = mid. The interval shrinks and the invariant survives. At termination lo = hi, so the insertion boundary is determined. An ordinary matching-value lookup then also checks that the index is in range and its value equals the target.

Correctness and complexity are separate claims. Halving a random-access interval gives logarithmic comparisons; it does not make sorting free. If a changing dataset receives one lookup, sorting solely to enable that lookup may cost more than a scan. For repeated queries, index construction can pay off. A hash table has different expected behavior, memory requirements and worst-case qualifications. Measure the workload you actually intend to support.

A benchmark needs a fixture, a result check, a timing boundary and enough repetitions to expose noise. Exclude printing from the timed region unless output is part of the workload. Count preprocessing, copying and updates when they occur in actual use. If a fast routine returns the wrong duplicate or silently mutates the input, its speed is irrelevant to the promised contract.

Fully worked investigation

Search [2, 4, 4, 9] for lower bound of 4. Start lo=0, hi=4. mid=2 contains 4, so hi=2. mid=1 contains 4, so hi=1. mid=0 contains 2, so lo=1. Stop at 1, the first 4. For target 10, the same contract returns 4, not an invalid access to a[4]. A follow-up membership check must test index < len(a) before reading the value. For an empty array the answer is 0 and no element is accessed.

Independent transfer problem

Trace lower bound for targets 1, 4 and 8 in [1, 4, 4, 4, 8]. Write a linear reference function and compare every target from 0 through 9. Then deliberately change hi=mid to hi=mid−1 and identify a failing input.

Reasoning and limitations

The correct indices are 0, 1 and 4. A linear reference returns the first enumerated value >= target, otherwise len(a). With [1,4] and target 4, the defective update can return 0 after discarding index 1 improperly. Explain the broken invariant; a single matching output on a large fixture does not prove correctness.

Unit 1: programs, abstractions and algorithmic reasoning

From a question to an operational contract

Computing begins by making a task precise enough that a result can be checked. An input domain states what information is accepted. A postcondition describes the relationship the output must bear to that input. Preconditions identify assumptions a component relies on. A failure policy describes what happens when the input is outside that domain or a resource is unavailable. For example, 'return the earliest request' requires decisions about time zones, missing timestamps and ties. Faster code cannot repair an undefined meaning of earliest.

Abstraction deliberately preserves some details and hides others. A queue interface can promise insertion at one end and removal at the other without exposing whether storage uses linked nodes or a circular array. That hidden implementation still affects capacity and performance, so the interface must state any relevant limits. Decomposition assigns responsibilities to components whose contracts fit together. If one component returns seconds and another interprets milliseconds, each can appear locally reasonable while their composition fails. A useful boundary includes representation and units as well as a function name.

An algorithm is a finite description of a procedure; a program expresses behavior through the rules of a programming language and its execution environment. Termination is a property to establish for a particular procedure and input class, not a guarantee provided by calling something an algorithm. A correct implementation must satisfy the contract, including termination where promised. The retained native lower-bound investigation supplies a full invariant argument and changed-boundary counterexample; this expansion explains the programming and representation mechanisms around that investigation.

Expressions, state and control flow

An expression computes a value. A statement directs execution, for example by assigning a value, choosing a branch or repeating work. A variable name refers to a value or storage location according to the language's rules. In Python, assignment binds a name to an object; it does not make a universal promise that a new independent object is copied. If two names refer to the same mutable list, modifying that list through one name can be visible through the other. Rebinding one name to a different list is a different operation.

Sequencing matters when operations observe or modify state. Consider the fictional starting values x=2 and y=5. Executing x=x+y followed by y=x-y yields x=7 and y=2 because the second statement sees the new x. It does not yield y=−3 by using both original values. A trace table should show the state after each statement. When a specification requires simultaneous updates, explicitly compute from the old state before replacing it. This distinction recurs in numerical methods, database updates and concurrent software.

A conditional selects behavior using a Boolean result. An if/elif/else chain chooses the first satisfied branch, so overlapping conditions make their order significant. A loop repeats a body under a control rule. A Python for loop visits items from an iterable; a while loop reevaluates its condition. A loop invariant describes what remains true at a specified point, and a decreasing nonnegative measure can help establish termination. A count of unprocessed input records is such a measure when exactly one record is consumed each iteration. It ceases to work if the loop continually adds records to the same collection.

Worked trace: a fictional filter receives integer readings [4, −1, 4, 0]. Its contract returns the sum of nonnegative readings and the count used, without changing the input. Initialize total=0 and used=0. After 4, the state is(4, 1). After−1 it remains(4, 1). After the second 4 it is(8, 2); after 0 it is(8, 3). The average is 8/3 if requested. Zero belongs in the count because the stated condition is nonnegative. For an empty input the result is(0, 0), and an average is undefined under this contract. Return an explicit absent-average state rather than dividing by zero or silently reporting a meaningful zero average.

Changed facts: readings arrive as strings and one entry is 'missing'. Comparing strings or silently skipping every parsing error changes the accepted domain. Specify parsing and missingness first. A valid redesign can return the accepted count, rejected count and reasons, but it should not pretend that three valid readings from a partially invalid file describe a fully accepted file. The original mathematical trace remains correct for its original integer domain.

Functions, scope, recursion and error boundaries

A function packages a computation behind parameters and a result contract. Local names help contain reasoning, but a function can still modify an object passed to it or access shared state. A pure calculation returns a result from its inputs without changing outside state; this makes some tests easier, but many useful systems must perform effects such as writing a file. Keep validation and calculation distinguishable from those effects so that a failed validation cannot partially apply the operation.

A function call needs an execution context containing its local state and a return point. Recursion expresses a task in terms of smaller instances and requires both a stopping case and progress toward it. For a list sum, sum_from(i) can return 0 at i=len(values), otherwise values[i]+sum_from(i+1). The termination argument uses the decreasing number of unprocessed elements. This conceptual definition is useful for reasoning; a recursive implementation also consumes call-stack space and can exceed an implementation's recursion limit. Replacing a loop with recursion does not automatically improve complexity or reliability.

An exception signals that ordinary control flow cannot continue as specified. A caller should catch errors it can meaningfully handle and preserve enough context to report a failure accurately. Catching every exception and returning 0 can conflate a genuine zero result with malformed data, an absent file or a programming defect. Cleanup and rollback are distinct responsibilities: closing a resource does not inherently undo its committed effects. Later units connect this boundary to persistent storage and transactions.

Languages and execution layers

Source code is text governed by syntax and meaning. Parsing identifies structure; name resolution and type-related rules determine whether operations make sense under a language's model. Translation can produce machine instructions or an intermediate representation. A runtime may interpret instructions, compile them ahead of execution, compile selected paths during execution or combine these approaches. 'Compiled' and 'interpreted' describe implementations and stages, rather than two mutually exclusive categories into which every language permanently falls.

Machine-level instructions operate on representations and resources supplied by an instruction-set architecture. Assembly provides symbolic forms for such operations; high-level constructs express larger abstractions such as functions and collections. CPython normally compiles Python source into implementation-specific bytecode executed by its interpreter. Those bytecode details can change across releases and are not a portable substitute for Python's language behavior. Successful parsing therefore establishes neither correct application logic nor suitability for every execution environment.

Data structures and resource tradeoffs

An array-like sequence supports positional access and ordered traversal. A linked structure follows references between nodes and offers different insertion and traversal costs. A stack removes the most recently added item; a queue removes the oldest queued item under a first-in-first-out contract. A map associates keys with values; a set represents membership without retaining a meaningful count of repeated equal elements. A tree organizes parent/child relationships; a graph permits more general connections. These are concepts and interfaces: a particular library supplies concrete semantics, capacity and cost guarantees.

Choosing a set for fictional readings [4, −1, 4, 0] produces the distinct values{4, −1, 0}. That changes the task if repeated observations must contribute separately. A map keyed by request ID similarly collapses repeated identifiers unless the design records or rejects duplicates explicitly. A hash-based implementation uses a hash to locate candidates and equality to distinguish keys that collide. Equal hash values do not prove equal keys, and expected lookup performance does not establish an unconditional worst-case bound.

Asymptotic analysis studies resource growth under a stated model. A scan can require a number of element inspections proportional to n; comparing every unordered pair requires n(n−1)/2 comparisons. For n=6 that is 15; for n=12 it is 66, not 30. A logarithm describes repeated multiplicative reduction, as developed in the preserved search model. Big-O is an upper-bound relation up to constants beyond a threshold. It is neither an exact time nor necessarily a tight bound; use a matching lower bound or Theta notation when claiming a tight growth rate. Count construction, copying, updates and memory where the real workload pays those costs.

Optional progressive practice and complete model

Question: a fictional dispatch rule returns the first urgent item in arrival order. The records are J1 ordinary, J2 urgent, J3 urgent. A developer sorts by identifier in descending order and returns the first urgent result. Explain the contract failure, supply the correct result and describe an independent check.

Model reasoning: arrival order makes J2 the correct result. Descending identifier order places J3 before J2 and solves a different problem. A reference check scans the original arrival sequence and returns the first item whose urgent flag is true, or an explicit no-match result. Test no urgent item, an urgent first item, multiple urgent items and an empty input. Keep the original sequence unchanged if that is part of the interface contract. A benchmark must compare implementations of this same contract, not reward the sorted version for returning a different urgent request.

Changed facts: the policy changes to highest numeric priority, then earliest arrival among ties. Supply J1 priority 2 at 10:00, J2 priority 3 at 10:02 and J3 priority 3 at 10:01, with all times in the same declared zone and date. Now J3 wins. The old first-urgent scan no longer suffices, while the descending-ID method still lacks a valid relation to priority and arrival. Compare the stated priority first and the stated timestamp second, and reject or explicitly handle missing values. The changed answer follows a changed specification, not evidence that the original answer was an arithmetic error.

Complete original cumulative application and rubric: https://www.lawfaregroup.com/knowledge/academy/developed-studies/computing-contracts-machines-and-evidence.html#cumulative

Continue studying

Apply the idea

A fictional catalog contains 64 sorted unique identifiers in an array. A search compares the middle identifier and repeatedly keeps only the half that could contain the target.

The catalog changes frequently and identifiers are no longer kept sorted. Which original correctness premise fails?

Additional worked record — a separate fictional scenario: Search [2, 4, 4, 9] for lower bound of 4. Start lo=0, hi=4. mid=2 contains 4, so hi=2. mid=1 contains 4, so hi=1. mid=0 contains 2, so lo=1. Stop at 1, the first 4. For target 10, the same contract returns 4, not an invalid access to a[4]. A follow-up membership check must test index < len(a) before reading the value. For an empty array the answer is 0 and no element is accessed.

Progressive transfer problem: Trace lower bound for targets 1, 4 and 8 in [1, 4, 4, 4, 8]. Write a linear reference function and compare every target from 0 through 9. Then deliberately change hi=mid to hi=mid−1 and identify a failing input.

Read the worked reasoning

The ordering premise fails, so the comparison no longer identifies a safe half to discard. Restore an appropriate ordered structure or use a search method valid for the new data. Do not retain binary search merely because it was previously fast.

Transfer reasoning: The correct indices are 0, 1 and 4. A linear reference returns the first enumerated value >= target, otherwise len(a). With [1,4] and target 4, the defective update can return 0 after discarding index 1 improperly. Explain the broken invariant; a single matching output on a large fixture does not prove correctness.

Check understanding

What should lower bound return for target 10 in [2,4,4,9]?

  1. 3, because every result must index an element
    Feedback

    Incorrect. Index 3 contains 9, which is below the target. The contract permits an insertion boundary beyond the last element.

  2. −1, because insertion positions cannot be returned
    Feedback

    Incorrect. A separate membership search may choose −1 for absence, but this contract asks for an insertion position.

  3. 4, the permitted one-past-end insertion position
    Feedback

    Correct. All four elements are below 10. Return the length and guard any later element access.

Further reading

Study the complete native lesson and matching original on-site reader unit with the preserved quantitative investigation, then the complete Harbor cumulative case and rubric. All practice, local laboratory execution and publisher chapters are optional; no external learning departure is required.

My learning →