There is no brute-force solutions
We're used to evaluating an algorithm's time complexity, but we often overlook its Space complexity. However, often the best solution for Time complexity is a brute-force solution for Space complexity and vice versa.
Let’s consider the common problem - given an array of integers, and an integer as a target. We need to return indices of the two numbers such that they add up to target. There is only one solution and we don’t use the same element twice. Maybe you've already guessed this is a leetcode task Two Sum.We'll start from a brute-force solution.
const twoSum = (nums, target) => {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
}As you can see I use two cycles for, one of which is nested. This fact gives us Time complexity O(n2) because there are two loops: outer O(n) and inner O(n).
We can improve our solution by using Hash Map. This is a common pattern for these types of problems. In the case of JavaScript we have an object as the Hash Map.
It’s not hard to calculate Time complexly - O(n). There is only one loop:
const twoSum = (nums, target) => {
const obj = {};
for(let i = 0; i < nums.length; i++) {
let val = target - nums[i];
if(val in obj) {
return [obj[val], i];
} else {
obj[nums[i]] = i;
}
}
}But if we take a look at Space complexity - the second solution isn't as straightforward as it may seem.
For the brute-force solution we have O(1), but for our improved decision - only O(n).
Why does it happen?
The main idea of the second solution - spend additional memory to save time. When we use brute-force - the amount of extra memory does not depend on the size of the input array. It is not important that the array has 5 elements or 1 million elements. In both cases we have several extra variables: i, j. That’s all.
Once we add an object - we consume a new space. The Space complexity increases from O(1) to O(n). Obviously having a small amount of memory (for example, for embedded systems) but acceptable and predictable size of the input data and under less strict time constraints, in most cases we choose the first so-called "brute-force" solution instead of second - improved decision.
