Prerequisite: Time Complexity Analysis
Generally, while doing competitive programming problems on various sites, the most difficult task faced is writing the code under desired complexity otherwise the program will get a TLE ( Time Limit Exceeded ). A naive solution is almost never accepted. So how to know, what complexity is acceptable?
The answer to this question is directly related to the number of operations that are allowed to perform within a second. Most of the sites these days allow 108 operations per second, only a few sites still allow 107 operations. After figuring out the number of operations that can be performed, search for the right complexity by looking at the constraints given in the problem.
Given an array A and a number x, check for a pair in A with the sum as x.
where N is:
1) 1 <= N <= 103 2) 1 <= N <= 105 3) 1 <= N <= 108
For Case 1
A naive solution that is using two for-loops works as it gives us a complexity of O(N2), which even in the worst case will perform 106 operations which are well under 108. Ofcourse O(N) and O(NlogN) is also acceptable in this case.
For Case 2
We have to think of a better solution than O(N2), as in worst case, it will perform 1010 operations as N is 105. So complexity acceptable for this case is either O(NlogN) which is approximately 106 (105 * ~10) operations well under 108 or O(N).
For Case 3
Even O(NlogN) gives us TLE as it performs ~109 operations which are over 108. So the only solution which is acceptable is O(N) which in worst case will perform 10^8 operations.
The code for the given problem can be found on : https://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there-exist-two-elements-in-s-whose-sum-is-exactly-x/
- Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
- How can competitive programming help you get a job?
- How to begin with Competitive Programming?
- C++ tricks for competitive programming (for C++ 11)
- Bit Tricks for Competitive Programming
- Python in Competitive Programming
- A Better Way To Approach Competitive Programming
- Fast I/O for Competitive Programming
- What Are The Best Resources For Competitive Programming?
- How to become a master in competitive programming?
- What is Competitive Programming and How to Prepare for It?
- Bitwise Hacks for Competitive Programming
- Competitive Programming: Conquering a given problem
- Interactive Problems in Competitive Programming
- How to read Competitive Programming Questions?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.