memorytimebig-o

Is a code with less time complexity then space complexity possible?


I recently learnt big O notation, so when I analysed complexities of some example codes, I observed almost all had less memory and more time, so I thought if vice versa is possible

Now some example came to me was, say taking input of N* N matrix, and printing out just 1 value at a given index, but when I thought more, essentially if we store N*N matrix, we have to take input, so O(N^2) time complexity is probably essential if I have O(N^2) memory complexity

Is my thinking correct, or is there a counterexample I am missing on


Solution

  • If you think about it it's trivial: yes. Your example is almost right, let me elaborate on yours and give you another example for good measure.

    In your example you are thinking of some code that has to be executed on the moment, without differentiating between input and actual query. If you have to load and query a matrix it's clear that it will be necessary to process all the n^2 matrix entries, so we'll have time and spatial complexity of O(n^2) for this preprocessing, but the query itself will have O(1) as time complexity. It's obvious that for a one time code it's pretty useless, but try to think of a database.

    In a SQL database you'll have each table with the primary key id that works as indexes and thanks to these ids you can have a query with a time complexity of O(log n) whether the spatial complexity could be O(n) or more; so, in effect, we have a code that has less time complexity then space complexity.