When starting out in competitive programming, most beginners have no idea what coding style or structure to follow. A great way to learn is by examining how problems are typically presented and solved in this environment.
Let’s walk through an example.
Sample Problem: Linear Search
Problem Statement
Given an array of integers and a target element x
, determine whether x
is present in the array. If it is, return the index of its first occurrence; otherwise, return -1
.
Input Format
- The first line contains an integer
T
– the number of test cases. - For each test case:
- Line 1: Integer
n
, the size of the array - Line 2:
n
space-separated integers (the array elements) - Line 3: The target element
x
- Line 1: Integer
Output Format
- For each test case, output the index of
x
in the array. - If
x
is not found, print-1
. - Each output should appear on a new line.
Constraints
- 1 ≤ T ≤ 100
- 1 ≤ n ≤ 100
- 1 ≤ arr[i] ≤ 100
Example
Input:
2
4
1 2 3 4
3
5
10 90 20 30 40
40
Output:
2
4
Explanation:
- In the first test case,
3
is found at index 2. - In the second,
40
is found at index 4.
Sample C++ Program for Beginners
#include<iostream>
using namespace std;
// Function to search for element x in arr[]
int search(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
int main() {
int arr[100], x, t, n;
cin >> t; // Number of test cases
while (t--) {
cin >> n; // Size of the array
for (int i = 0; i < n; i++)
cin >> arr[i]; // Array elements
cin >> x; // Element to search
cout << search(arr, n, x) << "\n";
}
return 0;
}
Common Mistakes Beginners Make
- Adding Unnecessary Output
Avoid printing prompts like “Enter value of n” – most online judges expect clean output matching the problem statement exactly. - Ignoring Output Format
Many problems require specific formatting, such as a newline after every test case. Missing these details can cause your submission to be rejected even if the logic is correct.
How to Start Practicing
You can begin with the linear search problem shown above. Try submitting your solution to any online judge to understand how your code is evaluated.
Once you’re comfortable, move on to beginner-level problems categorized under “School” or “Basic” sections on competitive programming platforms.
Top Platforms for Competitive Programming
- Codeforces
- CodeChef
- HackerEarth
- LeetCode
- AtCoder
- GeeksforGeeks
- SPOJ
- Project Euler
Conclusion
Starting with competitive programming is all about carefully reading problem statements and sticking strictly to the input-output format. As seen in the example, even small formatting errors can result in rejection.
Focus on solving easy problems first to get familiar with the environment and gradually work your way up. With consistent practice on platforms like Codeforces and GeeksforGeeks, you’ll build strong logical and coding skills over time.
Comments are closed