The Wayback Machine - https://web.archive.org/web/20241119131910/https://www.geeksforgeeks.org/what-are-online-and-offline-query-based-questions-in-competitive-programming/
Open In App

What are Online and Offline query-based questions in Competitive Programming

Last Updated : 05 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The query-based questions of competitive programming are mainly of two types:

  1. Offline Query.
  2. Online Query.
     

Offline Query

An offline algorithm allows us to manipulate the data to be queried before any answer is printed. This is usually only possible when the queries do not update the original element set before printing the result.

Features:

  1. Offline query offers a much wide range of use as compared to the Online query.
  2. They provide greater usability and opportunity for customizing the return data.
  3. The offline solution first read all queries and preprocess them (like sorting queries for making further process also efficient) then calculate and output the answer of each query in the initial given order.
  4. In an offline setting, all queries are presented in advance.
  5. Problems are easier to solve in an offline setting, as one may be able to reorder the queries or can work on multiple queries at the same time.
  6. Sorting queries and original data can help to achieve better efficiency of O(N + Q) instead of efficiency of O(N * Q) which is common in cases where sorting is not possible as queries keep streaming in as in the case of online queries.

One example of an Offline Query is the Segment Tree.

Example: 

Given an array A[] = {2,3,5,6,7,9} and the task is to answer q queries for this array.
Each query contains two integers l and r and requires to output the sum of the array from l to r.

Necessary Condition For Offline Query: 

This technique can be used only when the answer of one query does not depend on the answers of previous queries since after sorting the order of queries may change.

When to use Offline query:

  1. Offline queries should be used for large reports.
  2. When all the queries are known upfront.

Online Query

To answer the queries in order of their appearance and you can’t pre manipulate the queries for an efficient approach such queries are called online queries. 

Features:

  1. In such kinds of queries, our data may also get updated.
  2. The answer can not be precomputed in advance.
  3. The answer of one query also affects the answer of further queries. So, each query is answered one by one.
  4. Online queries will offer a response shortly after the query, thus allowing a quick resolution for the query.

Example:

Given an array A = {2,3,5,6,7,9} and the task is to answer q queries for this array.
Each query is of two types

  1. Update the ith index by A[i] = x 
  2. Find sum from l to r

In this example after each query, the data of the array is changing. So it can’t be solved by the offline query method.

Necessary Condition For Online Query:

Online queries can be used only when the data is changing and when sorting is not possible due to continuous streaming of queries. 

When to use Online Query:

  1. Online queries should be used when there is a need to query a few transactions at a specific date-time.
  2. They should be used when it is required to query small queries quickly.

Offline Query vs Online Query

Below are some of the differences between offline query and the online query:

S No. Offline Query Online Query
1 This allows to manipulation of the data to be queried before any answer is printed. The queries cannot be pre-manipulated and answer the queries in order of their appearance.
2 Offline queries are possible when the queries do not update the original element set before printing the result. In online queries, the data set may also get updated.
3 Offline queries provide better efficiency of O(N + Q), since sorting of queries and original data is done before computing the result. In the case of online queries, the queries keep on streaming due to which sorting of queries is not possible and efficiency goes to O(N * Q).
4 Offline queries should be used for large reports. Online queries should be used when it is required to query small queries quickly
5 In offline queries, all queries are present in advance. In online queries, the queries keep streaming.
6 In an offline query, the answer of one query does not depend on the answer of the previous query. In an online query, the answer of one query affects the answer of further queries.

Previous Article
Next Article

Similar Reads

Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 min read
How to read Competitive Programming Questions?
Competitive Programming is considered as a sport in the field of computer science. The culture of this sport is growing day by day and a lot of people are also considering this as a career choice. So, to help the participants with improving their efficiency in this sport, in this post, we have tried to cover all possible things, needed to keep in m
5 min read
Number of elements greater than K in the range L to R using Fenwick Tree (Offline queries)
Prerequisites: Fenwick Tree (Binary Indexed Tree)Given an array of N numbers, and a number of queries where each query will contain three numbers(l, r and k). The task is to calculate the number of array elements that are greater than K in the subarray[L, R]. Examples: Input: n=6 q=2 arr[ ] = { 7, 3, 9, 13, 5, 4 } Query1: l=1, r=4, k=6 Query2: l=2,
15+ min read
Creation and Utilisation of Custom Snippets for Competitive programming in VScode
Coding down the whole algorithm from scratch during the online contest can cost you plenty of time and may lead to a bad rank. There is no point in coding the same algorithm you have coded hundreds of times earlier. Why not utilize your previously coded implementations? You can do that by creating custom code snippets and summoning them just by a k
2 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
We have introduced Graph basics in Graph and its representations. In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. Following is an example undirected and unweighted graph with 5 vertices. Below is an adj
7 min read
Input/Output from external file in C/C++, Java and Python for Competitive Programming
In Competitive Programming, most of the time we need to enter input for checking our code manually. But it would become cumbersome if we have a questions like Graphs, strings, or bulky entry of input data because it will definitely time out or the chances of typing incorrect data would be increased. We can easily get rid of problem by simply saving
4 min read
Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2
Prerequisites : Input/Output from external file in C/C++, Java and Python for Competitive Programming In above post,  we saw a way to have standard input/output from external file using file handling. In this post, we will see a very easy way to do this. Here we will compile and run our code from terminal or cmd using  input and output streams. Win
3 min read
Prefix Sum Array - Implementation and Applications in Competitive Programming
Given an array arr[] of size N, find the prefix sum of the array. A prefix sum array is another array prefixSum[] of the same size, such that the value of prefixSum[i] is arr[0] + arr[1] + arr[2] . . . arr[i]. Examples: Input: arr[] = {10, 20, 10, 5, 15}Output: prefixSum[] = {10, 30, 40, 45, 60}Explanation: While traversing the array, update the el
15+ min read
Winning and Losing States for Competitive Programming
In Competitive Programming, we often encounter problems where two players are playing a game optimally and we need to find the winner of the game. In order to solve such problems, we should have a clear understanding of Winning and Losing states of the game. In this article, we will go through the basics of Winning and Losing States and how to iden
4 min read
Stars and Bars Algorithms for Competitive Programming
The Stars and Bars (also known as Balls and Urns) technique is a popular method used in Combinatorics, the study of counting and arrangement. It's a graphical way to solve certain types of problems and is particularly useful when dealing with problems related to the distribution of identical objects into distinct groups. This article will introduce
14 min read
Competitive Programming - Myths and Mind Blowing Facts
Competitive Programming has been the most trending activity to be part of for the whole coders' community on today's date. Competitive programming is a brain game conducted in different sites over the internet, where coders solve the challenges by coding it according to given statements and constraints. But why do most of the coders love it, the an
7 min read
Prefix Function and KMP Algorithm for Competitive Programming
The prefix function is a string matching technique used in computer science and string algorithms. It efficiently computes an array that represents the length of the longest proper prefix which is also a suffix for each prefix of a given string. The Knuth-Morris-Pratt (KMP) algorithm utilizes the prefix function to perform pattern matching in linea
15+ min read
Range Operations and Lazy Propagation for Competitive Programming
In competitive programming, mastering range operations and understanding lazy propagation techniques is a crucial skill set for efficiently handling complex problems involving large datasets. Range operations involve performing actions, such as queries or updates, over a specific range of elements in a data structure, offering a powerful tool for s
15+ min read
How to Focus on Competitive Programming and Web Development Together?
I am 6 Star Coder!I am 5 Star Coder! Can I crack SDE job by doing CP only? But I don't know about web development? You have heard these lines from your friends..... or you are facing the same situation. Learning new technology is always exciting and challenging at the same time. Adding new skills is always a Plus point for a candidate, and learning
8 min read
What is Competitive Programming/Coding and How to Prepare for It?
Programming... Competitive Programming... It teaches you how to think?. If you are a programmer, you might have understood the deep meaning of these lines quoted by Steve Jobs and you might have also experienced that even after shutting down your computer you keep on thinking about programming stuff or code you have written in your project. Once yo
10 min read
Top 10 Algorithms and Data Structures for Competitive Programming
In this post, we will discuss Important top 10 algorithms and data structures for competitive coding. Topics : Graph algorithmsDynamic programmingSearching and Sorting:Number theory and Other MathematicalGeometrical and Network Flow AlgorithmsData StructuresThe links below cover most important algorithms and data structure topics: Graph Algorithms
3 min read
C++: Methods of code shortening in competitive programming
Shortcode is ideal in competitive programming because programs should be written as fast as possible. Because of this, competitive programmers often define shorter names for datatypes and other parts of the code. We here discuss the method of code shortening in C++ specifically.Type names Using the command typedef it is possible to give a shorter n
5 min read
Python in Competitive Programming
In 2017, when ACM allowed Python support for its prestigious competition, the ACM ICPC, a whole new community became interested in the sport of competitive programming. This meant more people coming back to the basics, learning algorithms that are the building blocks of complex packages they use to build their high level packages. Unfortunately, no
3 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Importance of Testing In Competitive Programming
Many times while solving problems, we face issues like time limit exceeds, wrong solution, runtime error, and memory limit exceeds because after designing algorithm we don't test algorithm efficiency, correctness, time complexity and running the algorithm on a large set of inputs for testing purpose. This is where stress testing comes for rescue. S
3 min read
Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
5 Best Languages for Competitive Programming
Needless to say, Competitive Programming is one of the most crucial and popular aspects of a programmer's journey. Though, all the programmers are strongly recommended to participate in such coding challenges to enhance their coding skills and to get various ravishing prizes, rewards, and other career opportunities. Meanwhile, there's a question th
5 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
How to get started with Competitive Programming in JavaScript
Competitive programming is a popular activity among programmers looking to enhance their problem-solving skills and algorithmic thinking. JavaScript is a wonderful language for competitive programming because of how simple it is to use, how powerful its libraries are, and how quickly it can prototype ideas. JavaScript is a great option for programm
5 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
Practice Tags :
three90RightbarBannerImg