VOOZH about

URL: https://www.geeksforgeeks.org/dsa/precomputation-techniques-for-competitive-programming/

⇱ Precomputation Techniques for Competitive Programming - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Precomputation Techniques for Competitive Programming

Last Updated : 23 Jul, 2025

Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations or data structures are needed multiple times, as it avoids the need to recalculate them every time.

Time-Space Trade-Off during Pre-Computation: In order to reduce the amount of time, pre-computation relies on quickly accessing the pre-existing data. We need to store that data in some sort of data structure, hence the Auxiliary space requirement increases.

A variety of questions in competitive programming requires printing solution for each Query. Test cases are designed in such a way that if a programmer computes solution again and again for each query then it may result in TLE (Time Limit Exceed).
Pre-Computation allows to store a part of solution before processing the queries and then for each query instead of calculating the solution we just need to retrieve that solution.

For example, let's say you have Q queries and each query requires to traverse an array of size N, this will result in a time complexity of O(Q*N), imagine if we can precompute and store the data in O(N) time and then process each query in O(1) time, then we can clearly see that the complexity drastically drops to O(max(Q,N)).

: We have an array arr[] of size N and for T number of test cases we want to get the following information in O(1)

: Before processing the test cases we can precompute the required data in O(N) as follows:

πŸ‘ Precomputation

Using the above table we can calcultate our requirement in O(1) as:

  • Sum of elements from index L to R = Sum[R]- Sum[L-1]
  • Xor of elements from index L to R = Xor[R]- Xor[L-1]
  • Next Greater element on left of i = nextGreater[i]
  • Next Smaller element on left of i = nextSmall[i]
  • Smallest element on left of i = MinLeft[i]
  • Greatest element on left of i = MaxLeft[i]

Click here to expand your knowledge about Prefix/Suffix Arrays:

Code Snippet forPre-Computation:

:

Let assume, there are Q queries and for each query we have to check if a number is Prime or not.

Brute force: For each query we can check if a number n is prime or not in

Optimal approach: Use sieve of eratosthenes to store the Primality in O(Nlog(logN)) and for each query we can check if a number is prime or not in O(1)

Complexity Analysis:

  • Brute force: )
  • Pre-Computation: O(max(Q, Nlog(logN)))

Code Snippet of check if a number is prime in O(1):

:

Lets assume, there are 'Q' queries and for each query we want to get smallest prime factor of a number 'n'.

Brute force: For each query we can get first prime factor of n in

Optimal approach: Use sieve of eratosthenes to store the Primality in O(Nlog(logN)) and for each query we can check if a number is prime or not in O(1)

Complexity Analysis:

  • Brute force:
  • Pre-Computation:

Code Snippet to get smallest prime factor of a number in O(1):

:

Lets assume, We have T number of test cases and for each test case we want to get FATORIAL , INVERSE FACTORIAL for a number 'n' , also we want calculate to calculate nCr in O(1)

Brute Force: For each test case we can calculate the above requirements in O(N) for a number N.

Optimal approach:

  • We can pre-compute the factorial of all the numbers for 1 to N in O(N) using the following recurence:
    • factorial[i] = i * factorial[i-1]
  • Also inverse factorial can be calculated as:
    • invfact[i]= (i+1) * invfact[i+1];
  • nCr can be calculated as:
    • factorial[n] * inverseFactorial[r] * inverseFactorial[n-r]

Complexity Analysis:

  • Brute Force: O(T * N)
  • Precomputaion approach: O(max(T, N))

Code Snippet to to compute nCr in O(1):

:

Lets assume, We have a string S and Q queries, for each query we want to get the number of occurance of a character in index range L to R.

Brute Force: For each query we can iterate the string from index L to R to know the occurance of desired character in O(N)

Pre-computation approach: We can precompute a 2-D prefix array pSum[][] such that pSum[i][j] stores the number of occurences of j'th aphabet till index i. To compute our require we can use the following formula:

  • Occurrence of j'th character between index L to R= pSum[R][j] - pSum[L-1][j]

Code Snippet of Pre-Computation On Strings:

:

Pre-Computation on trees mainly rely on a node storing information about its subtree, this allows the tree traversal to skip certain nodes and hence reduces the complexity to the height of he tree in most of the cases.
Below data can be pre-computed in case of a tree:

  • Precomputation in Databases
  • Precomputation in Data Analytics
  • Machine Learning and AI
  • Pathfinding
  • Recommendation Systems
  • Precomputation is a common technique that uses fast information retrieval rather than computing again and again.
  • It’s a trade-off between time and space.
  • Different question requires different pre-computation techniques hence to tackle those problem the best we can do is to practice a lot of problems.

Problem

Difficulty

Queries for the product of first N factorials

Easy

Range sum queries without updates

Easy

Range Queries for Frequencies of array elements

Easy

Count Primes in Ranges

Easy

Check in binary array the number represented by a subarray is odd or even

Easy

GCDs of given index ranges in an array

Easy

Mean of range in array

Medium

Difference Array | Range update query in O(1)

Medium

Range sum query using Sparse Table

Medium

Number whose sum of XOR with given array range is maximum

Medium

Number of primes in a subarray (with updates)

Medium

Sum of Interval and Update with Number of Divisors

Medium

Print modified array after multiple array range increment operations

Medium

Sparse Table

Hard

Range Minimum Query (Square Root Decomposition and Sparse Table)

Hard

Range Query on array whose each element is XOR of index value and previous element

Hard

Queries for GCD of all numbers of an array except elements in a given range

Hard

Queries of nCr%p in O(1) time complexity

Hard

Comment
Article Tags:
Article Tags: