The Wayback Machine - https://web.archive.org/web/20240626185121/https://www.geeksforgeeks.org/common-mistakes-avoided-competitive-programming-c-beginners/
Open In App

Common mistakes to be avoided in Competitive Programming in C++ | Beginners

Last Updated : 29 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report
  1. Not using of 1LL or 1ll when needed




    // A program shows problem if we
    // don't use 1ll or 1LL
    #include <iostream>
    using namespace std;
    int main()
    {
        int x = 1000000;
        int y = 1000000;
      
        // This causes overflow even
        // if z is long long int
        long long int z = x*y;
      
        cout << z;
        return 0;
    }

    
    

    Output: -727379968
    

    You might get some other negative value as output. So what is the problem here? The ints are not promoted to long long before multiplication, they remain ints and their product as well. Then the product is cast to long long, but we are late now as overflow has already occurred. Having one of x or y as long long should would work, as the other would be promoted. We can also use 1LL (or 1ll). LL is the suffix for long long, which is 64-bit on most C/C++ implementations. So 1LL, is a 1 of type long long.




    // C++ program to show that use of 1ll
    // fixes the problem in above code.
    #include <iostream>
    using namespace std;
    int main()
    {
        int x = 1000000;
        int y = 1000000;
      
        long long int z = 1LL*x*y;
      
        cout << z;
        return 0;
    }

    
    

    Output: 1000000000000
    

    Here is another place where this trick can help you.




    // Another problematic code that doesn't 
    // use 1LL or 1ll
    #include <iostream>
    using namespace std;
      
    int main()
    {
        // we should use 1LL or 1ll here
        // instead of 1. The correct statement
        // is "long long int z = 1LL << 40;"
        long long int z = 1 << 40;
        cout << z;
        return 0;
    }

    
    

    Output: 0
    
  2. Not using cin.ignore() with getline




    // A program that shows problem if we
    // don't use cin.ignore()
    #include <iostream>
    using namespace std;
      
    int main()
    {
        int n;
        cin >> n;
        string s;
        for(int i = 0; i<n; ++i)
        {
            getline(cin, s);
            cout << s.length() << " ";
            cout << s << endl;
        }
        return 0;
    }

    
    

    Input:
    4
    a b
    c d
    e f
    g h
    Output:
    0 
    3 a b
    3 c d
    3 e f
    

    So what is the problem here?
    This has little to do with the input you provided yourself but rather with the default behavior getline() exhibits. When you provided your input for the integer n (cin >> n), you not only submitted the following, but also an implicit newline was appended to the stream:

        "4\n"

    A newline is always appended to your input when you select Enter or Return when submitting from a terminal. It is also used in files for moving toward the next line. The newline is left in the buffer after the extraction into n until the next I/O operation where it is either discarded or consumed. When the flow of control reaches getline(), the newline will be discarded, but the input will cease immediately. The reason this happens is because the default functionality of this function dictates that it should (it attempts to read a line and stops when it finds a newline).

    Because this leading newline inhibits the expected functionality of your program, it follows that it must be skipped our ignored somehow. One option is to call cin.ignore() after the first extraction. It will discard the next available character so that the newline is no longer intrusive.
    cin.ignore(n, delim);
    This extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.




    // C++ program to show that use of cin.ignore()
    // fixes the problem in above code.
    #include <iostream>
    using namespace std;
      
    int main()
    {
        int n;
        cin >> n;
        string s;
        cin.ignore(1, '\n');
        for (int i = 0; i<n; ++i)
        {
            getline(cin, s);
            cout << s.length() << " ";
            cout << s << endl;
        }
        return 0;
    }

    
    

    Input:
    4
    a b
    c d
    e f
    g h
    Output:
    3 a b
    3 c d
    3 e f
    3 g h
    

    But what if we don’t know how many lines of input are going to be there? We can use this then:




    // C++ program to handle cases when we
    // don't know how many lines of input 
    // are going to be there
    #include <iostream>
    using namespace std;
    int main()
    {
        string s;
        while (getline(cin, s))
        {
            if (s.empty())
                break;
            cout << s << endl;
        }
        return 0;
    }

    
    

    Input:
    a b
    c d
    e f
    g h
    
    Output:
    a b
    c d
    e f
    g h
    
  3. A problem when taking remainders: In a lot of problems, you have to print your solution modulo some large prime (for example 10^9 + 7).




    // Below program shows problem if we
    // don't use don't take remainders
    // properly.
    #include <iostream>
    #define mod 1000000007
    using namespace std;
      
    int main()
    {
        long long int x, y, z;
        cin >> x >> y >> z;
        z = (z + x*y)%mod; // not good practice
        cout << z;
        return 0;
    }

    
    

    Since z + x*y might not fit into long long, the above code can cause problems. The better way is to do this:




    // Program to demonstrate proper
    // ways of taking remainders.
    #include <iostream>
    #define mod 1000000007
    using namespace std;
      
    int main()
    {
        long long int x, y, z;
        cin >> x >> y >> z;
      
        // good practice
        z = ((z%mod) + ((x%mod)*(y%mod))%mod) % mod;
        cout << z;
        return 0;
    }

    
    

    This can save you a lot Wrong Answers so it is better to take mod after every computation that might exceed long long. The test cases are generally designed to make sure you have handled overflow cases properly.
    Why does this work?
    Because (z + x*y)%mod is the same as ((z%mod) + ((x%mod)*(y%mod))%mod)%mod.

  4. cin and cout might cause TLE: In a lot of programs, the cause of TLE is generally based on your algorithm. For example, if n = 10^6 and your algorithm runs in O(n^2) then this won’t pass a 1 second Time Limit. But say, you have found an algorithm that runs in O(n) for n = 10^6. This should pass the 1 second Time Limit.
    What if this is failing?
    One possible reason is that you are using cin and cout for I/O over multiple test cases.
    You can use scanf or printf for the same. You can also use some custom Fast I/O function for the same based on something like getchar() and putchar().

    scanf and printf are faster than cin and cout. See this for more details.

    Custom Fast I/O functions:




    // C++ program to demonstrate fast input and output
      
    // use long long x = fast_input(); to read in x
    inline long long int fast_input(void)
    {
        char t;
        long long int x=0;
        long long int neg=0;
        t = getchar();
        while ((t<48 || t>57) && t!='-')
            t = getchar();
        if (t == '-') //handle negative input
        {
            neg = 1;
            t = getchar();
        }
        while (t>=48 && t<=57)
        {
            x = (x<<3) + (x<<1) + t - 48;
      
            // x<<3 means 8*x and x<<1 means 2*x so we
            // have x = 10*x+(t - 48)
            t = getchar();
        }
      
        if (neg)
            x = -x;
        return x;
    }
      
      
    // use fast_output(x, 0); to print x and a newline
    // use fast_output(x, 1); to print x and a ' ' after
    // the x
    inline void fast_output(long long int x, int mode)
    {
        char a[20];
        long long int i=0, j;
        a[0] = '0';
        if (x < 0)
        {
            putchar('-');
            x = -x;
        }
        if (x==0)
           putchar('0');
        while (x)
        {
            // convert each digit to character and
            // store in char array
            a[i++] = x%10 + 48;
            x /= 10;
        }
      
        // print each character from the array
        for (j=i-1; j>=0; j--)
            putchar(a[j]);
      
        if (mode == 0)
           putchar('\n');
        else putchar(' ');
    }

    
    

Related Articles :
A Better Way To Approach Competitive Programming
C++ tricks for competitive programming (for C++ 11)
Writing C/C++ code efficiently in Competitive programming



Previous Article
Next Article

Similar Reads

Most Critical Mistakes &amp; Tips in Competitive Programming
The moment a beginner hears this word, an image pops up in one's mind where students are sitting in a room full of Computers and coding some out of the world stuff, We'll to be honest it's nothing too hard to grasp so we will be proposing tips that help a programmer to level up faster. So let's begin with the most underrated points on each topic wh
15+ 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
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
GCD (Greatest Common Divisor) Practice Problems for Competitive Programming
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers. Fastest way to compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The Euclidean algorithm is an efficient and widely used method for GCD c
4 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
Tips and Tricks for Competitive Programmers | Set 1 (For Beginners)
This article is a collection of various tips that would help beginners of Competitive programming to get an insight of things that should or shouldn’t be done. Competitive programming can only be improved by “PRACTICE, PRACTICE AND PRACTICE”. Try to solve as many questions you can solve on sites like practice.geeksforgeeks.org. This will enhance yo
6 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
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
Practice Tags :
three90RightbarBannerImg