Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
How to begin with Competitive Programming?
Next article icon

How to begin with Competitive Programming?

Last Updated : 26 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

At the very beginning of competitive programming, barely anyone knew 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<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     cout << "Enter the number of test cases: ";     cin >> t;      // One by one run for all input test cases     while (t--)     {         // Input the size of the array for the current test case         cout << "Enter the size of array for this test case: ";         cin >> n;          // Input the array elements for the current test case         cout << "Enter " << n << " elements of array separated by space: ";         for (int i = 0; i < n; i++)             cin >> arr[i];          // Input the element to be searched for the current test case         cout << "Enter the element to be searched: ";         cin >> x;          // Compute and print result         cout << search(arr, n, x) << "\n";     }     return 0; } 
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; } 
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);     }  }  
Python
# 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 print("Enter the 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 for the current test case     print(f"Enter the size of array for test case {i + 1}: ")     n = int(input())      # Input the array elements for the current test case     print(f"Enter {n} elements of array separated by space: ")     arr = list(map(int, input().split()))      # Input the element to be searched for the current test case     print("Enter the element to be searched: ")     x = int(input())      # Print the result of the search operation for the current test case     print(search(arr, x))      # The element can also be searched by the index method     # But you need to handle the exception when the element is not found     # Uncomment the below line to get that working.     # arr.index(x) 
C#
using System;  class Program {     // 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;     }      static void Main(string[] args)     {         // Note that size of arr[] is considered 100 according to         // the constraints mentioned in problem statement.         int[] arr = new int[100];         int x, t, n;          // Input the number of test cases you want to run         Console.Write("Enter the number of test cases: ");         if (!int.TryParse(Console.ReadLine(), out t))         {             Console.WriteLine("Invalid input. Please enter a valid integer.");             return;         }          // One by one run for all input test cases         while (t-- > 0)         {             // Input the size of the array for the current test case             Console.Write("Enter the size of array for this test case: ");             if (!int.TryParse(Console.ReadLine(), out n))             {                 Console.WriteLine("Invalid input. Please enter a valid integer.");                 continue;             }              // Input the array elements for the current test case             Console.Write($"Enter {n} elements of array separated by space: ");             string[] input = Console.ReadLine().Split();             if (input.Length != n)             {                 Console.WriteLine("Invalid input. Please enter exactly n elements separated by space.");                 continue;             }             for (int i = 0; i < n; i++)             {                 if (!int.TryParse(input[i], out arr[i]))                 {                     Console.WriteLine("Invalid input. Please enter valid integers separated by space.");                     continue;                 }             }              // Input the element to be searched for the current test case             Console.Write("Enter the element to be searched: ");             if (!int.TryParse(Console.ReadLine(), out x))             {                 Console.WriteLine("Invalid input. Please enter a valid integer.");                 continue;             }              // Compute and print result             Console.WriteLine(Search(arr, n, x));         }     } } 
JavaScript
// Function to search for the index of element x in arr[] function search(arr, x) {     for (let i = 0; i < arr.length; i++) {         // Return the index of the element if found         if (arr[i] === x)             return i;     }      // Return -1 if the element is not found     return -1; }  // Main function function main() {     let t; // Number of test cases     console.log("Enter the number of test cases: ");     t = parseInt(prompt());      // One by one run for all input test cases     while (t--) {         let n; // Size of the array         console.log(`Enter the size of array for test case ${t + 1}: `);         n = parseInt(prompt());          let arr = new Array(n); // Array to store elements         console.log(`Enter ${n} elements of array separated by space: `);         let elements = prompt().split(' ');          // Convert input string to integer array         for (let i = 0; i < n; i++) {             arr[i] = parseInt(elements[i]);         }          let x; // Element to be searched         console.log("Enter the element to be searched: ");         x = parseInt(prompt());          // Compute and print the result         console.log(`Result for test case ${t + 1}: ${search(arr, x)}`);     } }  // Calling the main function main(); 

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 

  • Codechef
  • Codeforces
  • HackerEarth
  • Leetcode
  • AtCoder
  • GeeksForGeeks
  • SPOJ
  • Project Euler

Must Read

  • Top 10 Algorithms and Data Structures for Competitive Programming. 
  • How to prepare for ACM – ICPC?
  • 25 Essential Concepts for Competitive Programming

Conclusion

In conclusion, competitive programming starts with understanding how to read and follow problem statements carefully. As shown in the linear search example, it's important to stick to the exact input and output formats without adding extra prompts or text. Small mistakes like missing a newline or printing unnecessary messages can lead to rejection. Beginners should focus on solving simple problems first to build confidence and learn the structure of coding challenges. Platforms like Codechef, Leetcode, and GeeksForGeeks offer a great place to practice and improve. With regular practice, anyone can develop strong problem-solving and coding skills.


Next Article
How to begin with Competitive Programming?

K

kartik
Improve
Article Tags :
  • GBlog
  • Competitive Programming
  • DSA
  • GBlog-Competitive-Programming
  • DSA Tutorials

Similar Reads

    Competitive Programming - A Complete Guide
    Competitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust
    8 min read
    Competitive Programming (CP) Handbook with Complete Roadmap
    Welcome to the Competitive Programming Handbook or CP Handbook by GeeksforGeeks! This Competitive Programming Handbook is a go-to resource for individuals aiming to enhance their problem-solving skills and excel in coding competitions. This CP handbook provides a comprehensive guide, covering fundam
    12 min read

    Mathematics for Competitive Programming

    Must do Math for Competitive Programming
    Competitive Programming (CP) doesn’t typically require one to know high-level calculus or some rocket science. But there are some concepts and tricks which are sufficient most of the time. You can definitely start competitive coding without any mathematical background, but maths becomes essential as
    15+ min read
    Pigeonhole Principle for CP | Identification, Approach & Problems
    In competitive programming, where people solve tough problems with computer code, the Pigeonhole Principle is like a secret tool. Even though it's a simple idea, it helps programmers tackle complex challenges. This article is your guide to understanding how this principle works and why it's crucial
    8 min read
    Euler Totient for Competitive Programming
    What is Euler Totient function(ETF)?Euler Totient Function or Phi-function for 'n', gives the count of integers in range '1' to 'n' that are co-prime to 'n'. It is denoted by \phi(n) .For example the below table shows the ETF value of first 15 positive integers: 3 Important Properties of Euler Totie
    8 min read
    Mathematics for Competitive Programming Course By GeeksforGeeks
    Mathematics forms the foundation of problem-solving in Competitive Programming (CP). Mastering key mathematical concepts is crucial for approaching algorithmic challenges effectively. If you're an aspiring competitive programmer or someone who wishes to enhance your problem-solving skills, this Math
    3 min read

    Number Theory for CP

    Binary Exponentiation for Competitive Programming
    In competitive programming, we often need to do a lot of big number calculations fast. Binary exponentiation is like a super shortcut for doing powers and can make programs faster. This article will show you how to use this powerful trick to enhance your coding skills. Table of ContentWhat is Binary
    15+ 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.GCD of Two NumbersFastest Way to Compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The E
    4 min read

    Bit Manipulation for CP

    Bit Manipulation for Competitive Programming
    Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag
    15+ min read
    Bit Tricks for Competitive Programming
    In competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&1
    7 min read
    Bitwise Hacks for Competitive Programming
    Prerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ).   First, we left shift '1' to n position via (1<<n)Then, use the 'O
    14 min read

    Combinatorics for CP

    Inclusion Exclusion principle for Competitive Programming
    What is the Inclusion-Exclusion Principle?The inclusion-exclusion principle is a combinatoric way of computing the size of multiple intersecting sets or the probability of complex overlapping events. Generalised Inclusion-Exclusion over Set:For 2 Intersecting Set A and B: A\bigcup B= A + B - A\bigca
    5 min read

    Greedy for CP

    Binary Search on Answer Tutorial with Problems
    Binary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and
    15+ min read
    Ternary Search for Competitive Programming
    Ternary search is a powerful algorithmic technique that plays a crucial role in competitive programming. This article explores the fundamentals of ternary search, idea behind ternary search with its use cases that will help solving complex optimization problems efficiently. Table of Content What is
    8 min read

    Array based concepts for CP

    What are Online and Offline query-based questions in Competitive Programming
    The query-based questions of competitive programming are mainly of two types: Offline Query.Online Query. Offline Query An offline algorithm allows us to manipulate the data to be queried before any answer is printed. This is usually only possible when the queries do not update the original element
    4 min read
    Precomputation Techniques for Competitive Programming
    What is the Pre-Computation Technique?Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations or data stru
    15+ min read
    PreComputation Technique on Arrays
    Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures(array in this case) in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations are needed multiple times, as
    15 min read
    Frequency Measuring Techniques for Competitive Programming
    Measuring the frequency of elements in an array is a really handy skill and is required a lot of competitive coding problems. We, in a lot of problems, are required to measure the frequency of various elements like numbers, alphabets, symbols, etc. as a part of our problem. Examples: Input: arr[] =
    15+ min read

    Dynamic Programming (DP) for CP

    DP on Trees for Competitive Programming
    Dynamic Programming (DP) on trees is a powerful algorithmic technique commonly used in competitive programming. It involves solving various tree-related problems by efficiently calculating and storing intermediate results to optimize time complexity. By using the tree structure, DP on trees allows p
    15+ 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 e
    15+ min read

    Game Theory for CP

    Interactive Problems in Competitive Programming
    Interactive Problems are those problems in which our solution or code interacts with the judge in real time. When we develop a solution for an Interactive Problem then the input data given to our solution may not be predetermined but is built for that problem specifically. The solution performs a se
    6 min read
    Mastering Bracket Problems for Competitive Programming
    Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec
    4 min read
    MEX (Minimum Excluded) in Competitive Programming
    MEX of a sequence or an array is the smallest non-negative integer that is not present in the sequence.Note: The MEX of an array of size N cannot be greater than N since the MEX of an array is the smallest non-negative integer not present in the array and array having size N can only cover integers
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences