Time complexity and space complexity are two ways of measuring an algorithm’s cost: how its work grows, and how its memory needs grow, as the input gets bigger. Both are usually written in Big O notation for the worst case. They answer a scaling question, not a stopwatch question, telling you what happens when your data goes from a thousand items to a million rather than how many seconds one run takes. That’s why two programs that feel equally fast on a small test can behave completely differently once real data arrives.
How Time Complexity Counts Work Instead of Seconds
Time complexity is usually estimated by counting the basic operations an algorithm performs, such as comparisons, additions or assignments.1Wikipedia. Time complexity Each basic operation takes roughly a fixed amount of time, so the number of operations and the running time rise and fall together.1Wikipedia. Time complexity Counting steps therefore gives a measure that doesn’t depend on whether you run the code on a fast laptop or an old phone. What matters is how that count changes as the input grows, which is why the input size gets its own letter, n.
Take searching an unsorted list for a name. If the name happens to be first, you check one item, which is the best case. If it’s last or missing, you check every item, so n checks for n names. Time complexity reports that n, because you can’t promise the lucky case. Double the list and the worst-case work doubles too.
The same algorithm can take different amounts of time on different inputs of the same size.1Wikipedia. Time complexity So complexity is usually quoted for the worst case, meaning the largest amount of work any input of that size can demand.1Wikipedia. Time complexity You may also see best-case and average-case figures, but an unlabelled complexity almost always means the worst case.
Complexity describes the shape of growth, not a measurement in seconds, which makes it useful before you’ve written or run any code at all. A count of steps is only a model, though. You decide which operations to count, and for most code you pick the one that repeats most, such as the comparison inside a loop. An addition, a comparison and an assignment can be treated as costing about the same, because the differences vanish when you only care about growth. Such a count predicts how cost grows, not which of two close programs will win a stopwatch race.
How to Read Big O Notation
Big O notation is the standard shorthand for describing how an algorithm’s cost grows, most often in the worst case.2W3Schools. DSA Time Complexity It treats two growth patterns as the same order when one stays within a fixed multiple of the other as the input gets large.3Wikipedia. Big O notation So constant factors and smaller terms are dropped, and an algorithm doing 3n + 5 steps is simply O(n).
The common classes, from best to worst:
- O(1), constant time: the work stays the same however large the input is, and this is the best class.4freeCodeCamp.org. Big O Cheat Sheet – Time Complexity Chart
- O(log n), logarithmic: the work grows very slowly, as in binary search, which halves the data at each step, and it counts as good.4freeCodeCamp.org. Big O Cheat Sheet – Time Complexity Chart
- O(n), linear: the work grows in step with the input, which is fair.4freeCodeCamp.org. Big O Cheat Sheet – Time Complexity Chart
- O(n log n): slightly worse than linear, and typical of efficient sorting.4freeCodeCamp.org. Big O Cheat Sheet – Time Complexity Chart
- O(n^2), quadratic: doubling the input roughly quadruples the work, as with nested loops.4freeCodeCamp.org. Big O Cheat Sheet – Time Complexity Chart
- O(2^n) and O(n!): the work explodes even for modest inputs, and these are the worst classes.4freeCodeCamp.org. Big O Cheat Sheet – Time Complexity Chart
With 1,000 items, the gaps become concrete. O(1) is one step, and O(log n) is about 10 steps. O(n) is 1,000 steps, and O(n log n) is about 10,000. O(n^2) is a million steps. O(2^n) is more steps than the computer could finish in any useful time.
You can spot most classes in everyday code. Looking something up by its position in an array is O(1). A single loop over the data is O(n). A loop inside a loop over the same data is O(n^2). Repeatedly halving the search range, as in binary search, is O(log n).
Dropping constants doesn’t make them unimportant in practice, since code that does 100 times more work per item will really be slower. Big O compares growth rates, so on its own it can’t tell you which of two algorithms in the same class is faster.
Working Out the Complexity of Your Own Code
Steps that run one after another add up, while loops nested inside each other multiply. A loop followed by another loop is still O(n), but a loop inside a loop is O(n^2).
A step-by-step method works for most loop-based functions. First decide what n is, then find the line that runs most often, usually the one in the innermost loop. Next ask how many times that line runs in terms of n, multiplying the counts of nested loops and adding the counts of separate ones. Finally, drop constants and smaller terms, so a function that does n squared steps plus n more steps is O(n^2). To check, imagine n doubling and ask whether the work roughly doubles, quadruples or stays put.
Checking a list for duplicates shows how much the approach matters. Comparing every item with every other item uses two nested loops, which is O(n^2). Sorting first and then checking neighbours is O(n log n). Storing the items you’ve seen in a hash set brings it down to roughly O(n) on average, at the cost of extra memory.
A recursive function that splits its problem can be described by how many subproblems each call creates and how much smaller each one is.5SpaceComplexity. Recursion Time Complexity: The Tree, the Recurrence, and the Master Theorem The Master Theorem is a ready-made formula for this kind of function: it weighs how fast the subproblems multiply against how fast they shrink.5SpaceComplexity. Recursion Time Complexity: The Tree, the Recurrence, and the Master Theorem Merge sort, which splits the data into two halves per call and merges them in linear time, comes out at O(n log n).
Beginners tend to make a few mistakes when counting. One is treating a built-in call like sort, or a search through a list, as if it took one step, when it hides its own loop. Another is forgetting that two different inputs need two letters, for example O(n + m). A third is calling a loop that stops early O(1) when the worst case still goes through every item.
What Space Complexity Measures
Auxiliary space is the extra memory an algorithm uses temporarily to get its job done.6GeeksforGeeks. What is the difference between Auxiliary space and Space Complexity? Space complexity counts the memory taken by the input as well as that extra working memory.6GeeksforGeeks. What is the difference between Auxiliary space and Space Complexity? So when someone says an algorithm uses O(1) space, they usually mean its extra working memory stays fixed, not that the input takes no room. Sources differ on whether they count the input, so say which you mean; “extra space” is the more common meaning.
Reversing a list shows the difference. Building a new reversed copy needs O(n) extra working memory. Swapping items in place from both ends needs O(1). Both take O(n) time, so they differ only in memory use.
To count memory, tally the variables and data structures your code creates, such as new lists, dictionaries and copies of strings. A list that grows in step with the input is O(n) space, while a handful of counters is O(1). A two-dimensional table with n rows and n columns takes O(n^2) space, which is often the surprise in dynamic programming problems.
Recursion uses memory too. Each recursive call keeps a frame on the call stack, the computer’s list of calls that haven’t finished yet.5SpaceComplexity. Recursion Time Complexity: The Tree, the Recurrence, and the Master Theorem Space use equals the largest number of frames alive at once multiplied by the size of each frame.5SpaceComplexity. Recursion Time Complexity: The Tree, the Recurrence, and the Master Theorem A recursive function that goes n calls deep uses O(n) memory even if it never builds a data structure.
The call stack has a limited size. A recursion that goes too deep runs out of room, and the program fails with a stack overflow. Rewriting the function as a loop often keeps the time complexity the same while cutting memory to O(1).
Average Costs and Random Running Times
A growable array, such as a Python list, occasionally has to copy everything into a bigger block of memory.7Wikipedia. Dynamic array But if it grows by a fixed proportion each time, adding n items takes O(n) time in total.7Wikipedia. Dynamic array Each addition then costs constant time when averaged over many operations, even though a single addition is sometimes slow. This is what “amortized” means.7Wikipedia. Dynamic array
If a growable array doubles its size when full, the expensive copies become rarer as the array gets larger, so they spread out thinly. If it grew by a fixed number of slots instead, the copies would happen so often that adding n items would cost O(n^2) overall. So appending to a list in a loop is still O(n) overall, though the occasional slow append can matter in code where every operation has to be fast.
Randomized algorithms come in two kinds. A Las Vegas algorithm always gives the right answer, but its running time varies with its random choices, so its complexity is stated as an average.8COMPSCI 532: Design and Analysis of Algorithms. COMPSCI 532: Design and Analysis of Algorithms Lecture 10 A Monte Carlo algorithm runs in a predictable time and gives the right answer only with high probability.9Introduction to Probability for Computing. Introduction to Probability for Computing
Trading Memory for Speed
Many problems can be solved faster by storing more, or with less memory by doing more work. This is the time-space trade-off.10Artificial Intelligence. Topological parameters for time-space tradeoff For some hard ordering problems, one known method takes time and memory of about 2^n each, while another uses little memory but needs about 4^n time.11Proceedings of the Twenty-First Annual ACM-SIAM Symposium on Discrete Algorithms. A Space–Time Tradeoff for Permutation Problems Picking an algorithm often means deciding which resource you can spare.
Caching is an everyday version. Saving results you’ve already computed, often called memoization, uses memory to avoid repeating work. A naive recursive Fibonacci function takes exponential time, while one that remembers its answers takes O(n) time and O(n) memory. On a device with little memory, though, the slower approach that saves memory can be the better choice.
To decide which resource to spend, ask first which limit you’re more likely to hit: waiting too long for results or running out of memory. A web service answering many users may spend memory to answer faster, while a program on a small device may do the reverse.
When Big O Doesn’t Predict the Fastest Code
Constants and smaller terms matter most when the input is small.12University of Wisconsin-Madison (CS367). What Is Time and Space Complexity in Algorithms? In one textbook example, a quadratic algorithm beats a linear one below 104 items and loses at every size above that.12University of Wisconsin-Madison (CS367). What Is Time and Space Complexity in Algorithms? In sorting tests, simple O(n^2) sorts were faster than O(n log n) sorts on 10 items.13International Journal of Complexity in Applied Science and Technology. A Comprehensive Analysis of Classical Sorting Algorithms with Diverse Input Conditions But on 100,000 items, quicksort took 0.089 seconds while bubble sort took about 266 seconds.13International Journal of Complexity in Applied Science and Technology. A Comprehensive Analysis of Classical Sorting Algorithms with Diverse Input Conditions
Fast libraries take advantage of this. Many standard sort routines switch to insertion sort for small chunks of data, using the low overhead of a simple algorithm where n is small. The overall complexity still stays at O(n log n).
Big O also ignores machine details such as how well code uses the processor’s cache.14DEV Community. When Big O Lies A processor reads memory in chunks, so code that reads neighbouring items one after another is much faster than code that jumps around. Arrays store items side by side, which suits this pattern, while linked structures can scatter items across memory. That is one reason two O(n) loops can differ by 5 to 10 times in actual speed.15Medium. Why Big-O Notation Lies: Real-World Algorithm Performance Explained
Once you’ve chosen a good complexity, measuring the real code with a profiler shows where the time actually goes.16Middleware. What Is Continuous Profiling? How It Works & Benefits First pick an algorithm with a sensible growth rate for the largest data you expect, then time the real code on realistic data before tuning further.
Problems With No Known Fast Solution
P is the group of yes-or-no problems that can be solved in a number of steps bounded by a polynomial in the input size, such as n^2 or n^3.17claymath.org. THE P VERSUS NP PROBLEM NP is the group of problems where a proposed answer can be checked that quickly, even if finding the answer seems much harder.17claymath.org. THE P VERSUS NP PROBLEM NP-complete problems are the hardest in NP, because every NP problem can be quickly converted into them.17claymath.org. THE P VERSUS NP PROBLEM A fast method for any single NP-complete problem would therefore give fast methods for all of them. Whether one exists is the famous unsolved P versus NP question.
A Sudoku shows the gap between checking and finding. Checking a finished grid against the rules is quick, but finding a solution to a hard puzzle by trying options can take very long. Every problem in P is also in NP, since if you can solve a problem quickly you can certainly check an answer quickly.
For a programmer, scheduling and route-planning problems of this kind often grow exponentially if solved exactly. In practice, programmers use approximate answers or rules of thumb that work well enough. Recognising one of these problems early saves time spent hunting for a perfect fast algorithm that may not exist.

