AAmit’s LibraryLEARN · PRACTISE · REFLECT

BCA

Problem solving and algorithmic thinking

Study map: BCA Semester 1 subject; proposed foundational breakdown, since the brochure supplies no units

An algorithm is a precise method for transforming permitted inputs into the required output. This chapter moves from defining a problem to constructing, tracing, testing, and comparing solutions.

1. Specify the problem before coding

A programming problem is not fully defined by a vague request such as ‘find the largest number’. You need to know what the input contains, what output is required, and what constraints apply. Are the values integers or decimals? May the collection be empty? Do negative values occur? Should the function return the value or its position? Clarifying these questions is part of problem solving, not a delay before the real work.

A useful specification separates preconditions from postconditions. A precondition states what must hold before the algorithm runs: for example, the input is a non-empty finite list of comparable numbers. A postcondition states the promised result: the returned value occurs in the list and is at least as large as every element. This specification permits different implementations while making their correctness assessable.

Constraints influence design. A method that works for ten items may become impractical for millions. Some problems require results quickly; others restrict memory or demand an exact answer. Write down these constraints alongside example inputs and expected outputs. Examples illustrate the specification but do not replace it. A program that passes three examples can still fail on an input nobody considered.

2. Decomposition and abstraction

Decomposition divides a difficult task into smaller responsibilities. To calculate the average mark for a class, you might separate reading the marks, checking validity, adding valid values, counting them, and reporting the result. This makes the overall process easier to reason about and helps identify where errors belong. Each component should have a clear purpose and a clear interface.

Abstraction focuses attention on relevant features while hiding unnecessary detail. When calling a function that validates a mark, the caller should need to know its contract, not every instruction inside it. Good abstraction does not mean ignoring important constraints. If a validation function silently changes invalid values to zero, that behaviour materially changes an average and must be part of the contract.

Decomposition should reflect the problem, not simply divide code into arbitrary lengths. A useful test is whether each component can be described in one clear sentence and whether its output serves another step. For study practice, draw the data flowing between components. This often reveals missing information or unnecessary coupling before any code is written.

3. Sequence, selection, and iteration

Sequence executes steps in a specified order. Selection chooses a path based on a condition. Iteration repeats work until a stopping rule is satisfied. These structures can express a wide range of algorithms, but correctness depends on their details. A condition may use the wrong boundary; a loop may skip an item or never terminate; a sequence may use a value before it has been initialised.

Consider finding the maximum in a non-empty list. Start by setting the candidate to the first element. Then inspect each remaining element. If that element is greater than the candidate, replace the candidate. After all elements have been inspected, return it. Initialising the candidate to zero would be incorrect for a list containing only negative numbers. Starting with a genuine input value avoids this assumption.

Pseudocode expresses the method without binding it to a particular language. Its vocabulary must still be precise: ‘repeat for each remaining element’ is meaningful, while ‘look at the numbers and pick the largest’ omits the actual method. A flowchart can help show decisions, but drawing boxes cannot repair an incomplete specification.

FUNCTION maximum(values)
  REQUIRE length(values) > 0
  candidate = values[0]
  FOR each value after the first
    IF value > candidate
      candidate = value
  RETURN candidate

4. Trace tables, invariants, and termination

A trace records the values of important variables as an algorithm executes. With input [-4, -9, -2], the candidate starts at -4, remains -4 after inspecting -9, and becomes -2 after inspecting -2. This exposes why a zero initialisation would fail. Trace small examples by hand before relying on a computer’s output. Include cases that challenge your assumptions.

An invariant is a statement that remains true at a specified point in every iteration. For maximum finding, after processing the first k elements, the candidate equals the maximum among those k elements. The statement is true initially because the first element is the maximum of a one-element prefix. When the next element is inspected, either the candidate remains valid or it is replaced by the larger new element. After all elements have been processed, the invariant gives the desired result.

Correctness also requires termination. A loop over a finite list terminates because each iteration advances to the next unprocessed element. A while-loop needs a similar argument: some quantity should move toward a stopping condition. If an algorithm produces the right answer only when it happens to stop, it is not yet a complete solution. In exam answers, explain both why the state remains correct and why execution finishes.

5. Search and the importance of preconditions

Linear search examines elements until it finds the target or reaches the end. It works without assuming sorted input. A successful search near the beginning needs little work; an unsuccessful search may inspect every element. When reporting an index, define how repeated values are handled: the first match, any match, or all matches. This is part of the specification.

Binary search repeatedly halves the range of possible positions. It compares the target with a middle element and discards the half that cannot contain the answer. This relies on sorted input and, for the usual efficient implementation, fast access to middle positions. On an unsorted list, the discarded half could contain the target. Calling binary search ‘better’ without mentioning these requirements misses its essential logic.

For n elements, linear search has worst-case time proportional to n. Binary search has worst-case comparisons proportional to log₂ n. But if data must first be sorted for one search, the sorting cost also matters. Algorithm selection depends on the full task: one query or many, mutable or stable data, and the cost of maintaining the required structure.

Further reading: Harvard CS50: algorithms lecture notes

6. Complexity and meaningful tests

Complexity describes how resource use grows with input size. The maximum-finding algorithm performs n−1 comparisons for n values, so its time grows linearly, commonly expressed as O(n). It stores only a candidate and a small amount of loop state in addition to its input, giving O(1) auxiliary space. Big-O notation describes a growth bound; it is not a stopwatch reading and does not capture every implementation detail.

Nested loops are not automatically quadratic. A loop that runs ten times inside a loop over n items still performs work proportional to n. A loop over every pair of n items typically performs work proportional to n². Analyse the number of iterations and the work inside them rather than counting indentation levels. Distinguish auxiliary memory from the storage already occupied by the input.

Tests should address boundaries and failure modes. For maximum finding, use one element, equal elements, mixed signs, all negative values, and a maximum at each end. Decide how empty input is handled. A test suite offers evidence but cannot generally establish correctness for every possible input. Combine tests with a clear specification, a trace, and a correctness argument. This habit remains useful when later studying data structures, databases, and machine learning.

Applied business–computing case: reason, implement and review

A shop must flag orders whose requested quantity exceeds available stock. Specify the inputs and the meaning of availability: physical stock minus existing reservations may differ from the number on the shelf. For each order, validate quantity, retrieve availability, compare values and produce an explicit result. A linear pass through n orders performs work proportional to n under a constant-time lookup assumption; a nested scan through all m inventory entries can require work proportional to n × m.

Correctness comes before speed. Test zero or negative quantity, missing product identity and two orders competing for the same stock. A fast comparison using stale availability can oversell. The business operation may require an atomic reservation or a controlled retry. Explain the algorithm’s preconditions, complexity and boundary with the database transaction. Computers execute the rule; managers decide the fulfilment policy.

Continue with a runnable practice extension

Small algorithms, visible decisions adds beginner call traces, elementary sorting and first-match binary search. Download the original Python lab and its tests, compare the contracts and preserve your inputs. The existing applied dependency-recursion lab remains available.

Study questions and answers

Why is candidate = 0 unsafe when finding a maximum?

An all-negative input would incorrectly return zero, which is not even an element. Initialise from the first element under a non-empty-input precondition.

Can binary search correctly search an arbitrary unsorted list?

No. The decision to discard half of the search range depends on ordering. Without sorted input, that half may contain the target.

Extended practice questions

Define an algorithm and explain why a business process description may need refinement before it becomes one.

An algorithm specifies steps sufficiently precisely to transform defined inputs into an intended result. A process instruction such as handle important orders first is incomplete until importance, ties, missing fields and completion conditions are defined. A business sorting procedure might rank accepted orders by deadline and then identifier, while routing unknown deadlines for human review. The algorithm should terminate on the allowed input and produce a result that can be checked. Coding an ambiguous procedure does not resolve its business meaning; clarification of rules and exceptions comes before reliable automation.

Marking guide: Defined input/output; precise steps; ambiguity/ties; termination; business meaning. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

Trace a linear search for order ID 17 in [5, 9, 17, 22], stopping at the first match.

Compare 17 with the first value, 5: no match. Compare with 9: no match. Compare with 17: match, so stop. The search uses three value comparisons and returns index two with zero-based indexing, or position three in ordinary counting. The fourth item is not inspected. This example assumes the list is available and equality is correctly defined for the identifiers. An absent target would require checking all four items. Recording the trace helps distinguish an algorithm result from an untested assertion that the software found the right order.

Marking guide: Ordered trace; three comparisons; index/position; stop; absent-target boundary. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

Critique choosing an algorithm solely because it performs fewer comparisons on one example.

One trace reveals behaviour for one input, not reliable performance across the input range. Consider size, ordering, duplicate identifiers, absent targets and the cost of preprocessing. Binary search requires suitable ordering; a hash lookup requires a maintained data structure and a defined collision strategy. Correctness and business identifier rules matter before speed comparisons. Measure representative workloads and state what resources are being compared, such as time or memory. The best choice may change when updates are frequent or datasets are small, so an attractive single-example count is insufficient evidence.

Marking guide: Input range; prerequisites; preprocessing/update tradeoffs; correctness; representative measures. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

Frame a research investigation comparing order-lookup approaches for a small retailer.

Define a workload containing realistic lookup frequencies, updates, duplicate handling and unsuccessful searches. Compare a linear list search with an appropriately maintained indexed approach under equivalent identifier rules. Measure latency distributions, memory and update overhead rather than only an average successful lookup. Keep datasets synthetic or responsibly handled, and publish the workload definitions so the comparison can be examined. Investigate which business conditions justify the added maintenance. The contribution is a conditional recommendation grounded in observed tradeoffs, not a claim that one data structure is universally best.

Marking guide: Workload; equivalent semantics; metrics; reproducibility; conditional contribution. Indicative allocation: reasoning 4; application or workings 3; assumptions and limits 3.

Marks: 10

A maximum-finding routine starts with candidate 0 and processes[-8, -3, -5]. Explain the failure and a valid alternative.

If the routine only replaces the candidate when an input is larger, none of the negative inputs exceeds 0, so it returns a value not in the dataset. Initialise from the first element after checking that the collection is nonempty, then compare the remaining elements. The result is−3. Define the empty-input policy explicitly rather than hiding it in a convenient starting value. The business meaning of a maximum, allowed input types and missing values must also be agreed. A trace exposes the error before the routine is embedded in a report.

Marking guide: Incorrect initial value;−3 result; first-element/empty policy; input contract; trace. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Compare an algorithm's correctness with its running-time efficiency.

Correctness asks whether the procedure produces the specified result for the permitted inputs and handles defined exceptions. Efficiency concerns resources such as time and memory as input size changes. A fast routine returning the wrong maximum is not a correct solution, while a correct routine may still be impractical at scale. Use contracts, traces and relevant tests for behaviour, then analyse or measure performance under stated conditions. Complexity describes growth under a model; it does not supply an exact wall-clock time or establish suitability for every business workload.

Marking guide: Behaviour versus resource use; separate evidence; growth versus elapsed time; workload scope. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Trace a linear maximum scan of[4, 1, 7, 3] initialised to the first element. How many remaining-element comparisons occur?

The initial candidate is4. Comparing 1 leaves it4; comparing 7 changes it to7; comparing 3 leaves it7. The returned maximum is7. There are three comparisons with remaining elements for this four-element input, matching n−1 under the stated implementation. This count excludes input validation and does not equal a measured execution time. Duplicate maxima would preserve a maximum value, but choosing the first or last associated record requires a separate tie rule. Specify that rule when the output is used to select a customer, item or employee rather than only a number.

Marking guide: Trace 4/4/7/7;3 comparisons;n−1;time and tie distinctions. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Specify an algorithmic contract and test set for finding the highest valid transaction amount.

Define permitted number types, units, finite values, missing-data treatment and whether negative amounts are allowed. State the empty-result and tie behaviour. Test a singleton, all-negative permitted values, repeated maxima, malformed input and the empty collection, with independently known expected results. Preserve rejected-record counts if invalid entries are excluded. Finance defines the amount's meaning; the programmer implements the contract. An algorithm that passes a few examples is not proved correct for every input, so explain the invariant that the current candidate is the largest accepted value seen so far.

Marking guide: Contract/boundaries; independent cases; rejection visibility; invariant; business ownership. Indicative allocation:reasoning4;application or workings3;assumptions and limits3.

Marks: 10

Revision cards

Define an algorithm and explain why a business process description may need refinement before it becomes one.

An algorithm needs precise inputs, steps and results; business phrases require explicit rules, ties and exception handling.

Trace a linear search for order ID 17 in [5, 9, 17, 22], stopping at the first match.

Three comparisons find ID 17 at zero-based index two, position three; stop before inspecting 22.

A maximum-finding routine starts with candidate 0 and processes[-8, -3, -5]. Explain the failure and a valid alternative.

Starting at0 fails for an all-negative collection. Check nonempty input, initialise from its first value and obtain−3.

Compare an algorithm's correctness with its running-time efficiency.

Correctness concerns the required result; efficiency concerns resource use. Test behaviour first, then assess growth and representative performance.

Trace a linear maximum scan of[4, 1, 7, 3] initialised to the first element. How many remaining-element comparisons occur?

Candidates 4→4→7→7; maximum 7; three remaining-element comparisons. Record-selection ties need their own policy.

Specify an algorithmic contract and test set for finding the highest valid transaction amount.

Define units, validity, empty and tie rules; test edge cases and explain the largest-so-far invariant. Exclusion must be visible.

What precondition does ordinary binary search require?

The searched sequence must be sorted according to the comparison used. Halving an unsorted search space can discard the target. Verify the ordering and define how duplicates and absent values are handled.

Does a fast result on one small input prove good scalability?

No. Examine operation growth, input structure and worst or relevant cases. Timing also depends on hardware and implementation. Test correctness separately: a quickly returned wrong result is not an effective algorithm.

What makes an algorithm's stopping condition important?

It defines when the procedure is finished and what result can be returned. A loop that keeps changing state without a valid stopping rule may never complete. Check empty inputs and boundary cases as well as ordinary examples.

Practice task

Write maximum and linear-search functions in a language of your choice. Give their contracts, trace two inputs, identify a loop invariant, and test boundary cases. Then explain their time and auxiliary-space complexity.

Sources and further reading

  • CS50x syllabus and free course
    Type: Free lectures and course materials; account needed for submissions; paid credentials optional
    Use: Follow the introductory programming sequence and solve its exercises.
  • Algorithms lecture
    Type: Free video and learning material
    Use: See search, sorting, and growth rates demonstrated.

Open interactive reading and progress tools