M01 · Algorithmic Thinking

From Problem to Algorithm: Inputs, Outputs and Constraints

Most wrong solutions are correct answers to a different question. Before choosing a loop or a data structure, write down exactly what goes in, what must come out, and how large the input can get. This lesson does that for linear search and for a duplicate-detection problem, then uses the constraints to pick between three solutions.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M01 Algorithmic Thinking · 2 of 2 lessons available

You will be able to

  • Write a precise problem contract: input types and ranges, ordering, duplicates, the empty case, and the exact output including "not found".
  • Use the input-size constraint to estimate which growth rates are fast enough before writing code.
  • Start from a brute-force solution, state its cost, and explain why it is still worth having.
  • Decompose a problem into steps and choose a data structure from the operations those steps need.
  • Name the language details (integer width, null, not-found conventions) that change a contract between C#, Python, Java and C++.

Helpful before this lesson

    Guidance only. Those modules are planned; the essentials are recapped here.

    Visual walkthrough

    The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

    Mental model

    An algorithm is a finite sequence of unambiguous steps that turns every valid input into a correct output. A data structure is a way of arranging data so that the operations an algorithm needs are cheap. Both only make sense relative to a problem, and a problem is a contract with three parts:

    1. Input: what you are given, its types, its size, and every property you may rely on (sorted? distinct? non-empty? within some range?).
    2. Output: exactly what must be returned for each input, including ties and the "nothing found" case.
    3. Constraints: how large the input can be and how much time and memory you may use.

    Writing the contract first is not bureaucracy. Each line either rules out a bug or rules out an approach. "Values are sorted" makes binary search possible. "There may be duplicates" forces you to say which match you return. "n can be a million" rules out comparing every pair.

    The lab above runs the smallest complete example: find a target in an array. A precise contract:

    • Input: an array of integers (any order, duplicates allowed, possibly empty) and a target integer.
    • Output: the smallest index i with values[i] == target, or -1 if there is none.
    • Constraints: only equality tests on elements; O(1) extra memory.

    Every phrase does work. "Smallest" settles duplicates: the Duplicates: first match preset stops at index 2 and never looks at the second 19. "Possibly empty" is a real input, not an error: the Empty array preset returns -1 after one bounds check and no comparison. "Any order" is why no faster method exists: without ordering, any element you skip could be the target. The Not found preset shows the price, n comparisons.

    A different, equally valid contract ("return any matching index", or "return a boolean", or "throw if absent") would change the implementation and the tests. That is why the contract comes first.

    Questions to ask about any input

    Question Why it matters
    Can it be empty? Can it be null/None? Loops that read values[0] or compute n - 1 break on empty input.
    Is it sorted? By what? Enables binary search, two pointers and merging; otherwise you may need to sort first (O(n log n)).
    Can values repeat? Decides which match you return and whether a set loses information.
    What range do values take? Sums and products can overflow fixed-width integers; small ranges allow counting arrays.
    How large can n get? Decides which growth rate is acceptable (next section).
    May I modify the input? Sorting in place is cheaper than sorting a copy, but the caller may not expect it.
    Is the input given all at once? A stream you see once rules out sorting and random access.

    From constraints to a target complexity

    Once you know the largest n, you can rule out approaches before writing them. The table below is a rule of thumb, not a guarantee: it assumes roughly 10⁷ to 10⁸ simple operations per second in compiled C#, Java or C++ (often ten or more times fewer in CPython) and a time budget of about a second.

    Largest n Growth rates that usually fit Typical shape
    ≤ 10 O(n!), O(n · n!) try every ordering
    ≤ 20–25 O(2ⁿ), O(n · 2ⁿ) try every subset
    ≤ a few hundred O(n³) three nested loops
    ≤ about 10⁴ O(n²) every pair
    ≤ about 10⁶ O(n log n) sort, then scan; heap; balanced tree
    ≥ 10⁷ O(n), O(log n), O(1) one pass, hashing, binary search

    The exact count matters at the boundaries; the Big O explorer draws these curves side by side, and module M03 shows how to count. The useful habit is the direction of reasoning: constraints → acceptable growth → candidate techniques.

    Worked example: has any badge been scanned twice?

    The problem Has any badge been scanned twice? gives you a log of integers and asks whether any value appears more than once.

    Contract. Input: an array of integers, possibly empty, any order. Output: true if some value occurs at least twice, else false. An empty or one-element log returns false.

    Brute force. Compare every pair:

    Pseudocode
    for i from 0 to n - 1:
        for j from i + 1 to n - 1:
            if values[i] == values[j]: return true
    return false

    In the worst case (no duplicate) this makes n(n − 1)/2 comparisons: Θ(n²) time, O(1) extra space. It is obviously correct, which makes it valuable even when it is too slow: it is the reference you test faster versions against. Every algorithm in this lab is checked that way, against a simple or built-in reference on random inputs.

    Decompose and look for structure. The question "have I seen this value before?" is asked once per element. Two ways to make that question cheap:

    1. Sort, then compare neighbours. After sorting, equal values are adjacent, so one pass of n − 1 neighbour comparisons answers the question. Cost: O(n log n) for the sort, plus O(n). It either modifies the input or needs a copy.
    2. Remember what you have seen in a hash set. For each value: if it is in the set, return true; otherwise add it. n expected-O(1) set operations: O(n) expected time, O(n) extra space.
    Approach Time Extra space Notes
    All pairs Θ(n²) worst case O(1) the test oracle
    Sort + neighbours O(n log n) O(1) to O(n), depending on the sort and whether you copy changes order unless you copy
    Hash set O(n) expected O(n) worst case degrades if many values collide

    Choose with the constraints. With n ≤ 1,000 all three are fine and the simplest correct one wins. With n = 10⁶, the pairwise version needs about 5 × 10¹¹ comparisons and is out; the other two are both reasonable, and the choice comes down to whether memory or input order matters more. This is what "choosing a data structure" means in practice: the step "have I seen x?" needs fast membership, and a set is the structure built for that. The hashing for lookup pattern collects more problems with the same shape, and the two readings that add up to a target problem uses a map instead of a set for the same reason.

    Pseudocode

    Pseudocode is a plan, not a program. Good pseudocode states loop bounds exactly (0 to n - 1, inclusive or exclusive), names the data structure (seen = empty hash set), and leaves out language noise such as type declarations. If you cannot write the loop bounds in pseudocode, the off-by-one bug will appear in the real code too. The listings below the lab show how one plan becomes four programs with the same structure.

    Language notes

    The same contract can mean different things in different languages:

    • Integer width. C# int and Java int are 32-bit and wrap around silently on overflow (C# throws OverflowException only in a checked context). C++ signed overflow is undefined behaviour, so the compiler may assume it never happens. Python int has unlimited precision and never overflows, but grows slower as numbers get larger. A constraint such as "values up to 10⁹, n up to 10⁵" means a sum can reach 10¹⁴: use long (C#, Java) or std::int64_t (C++).
    • Missing input. C#, Java and Python have a null reference (null, None); decide whether the contract allows it. A C++ std::vector or std::span cannot be null, only empty.
    • "Not found" conventions differ. List<T>.IndexOf (C#) and List.indexOf (Java) return -1. Python's list.index raises ValueError instead (while str.find returns -1). C++ std::find returns the end iterator. Code that ports a contract between languages must translate this, not copy it.
    • Equality. Linear search needs only an equality test, but what == means depends on the type: value equality for numbers and strings in Python and for C# strings, reference identity for Java objects compared with == (use equals). Module M04 covers this in detail.

    Common mistakes

    • Solving the example instead of the problem. Checking only the sample input misses the empty, the single-element and the all-equal cases.
    • Unstated assumptions. Relying on sorted input, distinct values or a non-empty array without the contract saying so.
    • Ignoring the size constraint until the solution times out, or optimising a problem where n ≤ 100 and the brute force was fine.
    • Forgetting the cost of a hidden step, such as sorting before a binary search, or copying an array to avoid modifying it.
    • Ambiguous output. "Return the index" without saying which one, or what to do when there is none.

    Edge cases

    A checklist that catches most contract gaps:

    • empty input, one element, two elements;
    • all elements equal, all distinct;
    • the answer at the first position, at the last position, or absent;
    • the smallest and largest allowed values (overflow, negative numbers);
    • already sorted and reverse sorted input.

    The next lesson turns this list into a habit and adds the tool that proves a loop correct: the loop invariant.

    Worked practice

    1. Write a precise contract for "find the largest value in an array".

    Input: an array of integers, any order, duplicates allowed. The empty case must be decided: either the contract requires n ≥ 1, or it says what to return (an error, a sentinel, or "no value", such as an optional). Output: a value m that occurs in the array with m ≥ x for every element x. Note that the output is a value, not an index; with duplicates, the index would need its own rule.

    2. n ≤ 200,000. Is an all-pairs O(n²) solution acceptable?

    n² = 4 × 10¹⁰ elementary steps, and even n(n − 1)/2 is 2 × 10¹⁰: far over the rule-of-thumb budget of about 10⁸ per second. Look for O(n log n) or O(n).

    3. In the duplicate problem, when is "sort + neighbours" the better choice than a hash set?

    When extra memory is tight and the input may be reordered (an in-place sort needs O(1) to O(log n) extra space, a hash set needs O(n)), or when you also need the values in order afterwards. The hash set wins when the input order must be preserved and memory is available.

    4. The contract says "return the index of the target". Name two questions you must ask.

    Which index if the target occurs several times (first, last, any)? What to return if it is absent (-1, an exception, an insertion point)? Also: can the array be empty, and is it sorted?

    Summary

    • A problem is a contract: input properties, exact output, size and resource constraints.
    • The largest n tells you which growth rates are worth trying before you write code.
    • Brute force first: it is correct, it is your test oracle, and its cost tells you how much better you need to be.
    • Decompose the problem into steps; the operations those steps need choose the data structure.
    • Integer width, null handling and "not found" conventions differ between C#, Python, Java and C++; a contract must say which one it means.

    Full implementation

    Linear search in four languages, each checked against one shared fixture (empty, one element, first, last, duplicates, missing, extremes) including the exact number of comparisons, and 2,000 random arrays compared with the language's built-in search (Array.IndexOf, list.index, List.indexOf, std::find).

    namespace Bekadan.Dsa.Examples.Searching;
     
    /// <summary>
    /// Linear search with an early exit: the index of the first element equal to
    /// the target, or -1. Works on unsorted data. O(n) comparisons in the worst
    /// case, 1 in the best; O(1) extra space.
    /// </summary>
    public static class LinearSearch
    {
        public static int IndexOf<T>(T[] items, T target, IEqualityComparer<T>? comparer = null)
        {
            comparer ??= EqualityComparer<T>.Default;
            for (int i = 0; i < items.Length; i++)
            {
                if (comparer.Equals(items[i], target))
                {
                    return i; // the first match: stop early
                }
            }
            return -1; // compared every element
        }
    }
    

    Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Searching/LinearSearch.cs

    """Linear search with an early exit.
     
    Returns the index of the first element equal to the target, or -1. Works on
    unsorted data. O(n) comparisons in the worst case, 1 in the best; O(1) extra
    space.
    """
     
    import operator
    from collections.abc import Callable, Sequence
    from typing import Any
     
     
    def linear_search(items: Sequence[Any], target: Any, equals: Callable[[Any, Any], bool] = operator.eq) -> int:
        for i in range(len(items)):
            if equals(items[i], target):
                return i  # the first match: stop early
        return -1  # compared every element
    

    Tested on CPython 3.14.0 · examples/python/dsa_examples/linear_search.py

    package dev.bekadan.dsa.searching;
     
    import java.util.Objects;
    import java.util.function.BiPredicate;
     
    /**
     * Linear search with an early exit: the index of the first element equal to
     * the target, or -1. Works on unsorted data. O(n) comparisons in the worst
     * case, 1 in the best; O(1) extra space.
     */
    public final class LinearSearch {
        private LinearSearch() {
        }
     
        public static <T> int indexOf(T[] items, T target) {
            return indexOf(items, target, Objects::equals);
        }
     
        public static <T> int indexOf(T[] items, T target, BiPredicate<? super T, ? super T> equals) {
            for (int i = 0; i < items.length; i++) {
                if (equals.test(items[i], target)) {
                    return i; // the first match: stop early
                }
            }
            return -1; // compared every element
        }
    }
    

    Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/searching/LinearSearch.java

    #pragma once
     
    #include <cstddef>
    #include <functional>
    #include <span>
     
    namespace bekadan::dsa {
     
    // Linear search with an early exit: the index of the first element equal to
    // the target, or -1. Works on unsorted data. O(n) comparisons in the worst
    // case, 1 in the best; O(1) extra space. (std::find does the same with iterators.)
     
    template <typename T, typename Equal = std::equal_to<>>
    std::ptrdiff_t linear_search(std::span<const T> items, const T& target, Equal equal = {}) {
        for (std::size_t i = 0; i < items.size(); ++i) {
            if (equal(items[i], target)) {
                return static_cast<std::ptrdiff_t>(i);  // the first match: stop early
            }
        }
        return -1;  // compared every element
    }
     
    }  // namespace bekadan::dsa
    

    Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/linear_search.hpp

    References