Sometimes you can optimize by solving for one of the variables in terms of the others, so that you don't need to waste time computing it.
A common type of "equation" problem is the 2-sum, 3-sum, k-sum, k-sum-smaller, etc problem. Here's a problem that shows the core idea.
Problem: Print out all positive integers a
, b
, and c
that sum to the number 10.
You might think to do a brute force solution like this:
Time Complexity O(n3). We have a triple for-loop.
Space Complexity O(1).
But you can actually do much better than brute-force. Whenever you see a problem like this, you can always write one of the variables using the other variables. Here, you can subtract a and b from both sides of the equation to solve for c, like this:
This equation tells you that the value of c
is completely determined by the values of a
and b
. This is because c = 10 - a - b
. This means we don't need to loop over it. Here's the above code, but where we removed the for-loop over c:
Time Complexity O(n2). We have a double for-loop.
Space Complexity O(1).