Space complexity
The memory an algorithm uses splits into 3. Input space holds the data it receives. Temporary space holds what it uses while running: variables, objects and function frames. Output space holds the result. For space complexity you count temporary and output, not input, because the input was already there. It's like cooking: you already had the ingredients; what counts is how many pots you dirty and the dish you serve.
Temporary space has 3 parts. Temporary data is the variables, constants and objects created while running. Frame space holds the context of each called function, and it's freed when the function returns. Instruction space holds the compiled program, and it's almost always ignored. When analyzing, you count temporary data, frames and output.
For space you almost always look at the worst case, because memory is a hard requirement: if it runs out, the program crashes. Worst case has 2 meanings. First, the input that asks for the most memory: if with n < 10 it uses little but with large n it creates a list of n, it's O(n). Second, the peak during execution: if at one moment it uses O(1) and at another O(n), the O(n) counts. It's like booking a hall: you book for the moment it's fullest, not the average.
Common space complexities, from smallest to largest: O(1) when the number of variables doesn't depend on n; O(log n) in divide and conquer, like merge sort's stack, or when storing a number's digits; O(n) with lists, stacks or queues of n elements, or recursion n deep; O(n²) with n × n tables, like a matrix or a graph; and O(2ⁿ) with a full binary tree of n levels, which has 2ⁿ − 1 nodes.
Lowering time and space at once is hard: you often gain in one at the cost of the other. Spending more memory to go faster is called trading space for time, and it's the most common, because time is usually worth more. Databases do it with indexes: they take memory and in exchange searches are O(log n) or O(1). The other way round, on a device with very little memory, like a sensor, you can search by walking a list instead of using a hash table: it takes longer but uses less.
