×

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various competitive programming platforms available nowadays. In competitive programming, you have to solve problems on your merit. But it is also true that in every place, there are some tricks used to solve problems in a short time. These tricks provide some features that take less time to solve problems. So, if you know the tricks, you will surely get the advantage. In this article, we will discuss some tricks which are available in the C++ language, especially in C++ 11.

1. Include all standard libraries

We use many standard libraries to insert different things in our code. These libraries are as follows:

#include <iostream>

#include <algorithm>

#include <vector>

#include <string>

#include <stack>

#include <set>

#include <queue>

#include <map>

Instead of including each standard library individually, use #include <bits/stdc++.h> to include all of them in your project. This would be particularly helpful in a programming contest where speed is of concern. There are numerous header files in <bits/stdc++.h> that you might not need for your project. The time required for compilation may increase as a result.

2. Using range-based for loop

C++ 11 runs for loop across a number of values. It is used as a more readable alternative to the classic for loop that operates over a range of values, such as all of the container's elements. If you wish to iterate sequentially from beginning to end, this C++11 feature is the best. Below the given code is an example of the implementation of the above-said feature.

#include <iostream>
#include <map>
#include <vector>
int main()
{
	std::vector<int> v = { 0, 1, 2, 3, 4, 5 };
	for (auto i : v)
		std::cout << i << ' ';


	std::cout << '\n';
	for (int n : { 0, 1, 2, 3, 4, 5 })
		std::cout << n << ' ';


	std::cout << '\n';
	int a[] = { 0, 1, 2, 3, 4, 5 };
	for (int n : a)
		std::cout << n << ' ';


	std::cout << '\n';
	for (int n : a)
		std::cout << "hello world" << ' ';


	std::cout << '\n';
	std::string str = "earth";
	for (char c : str)
		std::cout << c << ' ';


	std::cout << '\n';
	std::map<int, int> MAP(
		{ { 1, 1 }, { 2, 2 }, { 3, 3 } });
	for (auto i : MAP)
		std::cout << '{' << i.first << ", " << i.second
				<< "}\n";
}

Output:

C++ Tricks for Competitive Programming

3. Use auto to omit the data type of a variable

The auto keyword indicates that the type of the variable being defined will be deduced automatically from its initialiser. When it comes to functions, a return type expression will be used at runtime to determine whether the return type is auto. When generating iterators for containers, it is a good idea to utilise auto to minimise lengthy initialisations. If a variable containing the auto keyword is not initialised at the time of declaration, a compile time error will be occurred. Below the given code is an example of the implementation of the above-said feature.

//First program:
#include <bits/stdc++.h>
using namespace std;


int main()
{
	auto x = 4;
	auto y = 3.37;
	auto ptr = &x;
             auto a = 'a';
            auto t = true;
	cout << typeid(x).name() << endl
		<< typeid(y).name() << endl
		<< typeid(ptr).name() << endl;


	return 0;
}


//Second program:
#include <bits/stdc++.h>
using namespace std;


int main()
{
	set<string> st;
	st.insert({ "world", "is", "very", "nice" });
	for (auto it = st.begin(); it != st.end(); it++)
		cout << *it << " ";


	return 0;
}

Output:

C++ Tricks for Competitive Programming

4. Checking if the number is even or odd without using the % operator

Although utilising the % operator is still preferable, this method can still be useful in certain circumstances (with large numbers). The goal is to determine whether or not the number's final bit is set. The number is odd if the last bit is set; otherwise even. We know that in bitwise and operation, the answer will be 1 if and only if both the bits are 1. We use this technique only. Below the given code is an example of the implementation of the above-said features.

Code using % operator:

#include <iostream>
using namespace std;
bool isEven(int n)
{
	If ( n%2 == 0 )
	return true;
	else
	return false;
}
int main()
{
	int n = 101;
	isEven(n)
	? cout << "Even"
	: cout << "Odd";
	return 0;
}

Output:

C++ Tricks for Competitive Programming

Code using & operator:

#include <iostream>
using namespace std;
bool isEven(int n)
{
	return (!(n & 1));
}
int main()
{
	int n = 101;
	isEven(n)
	? cout << "Even"
	: cout << "Odd";
	return 0;
}

Output:

C++ Tricks for Competitive Programming

5. Use of ternary operator instead of if else statement

It is often seen that we have to use conditional statement in many places. We mainly use if else statements to apply conditions. We use this very frequently because it is easy to use this type of conditional statement in our code. But just think about competitive programming. You have to increase your speed in that situation. So for every conditional case, if you use if-else statement then it will take time to complete your code. But ternary operator can be use as the replacement of if else statement. See the following code to understand how if else statements increase your time and decrease the speed.

Code using if-else statement:

#include <iostream>
using namespace std;
int fun(int n)
{
	If ( n > 100 )
	{
	return 1;
	}
	else
	{
	return 0; 
	}
}
int main()
{
	int n = 50;
	if ( n < 0 )
	{
	return 0;
	}
	else
	{
	cout<< fun(n);
	}
	return 0;
}

Output:

C++ Tricks for Competitive Programming

As you can see, we have spent lot of time for completing this if else statements but if we use ternary operator in same code we will surely get benefit. Let’s see the below code to get more clear idea.

Code using ternary operator:

#include <iostream>
using namespace std;
int fun(int n)
{
     int x;
	n > 100 ? x= 1: x= 0;
	return x;
}
int main()
{
	int n = 50;
	n < 0 ? cout<< 0 : cout << fun( n );
	return 0;
}

Output:

C++ Tricks for Competitive Programming

6. Two variables swapping without use of third variable

Swapping is a very common process in programming problems. Many famous sorting algorithms need swapping as a basic process. So, you can see the importance of swapping. In this process, mainly the values of two variables are interchanged. If we have to swap two numbers then it is necessary to take one more variable to store value. But just think about a big set of data which is to be sorted. Now you have to swap. For every swapping you have to take one extra variable. This thing will surely increase the time complexity. You can reduce this extra complexity by doing xor operation on two variables.

Code using extra variable:

#include <iostream>
using namespace std;
int main()
{
	int a = 50;
	int b = 10;
	cout << a<< endl;
	cout << b<< endl;
	int c = a;
	a = b;
	b = c;
	cout << a<< endl;
	cout << b<< endl;
	return 0;
}

Output:

C++ Tricks for Competitive Programming

As you can see, we have declared one new variable to swap the variable. BY using the XOR operation we can do it more efficiently.  Let’s see the below code to get more clear idea.

Code using ternary operator:

#include <iostream>
using namespace std;
int main()
{ 
int a = 50;
	int b = 10;
	cout << a<<endl;
	cout << b<< endl;
	a ^= b;
	b ^= a;
	a ^= b;
	cout << a<< endl;
	cout << b<< endl;
	return 0; 
}

Output:

C++ Tricks for Competitive Programming

7. Multiplication by 2 and division by 2 easy method

Division by 2 and multiplication by 2 are very common operations which are used in many problems. It is very easy thing to multiply or divide. But just think about the situation when you have to multiply in a loop and the number is very big. The same thing can happen in the case of division. For this reason we can use right shift and left shift operations instead of multiplication and division.

Code using normal multiplication and division:

#include <iostream>
using namespace std;
int main()
{
	int a = 5;
	int b = 1;
	for ( int I = 0; I < a; I++ )
	{
	cout << b<< endl;
	b = b*2;
	}
	for ( int I = 0; I < a; I++ )
	{
	cout << b<< endl;
	b = b/2;
	}
	return 0;
}

Output:

C++ Tricks for Competitive Programming

As you can see, the time complexity increases automatically. But if we use shift operations we will surely get benefit.  Let’s see the below code to get more clear idea.

Code using shift operator:

#include <iostream>
using namespace std;
int main()
{ 
int a = 50;
	int b = 10;
	for ( int I = 0; I < a; I++ )
	{
	cout << b;
	//multiplication with 2
	b = b << 1;
	}
	for ( int I = 0; I < a; I++ )
	{
	cout << b;
	// division by 2
	b = b >> 1;
	}
	return 0;
}

Output:

C++ Tricks for Competitive Programming

Related Topics

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.