The Wayback Machine - https://web.archive.org/web/20240914184215/https://www.geeksforgeeks.org/precomputation-technique-on-arrays/
Open In App

PreComputation Technique on Arrays

Last Updated : 21 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

This technique relies on fast retreival of already stored data rather than recalculation.

Some Common Pre-Computation Techniques used on Array:

Though pre-computation can be done in various ways over a wide range of questions, in this section we will look at some of the popular techniques of pre-computation:

Prefix/Suffix on 1-D Array:

A prefix array PRE[] is defined on an array ARR[], such that for each index ‘i‘ PRE[i] stores the information about the values from ARR[0] to ARR[i]. This information can be in the form of prefix sum, prefix max, prefix gcd, etc.

Let’s construct prefix array for ARR[] = {4, 2, 1, -1, 3}, to do this we can simply iterate ARR[] from 0 to size-1, and store PRE[i]=ARR[i]+PRE[i-1], after doing this we have PRE[] = {4, 6, 7, 6, 9}

Why do we need this Prefix Array?

  • For simplicity consider the example for Prefix Sum Array. Suppose we have an array ARR[] of size N, and Q queries and for each query, we have to output the sum of values between the index L to R.
  • The Brute Force way of doing this will result in a time complexity of O(N*Q) where we iterate from L to R in each query to know the sum. In order to improve this time complexity we can use Pre-Computation i.e. calculate the Prefix sum array before processing the queries, and then for each query simply return PRE[R]-PRE[L-1] as the result in O(1), the overall complexity then would be O(max(N, Q))
  • The Suffix array is similar to the Prefix array the only difference is that the Suffix array stores the information about the values from index ‘i’ to the end of the array rather that start of the array i..e. SUFFIX[i] stores information about values from ARR[i] to ARR[size-1].

Below is the code to construct a Prefix Sum and Suffix Sum array:

C++




#include <iostream>
using namespace std;
 
// This function prints the array
void print(int arr[], int N)
{
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}
 
// This function calculates the PrefixSum
// of the array
void PrefixSum(int ARR[], int N)
{
 
    // PRE[] array stores the result
    int PRE[N];
    for (int i = 0; i < N; i++) {
 
        // At index 0, no previous values
        // are present
        if (i == 0)
            PRE[i] = ARR[i];
        else
            PRE[i] = PRE[i - 1] + ARR[i];
    }
    cout << "Prefix Sum: ";
    print(PRE, N);
}
 
// This function finds the Suffix
// sum of the array
void SuffixSum(int ARR[], int N)
{
 
    // This array stores the result
    int SUF[N];
    for (int i = N - 1; i >= 0; i--) {
 
        // At index N-1, there is no suffix
        // value available
        if (i == N - 1)
            SUF[i] = ARR[i];
        else
            SUF[i] = SUF[i + 1] + ARR[i];
    }
    cout << "Suffix Sum: ";
    print(SUF, N);
}
 
// Driver code
int main()
{
    int N = 5;
    int ARR[N] = { 4, 2, 1, -1, 3 };
    cout << "Given Array: ";
    print(ARR, N);
 
    // Funtion call to calculate prefix sum
    PrefixSum(ARR, N);
 
    // Function call to calculate suffix sum
    SuffixSum(ARR, N);
    return 0;
}


Java




public class PrefixSuffixSum {
     
    // This function prints the array
    static void print(int[] arr, int N) {
        for (int i = 0; i < N; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
 
    // This function calculates the PrefixSum of the array
    static void prefixSum(int[] arr, int N) {
        // PRE[] array stores the result
        int[] PRE = new int[N];
        for (int i = 0; i < N; i++) {
            // At index 0, no previous values are present
            if (i == 0)
                PRE[i] = arr[i];
            else
                PRE[i] = PRE[i - 1] + arr[i];
        }
        System.out.print("Prefix Sum: ");
        print(PRE, N);
    }
 
    // This function finds the Suffix sum of the array
    static void suffixSum(int[] arr, int N) {
        // This array stores the result
        int[] SUF = new int[N];
        for (int i = N - 1; i >= 0; i--) {
            // At index N-1, there is no suffix value available
            if (i == N - 1)
                SUF[i] = arr[i];
            else
                SUF[i] = SUF[i + 1] + arr[i];
        }
        System.out.print("Suffix Sum: ");
        print(SUF, N);
    }
 
    // Driver code
    public static void main(String[] args) {
        int N = 5;
        int[] ARR = { 4, 2, 1, -1, 3 };
        System.out.print("Given Array: ");
        print(ARR, N);
 
        // Function call to calculate prefix sum
        prefixSum(ARR, N);
 
        // Function call to calculate suffix sum
        suffixSum(ARR, N);
    }
}
//This code is contriuted by chinmaya121221


Python3




# This function prints the array
def print_array(arr, N):
    for i in range(N):
        print(arr[i], end = " ")
    print()
 
# This function calculates the PrefixSum
# of the array
def PrefixSum(ARR, N):
 
    # PRE[] array stores the result
    PRE = [0] * N
    for i in range(N):
 
        # At index 0, no previous values
        # are present
        if (i == 0):
            PRE[i] = ARR[i]
        else:
            PRE[i] = PRE[i - 1] + ARR[i]
    print("Prefix Sum: ", end = "")
    print_array(PRE, N)
 
# This function finds the Suffix
# sum of the array
def SuffixSum(ARR, N):
 
    # This array stores the result
    SUF = [0] * N
    for i in range(N - 1, -1, -1):
 
        # At index N-1, there is no suffix
        # value available
        if (i == N - 1):
            SUF[i] = ARR[i]
        else:
            SUF[i] = SUF[i + 1] + ARR[i]
    print("Suffix Sum: ", end = "")
    print_array(SUF, N)
 
# Driver code
if __name__ == "__main__":
    N = 5
    ARR = [4, 2, 1, -1, 3]
    print("Given Array: ", end = "")
    print_array(ARR, N)
 
    # Funtion call to calculate prefix sum
    PrefixSum(ARR, N)
 
    # Function call to calculate suffix sum
    SuffixSum(ARR, N)


C#




using System;
 
class Program
{
    // This function prints the array
    static void Print(int[] arr, int N)
    {
        for (int i = 0; i < N; i++)
        {
            Console.Write(arr[i] + " ");
        }
        Console.WriteLine();
    }
 
    // This function calculates the PrefixSum of the array
    static void PrefixSum(int[] ARR, int N)
    {
        // PRE array stores the result
        int[] PRE = new int[N];
        for (int i = 0; i < N; i++)
        {
            // At index 0, no previous values are present
            if (i == 0)
                PRE[i] = ARR[i];
            else
                PRE[i] = PRE[i - 1] + ARR[i];
        }
        Console.Write("Prefix Sum: ");
        Print(PRE, N);
    }
 
    // This function finds the Suffix sum of the array
    static void SuffixSum(int[] ARR, int N)
    {
        // SUF array stores the result
        int[] SUF = new int[N];
        for (int i = N - 1; i >= 0; i--)
        {
            // At index N-1, there is no suffix value available
            if (i == N - 1)
                SUF[i] = ARR[i];
            else
                SUF[i] = SUF[i + 1] + ARR[i];
        }
        Console.Write("Suffix Sum: ");
        Print(SUF, N);
    }
 
    static void Main()
    {
        int N = 5;
        int[] ARR = { 4, 2, 1, -1, 3 };
        Console.Write("Given Array: ");
        Print(ARR, N);
 
        // Function call to calculate prefix sum
        PrefixSum(ARR, N);
 
        // Function call to calculate suffix sum
        SuffixSum(ARR, N);
    }
}


Javascript




// This function prints the array
function print(arr, N) {
    for (let i = 0; i < N; i++) {
        console.log(arr[i] + " ");
    }
    console.log();
}
 
 
// This function calculates the PrefixSum
// of the array
function PrefixSum(ARR, N) {
 
    // PRE[] array stores the result
    let PRE = [];
    for (let i = 0; i < N; i++) {
     
        // At index 0, no previous values
        // are present
        if (i === 0)
            PRE[i] = ARR[i];
        else
            PRE[i] = PRE[i - 1] + ARR[i];
    }
    console.log("Prefix Sum: ");
    print(PRE, N);
}
 
// This function finds the Suffix
// sum of the array
function SuffixSum(ARR, N) {
 
    // This array stores the result
    let SUF = [];
    for (let i = N - 1; i >= 0; i--) {
     
        // At index N-1, there is no suffix
        // value available
        if (i === N - 1)
            SUF[i] = ARR[i];
        else
            SUF[i] = SUF[i + 1] + ARR[i];
    }
    console.log("Suffix Sum: ");
    print(SUF, N);
}
 
 
// Driver code
let N = 5;
let ARR = [4, 2, 1, -1, 3];
console.log("Given Array: ");
print(ARR, N);
 
PrefixSum(ARR, N);
 
SuffixSum(ARR, N);


Output

Given Array: 4 2 1 -1 3 
Prefix Sum: 4 6 7 6 9 
Suffix Sum: 9 5 3 2 3 












Prefix on 2-D Array:

The above idea of Prefix on 1-D array can be expanded to 2-D array, where we have a 2-D array ARR[][] of size NxM and PRE[i][j] will store the information about the values from row 0 to ‘i’ and and column 0 to ‘j’ . Let’s say we want to retrieve the sum of values of submatrice [i1, j1] to [i2, j2], we can simply use our 2-D prefix sum array to achieve this by simple Inclusion Exclusion principle PRE[i2][j2] – PRE[i2][j1-1] – PRE[i1-1][j2] + PRE[i1-1][j1-1].

Below is the code construct prefix sum for 2-D array:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
void print(vector<vector<int> >& arr, int N, int M)
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
 
void PrefixSum(vector<vector<int> >& ARR, int N, int M)
{
    vector<vector<int> > PRE(N, vector<int>(M));
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            int x = 0;
            int y = 0;
            int z = 0;
            if (i - 1 >= 0)
                x = PRE[i - 1][j];
            if (j - 1 >= 0)
                y = PRE[i][j - 1];
            if (i - 1 >= 0 && j - 1 >= 0)
                z = PRE[i - 1][j - 1];
            PRE[i][j] = ARR[i][j] + x + y - z;
        }
    }
    cout << "Give Array:" << endl;
    print(ARR, N, M);
    cout << "Prefix Sum Array:" << endl;
    print(PRE, N, M);
}
 
// Drivers code
int main()
{
    int N = 4;
    int M = 4;
 
    vector<vector<int> > ARR = { { 1, 1, 1, 1 },
                                 { 1, 1, 1, 1 },
                                 { 1, 1, 1, 1 },
                                 { 1, 1, 1, 1 } };
 
    // Function Call
    PrefixSum(ARR, N, M);
    return 0;
}


Java




import java.util.Arrays;
 
public class PrefixSum {
 
    // Function to print a 2D array
    static void print(int[][] arr, int N, int M)
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
 
    // Function to compute the prefix sum of a 2D array
    static void prefixSum(int[][] arr, int N, int M)
    {
        int[][] pre = new int[N][M];
 
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                int x = 0, y = 0, z = 0;
                if (i - 1 >= 0)
                    x = pre[i - 1][j];
                if (j - 1 >= 0)
                    y = pre[i][j - 1];
                if (i - 1 >= 0 && j - 1 >= 0)
                    z = pre[i - 1][j - 1];
                pre[i][j] = arr[i][j] + x + y - z;
            }
        }
 
        System.out.println("Given Array:");
        print(arr, N, M);
        System.out.println("Prefix Sum Array:");
        print(pre, N, M);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 4;
        int M = 4;
 
        int[][] arr = { { 1, 1, 1, 1 },
                        { 1, 1, 1, 1 },
                        { 1, 1, 1, 1 },
                        { 1, 1, 1, 1 } };
 
        // Function call
        prefixSum(arr, N, M);
    }
}


Python3




def print_matrix(matrix):
    # Function to print a 2D array
    for row in matrix:
        print(" ".join(map(str, row)))
 
def prefix_sum(matrix, n, m):
    # Function to compute the prefix sum of a 2D array
    prefix = [[0] * m for _ in range(n)]
 
    for i in range(n):
        for j in range(m):
            x = 0 if i - 1 < 0 else prefix[i - 1][j]
            y = 0 if j - 1 < 0 else prefix[i][j - 1]
            z = 0 if i - 1 < 0 or j - 1 < 0 else prefix[i - 1][j - 1]
 
            prefix[i][j] = matrix[i][j] + x + y - z
 
    print("Given Array:")
    print_matrix(matrix)
    print("Prefix Sum Array:")
    print_matrix(prefix)
 
if __name__ == "__main__":
    N = 4
    M = 4
 
    matrix = [
        [1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]
    ]
 
    # Function call
    prefix_sum(matrix, N, M)
 
# This code is contributed by shivamgupta0987654321


C#




using System;
 
class Program {
    // Function to print a 2D array
    static void Print(int[, ] arr, int N, int M)
    {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                Console.Write(arr[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
 
    // Function to compute the prefix sum of a 2D array
    static void PrefixSum(int[, ] ARR, int N, int M)
    {
        int[, ] PRE = new int[N, M];
 
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                int x = 0;
                int y = 0;
                int z = 0;
 
                // Calculate the sum of elements above the
                // current element
                if (i - 1 >= 0)
                    x = PRE[i - 1, j];
 
                // Calculate the sum of elements to the left
                // of the current element
                if (j - 1 >= 0)
                    y = PRE[i, j - 1];
 
                // Calculate the sum of elements in the
                // diagonal (top-left)
                if (i - 1 >= 0 && j - 1 >= 0)
                    z = PRE[i - 1, j - 1];
 
                // Compute the prefix sum for the current
                // element
                PRE[i, j] = ARR[i, j] + x + y - z;
            }
        }
 
        // Print the given array
        Console.WriteLine("Given Array:");
        Print(ARR, N, M);
 
        // Print the computed prefix sum array
        Console.WriteLine("Prefix Sum Array:");
        Print(PRE, N, M);
    }
 
    // Driver code
    static void Main()
    {
        int N = 4;
        int M = 4;
 
        int[, ] ARR = { { 1, 1, 1, 1 },
                        { 1, 1, 1, 1 },
                        { 1, 1, 1, 1 },
                        { 1, 1, 1, 1 } };
 
        // Function Call
        PrefixSum(ARR, N, M);
    }
}


Javascript




function print(arr) {
    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i].join(' '));
    }
    console.log();
}
 
function calculatePrefixSum(ARR) {
    const N = ARR.length;
    const M = ARR[0].length;
     
    // Initialize the prefix sum array
    const PRE = new Array(N);
    for (let i = 0; i < N; i++) {
        PRE[i] = new Array(M).fill(0);
    }
 
    for (let i = 0; i < N; i++) {
        for (let j = 0; j < M; j++) {
            let x = 0;
            let y = 0;
            let z = 0;
 
            if (i - 1 >= 0)
                x = PRE[i - 1][j];
            if (j - 1 >= 0)
                y = PRE[i][j - 1];
            if (i - 1 >= 0 && j - 1 >= 0)
                z = PRE[i - 1][j - 1];
 
            PRE[i][j] = ARR[i][j] + x + y - z;
        }
    }
 
    console.log("Given Array:");
    print(ARR);
    console.log("Prefix Sum Array:");
    print(PRE);
}
 
// Driver's code
const N = 4;
const M = 4;
 
const ARR = [
    [1, 1, 1, 1],
    [1, 1, 1, 1],
    [1, 1, 1, 1],
    [1, 1, 1, 1]
];
 
// Function Call
calculatePrefixSum(ARR);


Output

Give Array:
1 1 1 1 
1 1 1 1 
1 1 1 1 
1 1 1 1 
Prefix Sum Array:
1 2 3 4 
2 4 6 8 
3 6 9 12 
4 8 12 16 












Hashing the Arrays data:

There are times when Hashing can be used for pre-computation and drastically reduce the time complexity of program. Suppose for various query we would require the first index of an element ‘e‘ in the array. Instead of calculating this again and again, we can simply iterate on array once and hash the element to the first index it occurs to and finally retrieve this value in O(1) for each query.

Moreover Hashing can be combined with other precomputation techniques like prefix_sum in order to enhance the usability.

Practice 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



Similar Reads

Precomputation Techniques for Competitive Programming
What is the Pre-Computation Technique?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
15+ min read
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been
10 min read
Decrypt the encoded string with help of Matrix as per given encryption decryption technique
Given an encoded (or encrypted) string S of length N, an integer M. The task is to decrypt the encrypted string and print it. The encryption and decryption techniques are given as: Encryption: The original string is placed in a Matrix of M rows and N/M columns, such that the first character of the Original text or string is placed on the top-left c
6 min read
Reconstruct original string from resultant string based on given encoding technique
A binary string S of length N is constructed from a string P of N characters and an integer X. The choice of the ith character of S is as follows: If the character Pi-X exists and is equal to 1, then Si is 1if the character Pi+X exists and is equal to 1, then Si is 1if both of the aforementioned conditions are false, then Si is 0. Given the resulti
10 min read
LCA in a tree using Binary Lifting Technique
Given a binary tree, the task is to find the Lowest Common Ancestor of the given two nodes in the tree. Let G be a tree then the LCA of two nodes u and v is defined as the node w in the tree which is an ancestor of both u and v and is farthest from the root node. If one node is the ancestor of another one then that particular node is the LCA of tho
14 min read
Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
Given a vertex V of an N-ary tree and an integer K, the task is to print the Kth ancestor of the given vertex in the tree. If there does not exist any such ancestor then print -1.Examples: Input: K = 2, V = 4 Output: 1 2nd parent of vertex 4 is 1.Input: K = 3, V = 4 Output: -1 Approach: The idea is to use Binary Lifting Technique. This technique is
9 min read
Encryption and Decryption of String according to given technique
Given a string S, the task is to encrypt the string and decrypt the string again to the original form. Encryption Technique: If L is the length of the string, then take two values, one the ceil of ?L (say b), and the other floor of ?L (say a), and make a two-dimensional matrix having rows = a, and columns = b. If rows*columns &lt; L, then increase
10 min read
Difference between Backtracking and Branch-N-Bound technique
Algorithms are the methodical sequence of steps which are defined to solve complex problems. In this article, we will see the difference between two such algorithms which are backtracking and branch and bound technique. Before getting into the differences, lets first understand each of these algorithms. Backtracking: Backtracking is a general algor
4 min read
Sum of length of paths from every node to all other nodes using Tree Rerooting technique
For every node in an undirected tree, find the sum of length of paths from it to all other nodes, using Tree Rerooting technique. Rerooting is a dynamic programming technique in trees. Using this a property dp[i] on tree is calculated, when the tree is rooted at i. Example: Input: Consider the tree shown in the image: Output: 12 9 17 14 10 15 15 Ex
15+ min read
Transform and Conquer Technique
The Transform and conquer technique is a way of solving problems by breaking them down into smaller subproblems, solving the smaller subproblems, and then combining the solutions to the subproblems to solve the original problem. This technique can be used to solve problems in many different areas, including mathematics, computer science, and engine
5 min read
Code Optimization Technique (logical AND and logical OR)
Logical AND (&amp;&amp;)While using &amp;&amp; (logical AND), we must put the condition first whose probability of getting false is high so that compiler doesn’t need to check the second condition if the first condition is false. C/C++ Code #include &lt;bits/stdc++.h&gt; using namespace std; // Function to check whether n is odd bool isOdd(int n) {
7 min read
Problem Reduction in Transform and Conquer Technique
What is Problem Reduction?Problem reduction is an algorithm design technique that takes a complex problem and reduces it to a simpler one. The simpler problem is then solved and the solution of the simpler problem is then transformed to the solution of the original problem. Problem reduction is a powerful technique that can be used to simplify comp
7 min read
Javascript Program for Two Pointers Technique
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Let’s see the naive solution.   C/C++ Code &lt;script&gt; // Naive solut
4 min read
Two-Pointer Technique in a Linked List
The two-pointer technique is a common technique used in linked list problems to solve a variety of problems efficiently. It involves using two pointers that traverse the linked list at different speeds or in different directions. Use Cases of Two-Pointer Technique in a Linked List:1. Finding the Middle of a Linked List:One common application of the
3 min read
Representation Change in Transform and Conquer Technique
Representation Change is one of the variants of the Transfer and Conquer technique where the given problem is transformed into another domain that is more familiar or simpler to execute. In the case of representation change, the instance of a given problem is transformed into another representation without affecting the original instance. Character
8 min read
Top 20 Hashing Technique based Interview Questions
Find whether an array is subset of another arrayUnion and Intersection of two Linked ListsFind a pair with given sumFind Itinerary from a given list of ticketsFind four elements a, b, c and d in an array such that a+b = c+dFind the largest subarray with 0 sumCount distinct elements in every window of size kFind smallest range containing elements fr
1 min read
Instance Simplification Method in Transform and Conquer Technique
Instance simplification is one of the Transform and Conquer techniques. To understand Instance Simplification, first let us understand what is transform and conquer. Transform and Conquer is a technique whose main idea is to transfer the problem into some easier or similar versions using some procedure and then solve that easier or simpler versions
9 min read
Sliding Window Technique
Sliding Window problems are problems in which a fixed or variable-size window is moved through a data structure, typically an array or string, to solve problems efficiently based on continuous subsets of elements. This technique is used when we need to find subarrays or substrings according to a given set of conditions. Table of Content What is Sli
15+ min read
Rearrange an array in maximum minimum form using Two Pointer Technique
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be a maximum value, at second position minimum value, at third position second max, at fourth position second min, and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Explanation: First 7 is the max value, t
6 min read
Venice Technique
Venice Technique is a strategy where we create a new data structure called Venice Set that mainly helps to answer range queries which involves updating all elements by a common value in constant time. In this article, we will discuss about Venice Technique, the idea behind Venice Technique, its structure, implementation, etc. What is Venice Set?Ven
5 min read
Separate Chaining Collision Handling Technique in Hashing
Separate Chaining is a collision handling technique. Separate chaining is one of the most popular and commonly used techniques in order to handle collisions. In this article, we will discuss about what is Separate Chain collision handling technique, its advantages, disadvantages, etc. What is Collision? Since a hash function gets us a small number
4 min read
Open Addressing Collision Handling technique in Hashing
Open Addressing is a method for handling collisions. In Open Addressing, all elements are stored in the hash table itself. So at any point, the size of the table must be greater than or equal to the total number of keys (Note that we can increase table size by copying old data if needed). This approach is also known as closed hashing. This entire p
7 min read
Two Pointers Technique
Two pointers is really an easy and effective technique that is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Illustration : A[] = {10, 20, 35, 50, 75, 80}X = =70i = 0j = 5A[i] + A[j]
13 min read
Maximum OR sum of sub-arrays of two different arrays
Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12, 1} Output : 22 Explanation: Here, one way to get m
5 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
15+ min read
Count of possible arrays from prefix-sum and suffix-sum arrays
Given 2*N integers which are elements of a prefix and suffix array(in shuffled order) of an array of size N, the task is to find the no of possible array's of the size N which can be made from these elements Examples: Input: arr[] = {5, 2, 3, 5} Output: 2 Explanation: 1st array can be : {2, 3} Its prefix array:{2, 5} Its suffix array:{5, 3} 2nd arr
15+ min read
Difference between Static Arrays and Dynamic Arrays
In the Data structure, we know that an array plays a vital role in having similar types of elements arranged in a contiguous manner with the same data type. According to the concept of array, an array can be defined in two ways as per the memory allocation concept. Types of Arrays:There are basically two types of arrays: Static Array: In this type
5 min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Count of possible unique arrays after swapping elements at same index of given Arrays
Given two arrays arr1[] and arr2[] with distinct elements of size N.The task is to count the total number of possible combinations after swapping elements at the same index of both the arrays such that there are no duplicates in both the arrays after performing the operation. Examples: Input: arr1[] = {1, 2, 3, 4}, arr2[] = {2, 1, 4, 3}, N = 4Outpu
12 min read
Article Tags :
Practice Tags :