Hey Everyone! When starting out with DSA, many of us get confused about why our solutions get Time Limit Exceeded. We often don't know how to estimate whether our solution will pass the time constraints or not. Let's break this down and understand it clearly!
Most online judges (including LeetCode) have a time limit of 1-2 seconds per test case. Modern computers can perform roughly 10^8 (100 million) simple operations per second.
This gives us a simple way to estimate if our algorithm will be fast enough:
If your algorithm performs more than ~10^8 operations for the given constraints, it will likely give TLE (Time Limit Exceeded).
Look at the problem constraints. For example:
1 <= n <= 10001 <= nums.length <= 10^51 <= n <= 10^9Here's a quick reference table:
| Time Complexity | Max Input Size (n) | Operations for Max n | Will it Pass? |
|---|---|---|---|
| O(1) | Any | 1 | ✅ Always |
| O(log n) | 10^18 | ~60 | ✅ Always |
| O(n) | 10^8 | 10^8 | ✅ Yes |
| O(n log n) | 10^6 | ~2×10^7 | ✅ Yes |
| O(n²) | 10^4 | 10^8 | ✅ Borderline |
| O(n²) | 10^5 | 10^10 | ❌ TLE |
| O(n³) | 500 | 1.25×10^8 | ✅ Borderline |
| O(n³) | 1000 | 10^9 | ❌ TLE |
| O(2^n) | 20 | ~10^6 | ✅ Yes |
| O(2^n) | 30 | ~10^9 | ❌ TLE |
| O(n!) | 11 | ~4×10^7 | ✅ Borderline |
| O(n!) | 12 | ~5×10^8 | ❌ TLE |
Constraint: 2 <= nums.length <= 10^4
Brute Force (O(n²)):
Operations = (10^4)² = 10^8✅ Will pass (but just barely)
Hash Map (O(n)):
Operations = 10^4✅ Will pass easily (and is optimal)
Constraint: 1 <= nums.length <= 2×10^4
Three nested loops (O(n³)):
Operations = (2×10^4)³ = 8×10^12❌ TLE guaranteed
Two nested loops (O(n²)):
Operations = (2×10^4)² = 4×10^8⚠️ Risky - might TLE on some test cases
Prefix sum + hash map (O(n)):
Operations = 2×10^4✅ Will pass comfortably
Constraint: 1 <= nums.length <= 6
Backtracking (O(n! × n)):
Operations = 6! × 6 = 720 × 6 = 4,320✅ Will pass easily
But if the constraint was nums.length <= 10:
Operations = 10! × 10 = 3,628,800 × 10 ≈ 3.6×10^7✅ Still passes (factorial grows slower than exponential for small n)
When you see a constraint, think:
| Constraint | Think | Likely Approach |
|---|---|---|
| n ≤ 10 | Exponential/Factorial is fine | Backtracking, DFS with pruning |
| n ≤ 20 | 2^n is acceptable | Bitmask DP, subset enumeration |
| n ≤ 100 | O(n³) might work | Dynamic Programming |
| n ≤ 1,000 | O(n²) should work | Nested loops, DP |
| n ≤ 10,000 | O(n²) is risky | Optimized nested loops |
| n ≤ 100,000 | Need O(n log n) or better | Sorting, heap, binary search |
| n ≤ 1,000,000 | Need O(n) or O(n log n) | Hash map, two pointers, sliding window |
| n ≤ 10^9 | Need O(log n) or O(1) | Binary search, math formula |
Before coding, always:
NOTE: The 10^8 Rule Is an Estimate, Different judges have different time limits and hardware. Some use 10^9 operations/second. When in doubt, aim for a safety margin.
This simple mental math can save you hours of debugging and rewriting code!
Happy coding! 🚀