From constraints to a target complexity
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)The Constraints box at the bottom of a coding problem is not fine print—it is the biggest legal hint on the page. Reading the maximum value of n tells you which Big O complexity is required before you write a single line of code.
About 10^8 simple steps per second (rule of thumb, not a law)
Constraints are the limits given in a problem, such as n up to 100000. They tell you how fast your solution must be, for example O(n log n) instead of O(n^2).
A judge gives your Java solution about 1 to 2 seconds per test, which is roughly 10⁷ to 10⁸ simple steps. The code below turns a step count into a verdict.
If you plug the maximum n from the constraints into your algorithm's step formula and the result is around 10⁷ or less, your plan will almost certainly pass. If the result is 10⁹ (one billion) or 10¹⁰, your plan will almost certainly fail with Time Limit Exceeded.
Example 1 · Estimating step counts against the 10^8 budget
public class StepBudgetEstimatorDemo { private static final long BUDGET = 100_000_000L; // 10^8 rule-of-thumb budget
public static void checkPlan(String label, long estimatedSteps) { String verdict = (estimatedSteps <= BUDGET) ? "PASSES (< 10^8)" : "TLE RISK (> 10^8)"; System.out.println(label + " -> steps=" + estimatedSteps + " -> " + verdict); }
public static void main(String[] args) { long nSmall = 1_000; checkPlan("n=10^3, O(n^2) ", nSmall * nSmall);
long nLarge = 100_000; checkPlan("n=10^5, O(n^2) ", nLarge * nLarge); long nLogN = nLarge * 17; // log2(100,000) is about 17 checkPlan("n=10^5, O(n logn)", nLogN); checkPlan("n=10^5, O(n) ", nLarge); }}n=10^3, O(n^2) -> steps=1000000 -> PASSES (< 10^8) n=10^5, O(n^2) -> steps=10000000000 -> TLE RISK (> 10^8) n=10^5, O(n logn) -> steps=1700000 -> PASSES (< 10^8) n=10^5, O(n) -> steps=100000 -> PASSES (< 10^8)
What this code does
- For
n = 1,000,n^2 = 1,000,000is 100 times smaller than10^8, soO(n²)passes easily. - For
n = 100,000,n^2 = 10,000,000,000is 100 times larger than10^8, immediately telling you to rejectO(n²)and aim forO(n log n)(1,700,000steps) orO(n)(100,000steps).
Most online judges give your Java solution 1 to 2 seconds per test file. As a practical rule of thumb (not a strict physical law), a single CPU thread in Java 17 can execute roughly 10⁷ to 10⁸ (10 million to 100 million) simple loop steps per second.
- Safe zone (
<= 10^7steps): Finishes well under 1 second even with object allocations. - Borderline zone (
~10^8steps): Passes if the inner loop uses primitiveint[]arithmetic; may time out if every step allocates boxedIntegerobjects or hashes strings. - Timeout zone (
>= 10^9steps): Will exceed a 1-second limit; do not code this plan—optimize it first!
What fits for n ≤ 20, 10^3, 10^5, and 10^6
By combining the 10⁸ step budget with the maximum value of n, you can read the required Big O directly from the problem statement (shown after the code).
Example 2 · When n = 10^9: rejecting O(n) and using O(1) math instead
public class HugeConstraintDemo { // Constraint: 1 <= n <= 1,000,000,000 (10^9) // Problem: Count how many odd numbers exist in 1..n. // // An O(n) loop from 1 to 10^9 takes 1,000,000,000 steps -> TLE! // An O(1) formula (n + 1) / 2 takes 1 step! public static long countOddsUpToN(long n) { return (n + 1) / 2; }
public static void main(String[] args) { System.out.println("Odds in 1..7 : " + countOddsUpToN(7)); System.out.println("Odds in 1..10^9 : " + countOddsUpToN(1_000_000_000L)); }}Odds in 1..7 : 4 Odds in 1..10^9 : 500000000
What this code does
- Seeing
n <= 10^9in the constraints warns you that even a singleforloop from1tonis too slow. - Whenever
n >= 10^9, the intended solution is eitherO(log n)(halving/binary search) orO(1)(a direct mathematical formula).
- n <= 20 -> O(2^n) or O(n * 2^n) (backtracking / subsets).
- n <= 500 -> O(n^3) (three nested loops).
- n <= 2,000 (around 10^3) -> O(n^2) (nested pair or subarray loops).
- n <= 100,000 (10^5) -> O(n log n) or O(n) (sorting, two pointers, sliding window, hashing, binary search).
- n <= 1,000,000 (10^6) -> O(n) or O(log n) (single pass, prefix sums, two pointers).
- n >= 10^9 -> O(log n) or O(1) (binary search on answer, halving loop, or math formula).
When n <= 20, 2²⁰ ≈ 10⁶, so exponential O(2ⁿ) (trying all subsets via backtracking) fits easily. When n <= 1,000 (10³), n² = 10⁶, so a quadratic O(n²) nested loop passes comfortably. When n <= 100,000 (10⁵), n² = 10¹⁰ (way too slow!), so you need O(n log n) or O(n). When n <= 1,000,000 (10⁶), you usually need O(n) (or O(n log n) with light primitive operations). And when n is up to 10⁹ or 10¹⁸, even a linear O(n) loop times out—you must use O(log n) or O(1)!
Picking an approach from the limits
Notice how the constraint narrows down your toolset immediately. Suppose a problem asks for the best subarray and says 1 <= nums.length <= 100,000.
Before you even finish reading the sample test, you know n = 10^5 rules out checking all pairs of (start, end) because n² = 10¹⁰ will time out. You can stop thinking about two nested loops and immediately focus on patterns that run in O(n) or O(n log n)—such as a sliding window, two pointers, prefix sums, or sorting.
- If
n <= 1,000: Check if a cleanO(n²)nested loop solves the problem directly. - If
n = 100,000: RejectO(n²)on paper; look for sorting (O(n log n)), hashing (O(n)), or two pointers (O(n)). - If
n = 1,000,000,000: RejectO(n)on paper; look for binary search (O(log n)) or a direct math formula (O(1)).
When constant factors matter
Big O ignores constant factors, but the JVM does not when n is 500,000 or 1,000,000. Two O(n) solutions can differ by 5× to 10× in real wall-clock speed depending on how much work happens inside each step.
Example 3 · Lowering the constant factor: int[] frequency table vs HashMap
public class ConstantFactorArrayDemo { // Constraint: 1 <= nums.length <= 1,000,000 and 0 <= nums[i] <= 1,000 // Because values are bounded by 1,000, a primitive int[1001] array avoids // boxing 1,000,000 Integer objects in a HashMap! public static int mostFrequentBounded(int[] nums) { int[] freq = new int[1001]; int bestVal = nums[0]; int bestCount = 0; for (int x : nums) { freq[x]++; if (freq[x] > bestCount) { bestCount = freq[x]; bestVal = x; } } return bestVal; }
public static void main(String[] args) { int[] sample = {500, 12, 500, 999, 12, 500}; System.out.println("Most frequent: " + mostFrequentBounded(sample)); }}Most frequent: 500
What this code does
- Both
int[1001]andHashMap<Integer, Integer>giveO(n)time, butfreq[x]++is a direct array access with zero object allocation. - Checking value-range constraints (
0 <= nums[i] <= 1,000) lets you spot when a fast primitive array can replace aHashMap.
- Primitive arrays (
int[],long[]) have a much smaller constant factor than boxed collections (HashMap<Integer, Integer>). Arrays.sort(int[])(primitive Dual-Pivot Quicksort) has a smaller constant factor thanCollections.sort(List<Integer>).- When
n >= 10^5and your code prints thousands of lines,StringBuilderorBufferedWriteravoids slowSystem.out.printlnI/O overhead.
In Java 17, reading and writing a primitive int[] array is a tiny CPU instruction, whereas inserting into a HashMap<Integer, Integer> boxes int into Integer objects, computes a hash, and chases object references on the heap. When n = 10^6 and keys come from a small range (like ASCII characters 0..127 or values 0..100,000), using a primitive int[] array instead of a HashMap keeps the constant factor tiny.
Next step
Check your understanding
10 quick questions