Saturday, November 16, 2024
Google search engine
HomeData Modelling & AIHow to begin with Competitive Programming?

How to begin with Competitive Programming?

 

At the very beginning to competitive programming, barely anyone knows the coding style to be followed. Below is an example to help you understand how problems are crafted in competitive programming.
 

competitive-programming

Let us consider below problem statement as an example. 
Problem Statement: 
 

Linear Search: Given an integer array and an element x, find if element is present in array or not. If element is present, then print index of its first occurrence. Else print -1.
Input: 
First line contains an integer, the number of test cases ‘T’. Each test case should be an integer. Size of the array ‘n’ in the second line. In the third line, input the integer elements of the array in a single line separated by space. Element X should be input in the fourth line, i.e., after entering the elements of array. Repeat the above steps second line onwards for multiple test cases.
Output: 
Print the output in a separate line returning the index of the element X. If the element is not present, then print -1.
Constraints: 
1 <= T <= 100 
1 <= n <= 100 
1 <= arr[i] <= 100
Example Input and Output for Your Program: 
 

Input:
2
4
1 2 3 4
3
5
10 90 20 30 40 
40
Output:
2
4

Explanation: 
 

There are 2 test cases (Note 2 at the beginning of input)
Test Case 1: Input: arr[] = {1, 2, 3, 4},  
                    Element to be searched = 3.
             Output:  2
             Explanation: 3 is present at index 2.

Test Case 2: Input: arr[] = {10, 90, 20, 30, 40}, 
                    Element to be searched = 40.
             Output:  4
             Explanation: 40 is present at index 4.

 

C




// A Sample C program for beginners with Competitive Programming
#include<stdio.h>
 
// This function returns index of element x in arr[]
int search(int arr[], int n, int x)
{
    int i;
    for (i = 0; i < n; i++)
    {
       // Return the index of the element if the element
       // is found
       if (arr[i] == x)
         return i;
    }
 
    //return -1 if the element is not found
    return -1;
}
 
int main()
{
    // Note that size of arr[] is considered 100 according to
    // the constraints mentioned in problem statement.
    int arr[100], x, t, n, i;
 
    // Input the number of test cases you want to run
    scanf("%d", &t);
 
    // One by one run for all input test cases
    while (t--)
    {
        // Input the size of the array
        scanf("%d", &n);
 
        // Input the array
        for (i=0; i<n; i++)
           scanf("%d",&arr[i]);
 
        // Input the element to be searched
        scanf("%d", &x);
 
        // Compute and print result
        printf("%d\n", search(arr, n, x));
    }
    return 0;
}


C++




// A Sample C++ program for beginners with Competitive Programming
#include<iostream>
using namespace std;
 
// This function returns index of element x in arr[]
int search(int arr[], int n, int x)
{
    for (int i = 0; i < n; i++)
    {
        // Return the index of the element if the element
        // is found
        if (arr[i] == x)
            return i;
    }
 
    // return -1 if the element is not found
    return -1;
}
 
int main()
{
    // Note that size of arr[] is considered 100 according to
    // the constraints mentioned in problem statement.
    int arr[100], x, t, n;
 
    // Input the number of test cases you want to run
    cin >> t;
 
    // One by one run for all input test cases
    while (t--)
    {
        // Input the size of the array
        cin >> n;
 
        // Input the array
        for (int i=0; i<n; i++)
            cin >> arr[i];
 
        // Input the element to be searched
        cin >> x;
 
        // Compute and print result
        cout << search(arr, n, x) << "\n";
    }
    return 0;
}


Python3




# A Sample Python program for beginners with Competitive Programming
 
# Returns index of x in arr if it is present,
# else returns -1
def search(arr, x):
    n = len(arr)
    for j in range(0,n):
        if (x == arr[j]):
            return j
    return -1
 
# Input number of test cases
t = int(input())
 
# One by one run for all input test cases
for i in range(0,t):
 
    # Input the size of the array
    n = int(input())
 
    # Input the array
    arr = map(int, input().split())
 
    # Input the element to be searched
    x = int(input())
 
    print(search(arr, x))
 
    # The element can also be searched by index method
    # But you need to handle the exception when element is not found
    # Uncomment the below line to get that working.
    # arr.index(x)


Java




// A Sample Java program for beginners with Competitive Programming
import java.util.*;
import java.lang.*;
import java.io.*;
 
class LinearSearch
{
    // This function returns index of element x in arr[]
    static int search(int arr[], int n, int x)
    {
        for (int i = 0; i < n; i++)
        {
            // Return the index of the element if the element
            // is found
            if (arr[i] == x)
                return i;
        }
 
        // return -1 if the element is not found
        return -1;
    }
 
    public static void main (String[] args) throws IOException
    {
        // Note that size of arr[] is considered 100 according to
        // the constraints mentioned in problem statement.
        int[] arr = new int[100];
 
        // Using BufferedReader class to take input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         
        int t = Integer.parseInt(br.readLine());
         
        // String Buffer to store answer
        StringBuffer sb = new StringBuffer();
 
        // One by one run for all input test cases
        while (t > 0)
        {
            // Input the size of the array
            int n = Integer.parseInt(br.readLine());
 
            // to read multiple integers line
            String line = br.readLine();
            String[] strs = line.trim().split("\\s+");
             
            // Input the array
            for (int i = 0; i < n; i++)
                arr[i] = Integer.parseInt(strs[i]);
 
            // Input the element to be searched
            int x = Integer.parseInt(br.readLine());
 
            // Compute and print result
            sb.append(search(arr, n, x)+"\n");
 
            t--;
        }
         
        System.out.print(sb);
    }
}


Common mistakes by beginners 
 

  1. Program should not print any extra character. Writing a statement like printf(“Enter value of n”) would cause rejection on any platform.
  2. Input and output format specifications must be read carefully. For example, most of the problems expect a new line after every output. So if we don’t write printf(“\n”) or equivalent statement in a loop that runs for all test cases, the program would be rejected.

How to Begin Practice? 
You can begin with above problem itself. Try submitting one of the above solutions here. It is recommended solve problems on Practice for cracking any coding interview.
Now you know how to write your first program in Competitive Programming Environment, you can start with School Practice Problems for Competitive Programming or Basic Practice Problems for Competitive Programming.

Platforms for practicing the Competitive Programming 

Related Courses

Competitive Programming – Live Course

Unleash the competitive programmer within you with our Competitive Programming – Live Course. In this course, you’ll learn important topics of DSA, improving problem-solving & coding skills, various techniques for competitive programming, and efficient implementation of mathematical algorithms. As soon as you start, better will be your programming skills. Enrol Now! We’ll see you inside the course!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments