Explore - LeetCode
Input sizes vs time complexity
The constraints of a problem can be considered as hints because they indicate an upper bound on what your solution's time complexity should be. Being able to figure out the expected time complexity of a solution given the input size is a valuable skill to have. In all LeetCode problems and most online assessments (OA), you will be given the problem's constraints. Unfortunately, you will usually not be explicitly told the constraints of a problem in an interview, but it's still good for practicing on LeetCode and completing OAs. Still, in an interview, it usually doesn't hurt to ask about the expected input sizes.
n <= 10
The expected time complexity likely has a factorial or an exponential with a base larger than 2 -
You should think about backtracking or any brute-force-esque recursive algorithm. n <= 10 is extremely small and usually any algorithm that correctly finds the answer will be fast enough.
10 < n <= 20
The expected time complexity likely involves
Again, this bound is very small, so most algorithms that are correct will probably be fast enough. Consider backtracking and recursion.
20 < n <= 100
At this point, exponentials will be too slow. The upper bound will likely involve
Problems marked as "easy" on LeetCode usually have this bound, which can be deceiving. There may be solutions that run in
Consider brute force solutions that involve nested loops. If you come up with a brute force solution, try analyzing the algorithm to find what steps are "slow", and try to improve on those steps using tools like hash maps or heaps.
100 < n <= 1,000
In this range, a quadratic time complexity
Similar to the previous range, you should consider nested loops. The difference between this range and the previous one is that
1,000 < n < 100,000
In this range, ask yourself if sorting the input or using a heap can be helpful. If not, then aim for an
- Hash map
- A two pointers implementation like sliding window
- Monotonic stack
- Binary search
- Heap
- A combination of any of the above
If you have an
100,000 < n < 1,000,000
1,000,000 < n
With huge inputs, typically in the range of
Other time complexities are possible like
, but this is very rare and will usually only be seen in very advanced problems.