Python Competitive Programming Questions for Practice

Python Competitive Programming Questions for Practice

This space is to list Python competitive programming questions.

You can use questions for coding practice. As we progress, I will keep adding more coding questions here.

This initiation is a part of our FREE Python online tutorial.

0. Count Common Factor

This problem is asked in one of the HackerEarth contests.

Problem Statement: Little Robert likes mathematics. Today his teacher has given him two integers and asked him to find out how many integers can divide both numbers. Would you like to help him in completing his school assignment?

Input Formatting: There are two integers, a and b as input to the program.

Output Formatting: Print the number of common factors of a and b. Both the input values should be in a range of 1 to 10^12.


Input: 10 15
Output: 2

Explanation: The common factors of 10 and 15 are 1 and 5. So the answer will be 2.

Python Code:

data  = input()
li = data.split()
a = int(li[0])
b = int(li[1])
def gcd(a, b):
    if (a == 0): 
        return b; 
    return gcd(b%a, a); 
if (a>0 and a<(10**12+1) and b>=1 and b<(10**12+1)):
    count = 1
    for i in range(2, gcd(a, b)+1):
        if a%i==0 and b%i==0:
            count = count+1


  • We are reading two integers as a single input and then splitting it using the split() method.
  • The function gcd() is to find the greatest common divisor.
  • To know how to find the GCD of two numbers, you can go through the function gcd() which uses the recursion technique. It is self-explanatory.

1. Does it Divide?

This problem is asked in the HackerEarth contest.

Problem Statement: Consider a permutation of numbers from 1 to N written on a paper. Let’s denote the product of its element as ‘prod’ and the sum of its elements as ‘sum’. Given a positive integer N, your task is to determine whether ‘prod’ is divisible by ‘sum’ or not.

Input Format: The first input will be an integer T.  It depicts a number of test cases. Followed by the value for each test case. Each test case will contain an integer N (1<= N <=10^9). It is nothing but the length of the permutation.

Output Format: For each test case, print “YEAH” if ‘prod’ is divisible by ‘sum’, otherwise print “NAH”.

Python Code:

testSize = int(input())
for i in range(1,testSize+1):
for n in nArr:
    if n>=1 and n<=(10**9):
        prod = 1
        sum = 0
        for i in range(1, n+1):
            prod = prod*i
            sum = sum+i
        if prod%sum==0:






  • The first input is a number of test cases.
  • Iterate to read all the inputs and store them in the Python list.
  • For each element in the list, calculate prod and sum.
  • Print “YEAH” if the prod is divided by the sum. Otherwise, print “NAH”.

2. Sum of sub-arrays

Cohesity coding question

Python Code:

Cohesity Python coding question
#write your code here
def Solve (N,KΚ,Α):

    while i < N:
        while i < N and A[i] <= K:
            nCount = nCount + 1
            if A[1] - K:
        if bCheck==True:
            nResult = nResult + nCount
        while i< N and A[i] > K:
        return nResult

T = int(input())
for _ in range(T):
    N, K= map(int,input().split())
    out = Solve(N,K,A)

This question is asked in the Cohesity coding round on HackerEarth.

I hope that this code is self-explanatory.

3. Maximum Profit by buying and selling stocks

This competitive coding question is asked in Goldman Sachs.

Problem Statement: Suppose you have given the stock prices for respective days like (100, 180, 260, 310, 40, 535, 695). The stock price for the 1st day is 100, the 2nd day it is 180, and so on. Write a Python program to determine what days the user should buy and sell the stocks to get the maximum profit.

In the above case, in the following scenarios user will get maximum profit.

  • Buy stock on 1st day (100)
  • Sell stock on 4th day (310)
  • Buy stock on 5th day  (100)
  • Sell stock on 7th day (695)

Algorithm steps:

  • Find the local minima (buying stock)
  • Find local maxima (selling stock)
  • Repeat until all days are covered.

Python Program:

liStocks = [100, 180, 260, 310, 40, 535, 695]
#find local minima
def findMin(liStocks):
    for i, val in enumerate(liStocks[:-1]):
        if val < liStocks[i+1]: 
            return i, val 
    return -1, -1
#find local maxima 
def findMax(liStocks): 
    for i, val in enumerate(liStocks[:-1]): 
        if val > liStocks[i+1]:
            return i, val
    return i+1, liStocks[-1]
def buySellStock():
    while index < len(liStocks): 
        i, val = findMin(liStocks[index:]) 
        if i > -1:
            print("bye stock on day ", index+1, val)
        i, val = findMax(liStocks[index:])
        print("sell stock on day ", index+1, val)
if __name__ == "__main__":


buy stock on day 1 100 
sell stock on day 4 310 
buy stock on day 5 40 
sell stock on day 7 695

Note: The above program may not have covered all the corner test cases.

15 Python Competitive Programming Questions

Here is the list of the competitive programming questions asked to the Python developer in the coding interview.

  1. Remove Duplicate Char from String
  2. Hailstone Sequence
  3. Secure Conversation by Encryption and Decryption
  4. Special Elements in Matrix
  5. Next Greater No with the Same set of Digits
  6. Smallest Subarray with Sum Greater than Given Number
  7. Group Anagrams
  8. Find Duplicates in Array in O(n)
  9. Find Two Unique Numbers from Array in O(n)
  10. Number Patterns & Finding Smallest Number
  11. Minimum Cost of Merging Files [Amazon]
  12. Minimum Distance for Truck to Deliver Order [Amazon]
  13. Longest Path in a Weighted Tree
  14. Generate Balanced Parentheses
  15. Post-Order Traversal Without Recursion


I will keep adding more Python Competitive Programming Questions for Practice. Also, I explain each Python tutorial.

Follow this page to help yourself and to find some important tips for competitive programming.


  1. Here is the code I have written for problem 0: Count Common Factor.

    a=int(input("enter first no"))
    b=int(input("enter seconde no"))
    if a&gt;b:
    else :
    for i in range (1,temp+1,1):
            if a%i==0 and b%i==0 :
  2. My approach for question 1.

    import numpy
    li, factor_list = input().split(), []
    for factors1 in range(1, int(li[0]) + 1):
        for factors2 in range(1, int(li[1]) + 1):
            if int(li[0]) % factors1 == 0 and int(li[1]) % factors1 == 0:
                if int(li[0]) % factors2 == 0 and int(li[1]) % factors2 == 0:
    print('Output: ', len(numpy.unique(factor_list)))
  3. a = 15
    b = 10
    if a > b :
        large = a
        large = b
    count = 0
    for i in range(1,large+1):
        if a % i == 0 and b % i == 0 :
        else :
    print('The Number of Cofactors are' , count)
  4. a,b = input("Enter two numbers : ").split(" ")
    a,b = int(a),int(b)
    greater = a if a&gt;b else b
    count = 0
    for n in range(1,greater+1):
        if a % n == 0 and b % n == 0 :
    print(f'Cofactors of {a},{b} : ' , count)
  5. # Maximum Profit by buying and selling stocks
    st=(100, 180, 260, 310, 40, 535, 695)
    ls =[]
    r = len(st)
    temp = []
    for s in t:
        print("bay a stock day"+str(st.index(s)+1)+' in Rs',s)
            for i in range(st.index(s)+1,r):
                sub = 0
                sub = st[i]-s
            m1 =max(temp)
            temp = []
            print("sell a stock day"+str(i+1)+' of profit Rs  ',m1)
            print("sell a stock day"+str(i+1)+' of profit Rs  ',0)

Leave a Reply

Your email address will not be published. Required fields are marked *