Guide

Algorithm: Meaning, Steps, and a Worked Example

Learn what an algorithm is by choosing compatible requests for one repair workbench, tracing the steps, and testing the result against the stated goal.

By the Space Office team · Published · Updated · 16 min read

An algorithm is a precise, computable procedure for turning defined inputs into a result through explicit steps. Its usefulness depends on what problem those steps actually solve. In Space Office, Lithium can implement a bounded software rule, Carbon can test it, and Hydrogen coordinates and reviews. A human approves the objective, input definitions, access, and final use.

A bicycle-repair owner reviews an algorithm schedule with Lithium, Carbon, and Hydrogen beside fixed appointment cards
A useful procedure starts with an explicit goal and a result that can be checked against it.

Key takeaways

  • Specify the goal, valid inputs, expected output, and limits before choosing a procedure.
  • Trace a small example by hand so every accepted and skipped record has an explanation.
  • A locally attractive choice needs a reason it solves the complete stated problem.
  • Check correctness separately from running time, memory, and operating behavior.
  • Test empty, boundary, overlapping, reordered, and invalid cases against independent expectations.

Download the complete scheduling example and algorithm review worksheet. The bicycle shop, job requests, and minute values are fictional teaching material. The program returns a selection from sample records; it does not book customers, rearrange an actual workday, or contact another system.

What an algorithm is and why the goal matters

NIST’s algorithm definition frames the idea as computable steps that produce a desired result. A recipe-like description can introduce the concept, but a software procedure also needs unambiguous input meanings, decisions, and stopping behavior. “Choose the best jobs” is not enough: best might mean most completed requests, greatest revenue, earliest arrivals, or highest urgency. Those are different objectives.

The algorithm is the method, while a program is a particular implementation of it. You can describe a method in plain language or a step diagram before selecting JavaScript, Python, or Java. Implementation introduces additional questions about data types, input validation, error handling, and the execution environment. A correct idea can still be translated into a faulty program.

For the worked example, a bicycle shop has one repair workbench. Each request has a fixed start and finish, and the goal is to accept the maximum number of non-overlapping requests. A request cannot move or split into smaller pieces. Every accepted request counts equally. The exercise does not optimize profit, fairness, priority, customer travel, parts availability, or the chance that a repair will actually finish on time.

The owner must decide whether that goal is useful before anyone implements it. If an urgent repair must take priority, maximizing request count may be the wrong business objective. Writing the objective and exclusions clearly protects the project from a subtle failure: delivering software that correctly solves a problem the business never intended to ask. Keep that distinction visible in the brief and the acceptance record.

Define the input and compatibility rules

Each fictional record has an ID and two integer minute offsets within one approved day. Zero is the start of that day, and 1,440 is its endpoint. The code accepts at most 10,000 records. These limits make the exercise concrete; they do not define every real scheduling system. A real timetable would also need a date, time zone, daylight-saving policy where relevant, and a trustworthy source for its records.

Define what one interval means before selecting or comparing schedules.
Field or ruleExercise contractWhy it matters
IDUnique uppercase identifier, starting with a letter; at most 16 characters.A returned ID must identify one unambiguous request.
Start and endWhole minutes with 0≤start<end≤1440.Missing, reversed, fractional, and zero-length intervals are rejected.
CompatibilityA new job may start exactly when the previous one ends.Back-to-back jobs are allowed; no cleanup buffer is assumed.
ResourceOne workbench, with one job at a time.Multiple benches create a different allocation problem.
ObjectiveMaximize the number of accepted requests.Every accepted request has equal value for this calculation.
A bicycle shop owner and Lithium sort fixed requests by finish time while Carbon checks overlaps and Hydrogen records the objective
The next accepted interval must fit after the last accepted finish under the stated compatibility rule.

Treat an interval as including its start and excluding its end. A job from 0 to 30 and another from 30 to 60 can therefore share the endpoint without overlapping. If cleaning or handover needs five minutes, that rule is incomplete for the real task. Add the requirement to the model and its tests rather than quietly applying the teaching procedure while staff discover the missing buffer.

The program copies the relevant fields into new records before sorting. It should return selected IDs while leaving the caller’s input order and records unchanged. That behavior matters when another screen or calculation uses the same input. Agree whether malformed records should reject the complete batch or be isolated for review; this example rejects the batch rather than returning an apparently complete schedule with silent omissions.

Choose a method and trace its decisions

MIT’s interval-scheduling lecture notes analyze the unweighted, single-resource problem and the earliest-finish-time greedy method. The method orders requests by finish time, then scans that order and accepts each request that fits after the previous accepted finish. This choice solves the maximum-count problem under the assumptions above. It is not a rule that every scheduling problem should use.

  1. 1Validate the complete request collection against the input contract.
  2. 2Order requests by increasing finish time; use start time and ID to make ties predictable.
  3. 3Begin with an empty selection and the day’s initial endpoint.
  4. 4For each request, accept it when its start is at or after the last accepted finish.
  5. 5After accepting a request, remember its finish; otherwise leave the selection unchanged.
  6. 6Stop after every request has been considered and return the selected IDs.
A hand trace selects B, C, E, F: four compatible requests from six fictional records.
RequestStartFinishDecision in finish order
B030Accept; last accepted finish becomes 30.
A060Skip; it overlaps B.
C3060Accept; it starts at B’s finish.
D5590Skip; it overlaps C.
E6090Accept; it starts at C’s finish.
F90120Accept; it starts at E’s finish.

The trace gives the reviewer something more informative than a final count. Each skip names the conflict with the accepted prefix, and each acceptance moves the remembered endpoint forward. Choosing A first could produce A, E, F, only three requests. That counterexample explains why an intuitive earliest-start rule can lose useful options in this particular objective, even though its resulting schedule is compatible.

There is also a reason the earliest-finish choice can be trusted beyond this sample. Replacing the first request of a maximum-size compatible schedule with an earliest-finishing request leaves at least as much room for later requests. Repeat the same reasoning on the remaining compatible suffix. The argument depends on fixed intervals and equal request value. If those assumptions change, the justification must be reconsidered.

Implement the algorithm as a small function

function selectJobs(jobs) {
  if (!Array.isArray(jobs) || jobs.length > 10000) {
    throw new TypeError("Expected at most 10000 job records");
  }
  const seen = new Set();
  const ordered = jobs.map((job) => {
    if (!job || typeof job !== "object" || Array.isArray(job) ||
        typeof job.id !== "string" ||
        !/^[A-Z][A-Z0-9-]{0,15}$/.test(job.id) || seen.has(job.id)) {
      throw new TypeError("Each job needs a unique uppercase ID");
    }
    if (!Number.isInteger(job.start) || !Number.isInteger(job.end) ||
        job.start < 0 || job.end > 1440 || job.start >= job.end) {
      throw new RangeError("Use whole minutes: 0 <= start < end <= 1440");
    }
    seen.add(job.id);
    return { id: job.id, start: job.start, end: job.end };
  });
  ordered.sort((a, b) => a.end - b.end || a.start - b.start ||
    (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
  const selected = [];
  let lastEnd = 0;
  for (const job of ordered) {
    if (job.start >= lastEnd) {
      selected.push(job.id);
      lastEnd = job.end;
    }
  }
  return selected;
}
The implementation validates ordinary records, sorts a copied collection, and returns selected IDs without changing the input.

The input check uses Number.isInteger so a quantity that looks numeric as text is not silently treated as a valid minute. The code then enforces the day range and the strict start-before-end rule. Validation happens before selection. An invalid record raises an error instead of disappearing from the output, which prevents a partial collection from looking like the complete set the owner approved.

The comparator first compares finish values, then start values, then IDs using a consistent string order. MDN’s sort documentation explains why a comparator is needed for the intended ordering and that sort changes its target array. Here that target is the copied collection. Returning a new ID list also avoids exposing a mutable internal schedule as though it were an accepted booking record.

const sample = [
  { id: "A", start: 0, end: 60 },
  { id: "B", start: 0, end: 30 },
  { id: "C", start: 30, end: 60 },
  { id: "D", start: 55, end: 90 },
  { id: "E", start: 60, end: 90 },
  { id: "F", start: 90, end: 120 }
];
const result = selectJobs(sample);
console.log("Selected IDs:", result.join(", "));
console.log("Selected count:", result.length);
The complete download contains the function and this sample. Expected output: selected IDs B, C, E, F and selected count 4.

Save the reviewed download as algorithm-demo.js in a learning folder and run it with an approved JavaScript runtime, such as node algorithm-demo.js where Node.js is installed. The expected lines are “Selected IDs: B, C, E, F” with spaces after the commas and “Selected count:4” with a space before the number. Compare the displayed IDs with the hand trace rather than checking only that a process completed successfully.

Algorithm selection flow: validate requests, sort by finish, accept compatible intervals, and verify B, C, E, F
The same input contract connects the hand trace, implementation, and acceptance checks.

This file works only with the included records and terminal output. It does not read a calendar, reserve a bench, publish availability, or change a customer appointment. Connecting an API or a database would introduce access, source freshness, concurrent changes, and failure behavior. Keep that extension separate from proving the selection rule on an approved snapshot.

Test correctness with independent expectations

Carbon and a bicycle shop reviewer compare empty, back-to-back, overlapping, and reversed-interval algorithm cases with Lithium and Hydrogen
Test both valid selections and the conditions under which a collection must be rejected.

Begin with results you can calculate without running the implementation. Empty input should return an empty selection. One valid interval should be selected. A chain of back-to-back intervals should all fit. When every interval overlaps every other interval, only one can be selected. Duplicate IDs and invalid time boundaries should fail. Reordering the same valid records should not change the result because the method establishes its own ordering.

Check several properties of every returned result. Each ID must come from the input, no ID should appear twice, and consecutive selected intervals must be compatible. Also confirm that the original records and order remain unchanged. These properties test validity and interface behavior, but a valid schedule is not automatically maximum-sized. A procedure that always returns one compatible request would pass some of them while missing the objective.

For small collections, independently enumerate all subsets, reject the incompatible ones, and find the largest remaining count. Compare that count with the implementation’s result. This exhaustive check is a useful reference for small tests because it does not rely on the greedy selection rule. It becomes expensive as the collection grows, so it is a test technique for bounded samples rather than a proposed production replacement.

Algorithm checks separate valid input, compatible output, maximum count on small cases, and human approval of the objective
Correctness includes the requested objective as well as a result that looks valid.

Several different maximum-size selections can exist for the same collection. Two requests might have identical intervals, making either one a valid choice when only the count matters. Compare the returned count and compatibility with the independent reference rather than insisting on one arbitrary ID list. When deterministic tie behavior is part of the interface contract, test that behavior separately. The code’s start-time and ID tie rules make its result reproducible; they do not express customer priority or fairness. An owner who needs a different policy must specify it and review its effect on the method and its acceptance criteria.

Keep failing input collections with their expected result or error, actual result, and runtime version. When a test reveals a tie or boundary you had not specified, resolve the contract before rewriting the code. A fix should explain which behavior changed and why. Rerun the relevant tests after that change, preserving earlier examples so the next revision does not reintroduce the same mistake.

Analyze running time and know the limits

The method consists of validation, sorting, and one scan. With an O(nlogn) comparison sort, the overall method has O(nlogn) running time; the scan itself is linear in the number of requests. The copied records and selected list require linear additional storage in this implementation. These are growth descriptions under a stated computational model, not a promise about elapsed seconds on a particular machine.

JavaScript’s built-in sort does not promise one universal implementation or complexity across every runtime. Record the actual engine and test workload when measuring it. Input validation, allocation, comparison work, data transfer, and the surrounding application can affect observed performance. A six-record demonstration cannot establish production latency or a maximum supported business workload. Measure the relevant environment after the correctness contract is stable.

The limits of the objective matter as much as speed. Giving jobs different values produces a weighted problem; accepting the maximum count can then yield a worse total value. Multiple benches, movable start times, required breaks, uncertain durations, or dependencies create other problems. Do not patch those requirements into this procedure while continuing to claim the same guarantee. Reframe the task, choose a suitable method, and verify its assumptions again.

Use Space Office for one reviewed decision rule

A bounded assignment is a written input contract, an implemented selection method, and a test packet against the chosen objective. The customer supplies the meaning of each record, approved examples, resource constraints, expected invalid cases, and project conventions. Lithium can implement the rule. Carbon can test normal, boundary, and failure cases. Hydrogen coordinates and reviews the deliverable against the brief.

The human owner confirms that maximizing request count is appropriate, verifies the records and assumptions, approves any required access, and decides how the result may be used. A selected ID list is a proposal, not an actual booking operation. The current agents and workflow overview help scope that preparation and review process. An LLM may help explain or draft a brief, but the deterministic rule and its evidence still need explicit checks.

An algorithm is useful when its steps, objective, and acceptance evidence agree. Write the problem precisely, trace a small case, justify the choices, and test independently before optimizing or connecting real systems. Expand the procedure only when new requirements are understood, keeping the limitations visible enough that a person can decide whether the result answers the intended business question.

Sources and review notes

Reviewed against the linked primary sources on the checked dates. Search features and citations are selected by their respective platforms; no placement is guaranteed.

Frequently asked questions

What is an algorithm in simple terms?

Algorithm is the term for a precise, computable sequence of steps that produces a result from defined inputs. The method needs a clear objective and decision rules. A program implements the method in a particular language and environment, which introduces additional validation and operating concerns.

Is an algorithm the same as a program?

No. The algorithm is the procedure; the program is an implementation. The same method can be expressed in plain language, a diagram, or different programming languages. An implementation can contain a bug even when its underlying method is sound.

Why does the example sort by finish time?

For the unweighted single-workbench problem with fixed intervals, the earliest-finish method leaves room for later compatible requests and achieves a maximum count. Earliest-start ordering can lose options. The justification depends on the stated problem and does not transfer automatically to weighted jobs, multiple benches, or movable times.

How can I check that a result is correct?

Compare it with hand-calculated cases, verify input membership and compatibility, test empty and boundary cases, and check invalid-input behavior. For small collections, compare the selected count with an independent exhaustive-subset reference. A compatible result alone does not prove that its count is maximum.

Can Space Office implement an algorithm for my workflow?

Lithium can implement a bounded software rule from approved requirements, Carbon can test it, and Hydrogen coordinates and reviews the packet. A human approves the objective, data meaning, access, and final use. The fictional workbench example does not reserve resources or guarantee that its objective suits a real repair business.