Most Critical Mistakes & Tips in Competitive Programming
Last Updated :
13 Apr, 2023
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 where even the advanced competitive programmers slip.

So the concept of overflow can be seen in competitive coding a lot, the worst problem of not understanding it is, writing a completely perfect code but Still getting the wrong answer, this is because, at higher input ranges, the compiler strips down the result as per the data size hence it's important to remember the basic ranges of data types.
Int => [-109 To 109]
Long Int / long => [-1012,1012]
Long Long Int / long long => [-1018,10^18]
Example:
C++
// C++ Program, to Illustrate General Tips In Competitive
// Programming
// Importing all C++ libraries
#include <bits/stdc++.h>
using namespace std;
// Main method
int main()
{
// Case: Stack Overflow
int a = 100000, b = 100000;
// Expected answer ? 10^10 but
// no the answer you get is 1410065408, error in
// precision.
int c = a * b;
long long int d = a * b;
// Note: Still error will be generated because
// calculation was done on two ints which were later
// converted into long long ie they already
// lost their data before converting
// Print and display on console
cout << c << " " << d << endl;
// Now if we store a value more than its capacity then
// what happens is the number line of range of value
// becomes a number
// Example: Circle, If min val is 1 and max is 9, so if
// we add 1 to 9 it will result in 1, it looped back to
// starting, this is overflow
int p = INT_MAX;
// An example of overflow
cout << "An example of overflow " << p + 1 << endl;
// Long long is way better than double,
// double although can store more than long long but
// in exchange it will cost you your precision.
// We can simply use the below command as follows:
// cout<<fixed(no scientific
// notation)<<setprecision(0){removes decimal}<<variable
// to give value same form as long long
// Question where the answer came wrong coz of
// overflow!!
int t, n;
cin >> t;
while (t--) {
cin >> n;
// Here, before i used int and got wrong answer,
// then made it long long
long long pdt = 1, temp;
for (int i = 0; i < n; i++) {
cin >> temp;
pdt *= temp;
}
if (pdt % 10 == 2 || pdt % 10 == 3 || pdt % 10 == 5)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
}
Java
// Java Program, to Illustrate General Tips In Competitive
// Programming
// Importing required Java libraries
import java.util.*;
public class Main {
// Main method
public static void main(String[] args)
{
// Case: Stack Overflow
int a = 100000, b = 100000;
// Expected answer ? 10^10 but
// no the answer you get is 1410065408, error in
// precision.
int c = a * b;
long d = (long)a * b;
// Note: Still error will be generated because
// calculation was done on two ints which were later
// converted into long long ie they already
// lost their data before converting
// Print and display on console
System.out.println(c + " " + d);
// Now if we store a value more than its capacity
// then what happens is the number line of range of
// value becomes a number Example: Circle, If min
// val is 1 and max is 9, so if we add 1 to 9 it
// will result in 1, it looped back to starting,
// this is overflow
int p = Integer.MAX_VALUE;
// An example of overflow
System.out.println("An example of overflow "
+ (p + 1));
// Long is way better than double,
// double although can store more than long but
// in exchange it will cost you your precision.
// We can simply use the below command as follows:
// System.out.printf("%.0f", variable)
// to give value same form as long
// Scanner to read input
Scanner sc = new Scanner(System.in);
// Question where the answer came wrong coz of
// overflow!!
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
// Here, before i used int and got wrong answer,
// then made it long
long pdt = 1, temp;
for (int i = 0; i < n; i++) {
temp = sc.nextLong();
pdt *= temp;
}
if (pdt % 10 == 2 || pdt % 10 == 3
|| pdt % 10 == 5)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
C#
// C# Program, to Illustrate General Tips In Competitive
// Programming
// Importing required C# libraries
using System;
public class MainClass {
// Main method
public static void Main(string[] args)
{
// Case: Stack Overflow
int a = 100000, b = 100000;
// Expected answer ? 10^10 but
// no the answer you get is 1410065408, error in
// precision.
int c = a * b;
long d = (long)a * b;
// Note: Still error will be generated because
// calculation was done on two ints which were later
// converted into long long ie they already
// lost their data before converting
// Print and display on console
Console.WriteLine(c + " " + d);
// Now if we store a value more than its capacity
// then what happens is the number line of range of
// value becomes a number Example: Circle, If min
// val is 1 and max is 9, so if we add 1 to 9 it
// will result in 1, it looped back to starting,
// this is overflow
int p = int.MaxValue;
// An example of overflow
Console.WriteLine("An example of overflow "
+ (p + 1));
// Long is way better than double,
// double although can store more than long but
// in exchange it will cost you your precision.
// We can simply use the below command as follows:
// Console.WriteLine("{0:0}", variable)
// to give value same form as long
// Reading input
int t = int.Parse(Console.ReadLine());
while (t-- > 0) {
int n = int.Parse(Console.ReadLine());
// Here, before i used int and got wrong answer,
// then made it long
long pdt = 1, temp;
for (int i = 0; i < n; i++) {
temp = long.Parse(Console.ReadLine());
pdt *= temp;
}
if (pdt % 10 == 2 || pdt % 10 == 3
|| pdt % 10 == 5)
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
}
}
Python3
# Case: Stack Overflow
a = 100000
b = 100000
# Expected answer ? 10^10 but
# no the answer you get is 1410065408, error in
# precision.
c = a * b
d = a * b
# Note: Still error will be generated because
# calculation was done on two ints which were later
# converted into long long ie they already
# lost their data before converting
# Print and display on console
print(c, d)
# Now if we store a value more than its capacity then
# what happens is the number line of range of value
# becomes a number
# Example: Circle, If min val is 1 and max is 9, so if
# we add 1 to 9 it will result in 1, it looped back to
# starting, this is overflow
p = float("inf")
# An example of overflow
print("An example of overflow ", p + 1)
# Long long is way better than double,
# double although can store more than long long but
# in exchange it will cost you your precision.
# We can simply use the below command as follows:
# print(fixed(no scientific notation) setprecision(0){removes decimal} variable)
# to give value same form as long long
# Question where the answer came wrong coz of overflow!!
t = int(input())
while t > 0:
n = int(input())
# Here, before i used int and got wrong answer,
# then made it long long
pdt = 1
for i in range(n):
temp = int(input())
pdt *= temp
if pdt % 10 == 2 or pdt % 10 == 3 or pdt % 10 == 5:
print("YES")
else:
print("NO")
t -= 1
Output1410065408 1410065408
An example of overflow -2147483648
Tips For Data Structures
Tip 1: In competitive programming always declare the array globally when you need to have a function along with the main function, globally declared arrays can have a size of 10^7 as they are stored in Data Segments.
Tip 2: Whenever you declare a function where you need to return multiple items, or even in general where your goal is to return an array after some modifications, always go for Pass By Reference (eg void swap(int &a, int &b)), it helps you in two ways one, by reducing the time in making a copy of the data and then processing on it and second, as you're directly working on the main data you can modify as many values as you wish without having to worry about returning the values and dealing with them.
- The limit of the size of an array declared inside the main method is 10^5, coz it's stored in Stack Memory with a memory limit of around 8MB, if the size is more than this then it results in Stack Overflow.
- A very peculiar error occurs sometimes when you're taking multiple strings as input after a cin input. instead of taking required inputs, it automatically takes space as input then takes the remaining two strings, to resolve this use cin.ignore() before using the getline() to take the string as input.
- while forming a new string from another string, instead of using syntax like str = str + str2[I], ie adding character to get a string, this method's time complexity is O(size(string)), Hence listed of adding characters to a string we use push_back(character) whose time complexity is O(n).
Tips on STL
As we already know by far now that STL stands for Standard Template Library in C++, which is a boon for competitive programmers, that contains inbuilt special Data Structures and Algorithm that reduces and optimize your code like Crazy. DO remember following below listed STL data structures tips as follows:
Tip 1: Whenever we need to sort data in a question and remove duplicates, the best practice is to store it in a Set, it automatically sorts the data and as per the property of Set, It only stores unique values.
Tip 2: In questions where we need to find the frequency of all values, the best practice is to use a Map, The property of Map makes it automatically arrange the data in lexicographical order, and just with a little trick, you'll have the most efficient solution.
The same can be done in java as well, below is the code for above tips.
Example
C++
// C++ Program to Illustrate STL Algorithms Tips
// Importing all C++ libraries
// Standard command
#include <bits/stdc++.h>
using namespace std;
// Main method
// From here the code starts executing
int main()
{
// Creating vector and initializing objects
// by passing custom integer numbers
vector<int> v
= { 1, 4, 2, 5, 6, 3, 9, 0, 10, 3, 15, 17, 3 };
// Operation 1
// Finding the minimum element in the array,
// Note: It returns the pointer/iterator
auto min = min_element(v.begin(), v.end());
// Print and display elements on console
cout << "Min element: " << *min << endl;
// Operation 2
// // Finding the maximum element in the array
auto max = max_element(v.begin(), v.end());
cout << "Max Element: " << *max << endl;
// Operation 3
// Sum of all elements, the third parameter tells us
// initial sum ki value kya hai.
auto sum = accumulate(v.begin(), v.end(), 0);
cout << "The sum of all elements: " << sum << endl;
// Operation 4
// Count the frequency of an element in the array/vector
auto cnt = count(v.begin(), v.end(), 3);
cout << "Frequency Of 3 is: " << cnt << endl;
// Operation 5
// Finds an element and returns its pointer
auto elem = find(v.begin(), v.end(), 3);
if (elem != v.end())
cout << "the element is at posn: " << *elem << endl;
else
cout << "Element not found" << endl;
// Operation 6
// Reversing a string or array/vector
// using reverse method
reverse(v.begin(), v.end());
cout << "Reversed Vector: ";
for (auto val : v) {
cout << val << " ";
}
// New line for better readability
cout << endl;
// Operation 7
// Sort array/vector using sort() method
sort(v.begin(), v.end());
cout << "Sorted Vector: ";
for (auto val : v) {
cout << val << " ";
}
}
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
// Creating ArrayList and initializing objects
// by passing custom integer numbers
ArrayList<Integer> list = new ArrayList<>(
Arrays.asList(1, 4, 2, 5, 6, 3, 9, 0, 10, 3, 15, 17, 3));
// Operation 1
// Finding the minimum element in the array,
// Note: It returns the pointer/iterator
int min = Collections.min(list);
// Print and display elements on console
System.out.println("Min element: " + min);
// Operation 2
// Finding the maximum element in the array
int max = Collections.max(list);
System.out.println("Max Element: " + max);
// Operation 3
// Sum of all elements, the third parameter tells us
// initial sum ki value kya hai.
int sum = 0;
for (int val : list) {
sum += val;
}
System.out.println("The sum of all elements: " + sum);
// Operation 4
// Count the frequency of an element in the array/list
int cnt = Collections.frequency(list, 3);
System.out.println("Frequency Of 3 is: " + cnt);
// Operation 5
// Finds an element and returns its pointer
int index = list.indexOf(3);
if (index != -1)
System.out.println("the element is at posn: " + index);
else
System.out.println("Element not found");
// Operation 6
// Reversing a list using Collections.reverse method
Collections.reverse(list);
System.out.print("Reversed List: ");
for (int val : list) {
System.out.print(val + " ");
}
// New line for better readability
System.out.println();
// Operation 7
// Sort array/list using Collections.sort() method
Collections.sort(list);
System.out.print("Sorted List: ");
for (int val : list) {
System.out.print(val + " ");
}
}
}
Python3
# Creating a list and initializing objects
# by passing custom integer numbers
my_list = [1, 4, 2, 5, 6, 3, 9, 0, 10, 3, 15, 17, 3]
# Operation 1
# Finding the minimum element in the list
min_element = min(my_list)
print("Min element:", min_element)
# Operation 2
# Finding the maximum element in the list
max_element = max(my_list)
print("Max element:", max_element)
# Operation 3
# Sum of all elements
sum_of_elements = sum(my_list)
print("The sum of all elements:", sum_of_elements)
# Operation 4
# Count the frequency of an element in the list
frequency_of_3 = my_list.count(3)
print("Frequency of 3 is:", frequency_of_3)
# Operation 5
# Finds an element and returns its index
try:
index = my_list.index(3)
print("The element is at position:", index)
except ValueError:
print("Element not found")
# Operation 6
# Reversing a list using reverse() method
my_list.reverse()
print("Reversed List:", my_list)
# Operation 7
# Sort list using sort() method
my_list.sort()
print("Sorted List:", my_list)
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass
{
public static void Main(string[] args)
{
// Creating List and initializing objects
// by passing custom integer numbers
List<int> list = new List<int>
{
1, 4, 2, 5, 6, 3, 9, 0, 10, 3, 15, 17, 3
};
// Operation 1
// Finding the minimum element in the list
int min = list.Min();
// Print and display elements on console
Console.WriteLine("Min element: " + min);
// Operation 2
// Finding the maximum element in the list
int max = list.Max();
Console.WriteLine("Max Element: " + max);
// Operation 3
// Sum of all elements
int sum = list.Sum();
Console.WriteLine("The sum of all elements: " + sum);
// Operation 4
// Count the frequency of an element in the list
int cnt = list.Count(x => x == 3);
Console.WriteLine("Frequency Of 3 is: " + cnt);
// Operation 5
// Finds an element and returns its index
int index = list.IndexOf(3);
if (index != -1)
Console.WriteLine("the element is at posn: " + index);
else
Console.WriteLine("Element not found");
// Operation 6
// Reversing a list using list.Reverse method
list.Reverse();
Console.Write("Reversed List: ");
foreach (int val in list)
{
Console.Write(val + " ");
}
// New line for better readability
Console.WriteLine();
// Operation 7
// Sort list using list.Sort() method
list.Sort();
Console.Write("Sorted List: ");
foreach (int val in list)
{
Console.Write(val + " ");
}
}
}
JavaScript
// Creating an array and initializing objects
// by passing custom integer numbers
let myArray = [1, 4, 2, 5, 6, 3, 9, 0, 10, 3, 15, 17, 3];
// Operation 1
// Finding the minimum element in the array
let minElement = Math.min(...myArray);
console.log("Min element:", minElement);
// Operation 2
// Finding the maximum element in the array
let maxElement = Math.max(...myArray);
console.log("Max element:", maxElement);
// Operation 3
// Sum of all elements
let sumOfElements = myArray.reduce((a, b) => a + b, 0);
console.log("The sum of all elements:", sumOfElements);
// Operation 4
// Count the frequency of an element in the array
let frequencyOf3 = myArray.filter(x => x === 3).length;
console.log("Frequency of 3 is:", frequencyOf3);
// Operation 5
// Finds an element and returns its index
let index = myArray.indexOf(3);
if (index !== -1) {
console.log("The element is at position:", index);
} else {
console.log("Element not found");
}
// Operation 6
// Reversing an array using reverse() method
myArray.reverse();
console.log("Reversed Array:", myArray);
// Operation 7
// Sort array using sort() method
myArray.sort((a, b) => a - b);
console.log("Sorted Array:", myArray);
OutputMin element: 0
Max Element: 17
The sum of all elements: 78
Frequency Of 3 is: 3
the element is at posn: 3
Reversed Vector: 3 17 15 3 10 0 9 3 6 5 2 4 1
Sorted Vector: 0 1 2 3 3 3 4 5 6 9 10 15 17
Note: These are some popular algorithms that can make your life easy all have the same pattern of usage ie the name of the function
(lower lim, upper lim+1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem