Python Competitive Programming Questions

Python Competitive Programming Questions

In today's world, programmers use competitive programming extensively to improve their analytical thinking and problem-solving abilities. It combines algorithmic thought, coding expertise, and a competitive attitude to solve complex programming problems. On the other hand, python is a well-designed language for taking on difficult programming issues because of its simplicity and adaptability. So, in this article, we will see some Python Competitive Programming Questions.

Before moving ahead to the questions, let's have a brief look at Python and Competitive Programming.

What is Python?

The computer language Python is quickly becomes a favourite among developers all over the world because it is robust and flexible. Python has emerged as a preferred language for a wide variety of applications thanks to its readability, simplicity, and large library.

Python has a lot of features and benefits. Some of them are its simplicity and readability, Versatility, extensive library ecosystem, rapid Prototyping development, and strong community support. Applications of Python are in different fields like Web Development, Machine Learning, Scripting, Automation, Scientific Computing, and many more.

What is Competitive Programming?

Competitive programming means taking part in coding contests where individuals or teams must solve algorithmic problems in a set amount of time. These competitions, which can be performed offline or online, put contestants' skills to create effective and optimized algorithms to the test. The problems cover a wide range of subjects, including math, graph theory, dynamic programming, and data structures.

Some of the benefits of Competitive Programming are:

  • Enhancing Problem-Solving Skills
  • Improving Algorithmic Efficiency
  • Strengthening Technical Knowledge
  • Teamwork and Collaboration
  • Performance Under Pressure

Let's start to face different Python Competitive Programming Questions.

Two Sum Problem

In the "Two Sum" problem, the goal is to find two numbers from an array that add up to the given target value. The task is to provide the indices of these integers from the array. It will test the knowledge of arrays, hash tables, and fundamental looping concepts. The complement of each element encountered is stored in a hash table as part of the Python solution, enabling quick search.

Let’s see the code for the two-sum problem in Python:

Example:

def two_Sum(arr, t_value):

    comp_dict = {}

    for i, n in enumerate(arr):

        comp = t_value - n

        if comp in comp_dict:

            return [comp_dict[comp], i]

        comp_dict[n] = i

    return ["Not_Possible"]

arr = [5, 9, 14, 23]

t_value = 23

print(two_Sum(arr, t_value))

The output of this example is:

Output:

[1, 2]

In this example, a target value and an array of integers are the inputs. It stores the complement of each integer it encounters while iterating through the array in a dictionary. If a complement is in the dictionary, it signifies that a pair of numbers has been identified that together equal the desired value. The function outputs the two numbers' indices. The string "Not_Possible" is returned if there is no solution.

Fibonacci Series

The Fibonacci series is a popular programming question that requires generating a series of numbers where each number is the sum of the two before it. To generate the Fibonacci sequence up to a specified number of terms, the Python approach uses a simple loop.

Here is the code for Fibonacci Series:

Example:

def fibonacci(num):

    if(num == 1):

        return [0]

    fib = [0, 1]

    for i in range(2, num):

        fib.append(fib[i-1] + fib[i-2])

    return fib

num = int(input("Enter the number of Fibonacci numbers you want to produce: "))

fibo_series = fibonacci(num)

print(fibo_series)

The output of this code is:

Output:

Enter the number of Fibonacci numbers you want to produce: 4

[0, 1, 1, 2]

In this example, based on user input, the program constructs a Fibonacci series. It defines a Fibonacci function that accepts num as an argument. It returns [0] if the num is 1. If not, a loop is used to generate the Fibonacci series up to the specified integer. The created series is returned after being saved in a list. The code asks the user to enter the desired number of Fibonacci numbers, then calls the Fibonacci function and prints the resulting sequence.

Palindrome Number

When a number is compared to its reverse, and if both the numbers are the same, then it is known as a palindrome number. In other words, a palindrome exists when the number and its reversal are the same.

Here is a Python code to determine whether an integer is a palindrome:

Example:

def is_palindrome(number):

    org_num = str(number)

    rev_num = org_num[::-1]

    if org_num == rev_num:

        return True

    else:

        return False

n = int(input("Enter the number: "))

if is_palindrome(n):

    print("Palindrome")

else:

print("Not a palindrome")

The outputs of this code are:

Output:

Enter the number: 15351

Palindrome

….

Enter the number: 13645

Not a palindrome

In this solution, the function is_palindrome() takes a number as input and determines if it is a palindrome.

First, the number is converted to a string using str(). Then, the string is reversed using string slicing with a step of -1 ([::-1]) and stored in the variable reverse_str.

Next, the original string and the reversed string are compared using an if statement. If they are equal, the number is a palindrome, so the function returns True. Otherwise, it returns False.

This solution effectively checks if a number is a palindrome by converting it to a string, reversing the string, and comparing it to the original string.

Counting Subarrays

Given an array of integers, your task is to count the number of subarrays (contiguous sub-sequences) that have a sum equal to a given target value.

Explanation: The problem of counting subarrays involves finding the number of contiguous subarrays within a given array of integers that have a sum equal to a specified target value. A subarray is defined as a sequence of elements from the original array that are contiguous and maintain their relative order.

The goal is to devise an efficient algorithm to solve this problem and implement the count_subarrayfunction in Python. The function should take the input array nums and the target sum target as parameters and return the count of subarrays that satisfy the given condition.

Here is the solution for the Python competitive programming question Counting Subarrays:

Example:

def count_subarrays(nums, target):

    # Initialize a dictionary to store prefix sums and their counts

    prefix_sums = {0: 1}

    count = 0

    current_sum = 0

    # Iterate through the array and calculate prefix sums

    for num in nums:

        current_sum += num

        complement = current_sum - target

        # Check if complement exists in the prefix sums dictionary

        if complement in prefix_sums:

            count += prefix_sums[complement]

        # Update the count of the current prefix sum

        prefix_sums[current_sum] = prefix_sums.get(current_sum, 0) + 1

    return count

The output for the code will be:

Output:

print(count_subarrays([1, 2, 3, 4, 5], 7))

Output: 2

print(count_subarrays([1, 2, 3, -3, 1], 3))

Output: 3

This solution uses the concept of prefix sums and a dictionary to keep track of the count of prefix sums encountered so far. The algorithm iterates through the input array nums and calculates the prefix sums by continuously adding each element to a running sum. It checks if the complement (difference between the current sum and the target) exists in the prefix sums dictionary. If it does, the count of subarrays with the given target sum is incremented by the count associated with the complement in the dictionary. Finally, the count of subarrays satisfying the condition is returned.

The solution has a time complexity of O(n), where n is the length of the input array nums. This approach allows us to solve the problem efficiently without the need for nested loops.

Longest Increasing Subsequence

Given an array of integers, your task is to find the length of the longest increasing subsequence within the array. An increasing subsequence is a sequence of numbers in the array that are in increasing order but not necessarily consecutive.

Write a function named longest_increasing_subsequence that takes one parameter:

 nums (a list of integers): The input array of integers.

The function should return an integer representing the length of the longest increasing subsequence.

Example:

def longest_increasing_subsequence(nums):

    n = len(nums)

    if n == 0:

        return 0

    dp = [1] * n

    for i in range(1, n):

        for j in range(i):

            if nums[i] > nums[j]:

                dp[i] = max(dp[i], dp[j] + 1)

    return max(dp)

# Interactive input of numbers

nums = []

n = int(input("Enter the number of elements: "))

print("Enter the numbers:")

for _ in range(n):

    num = int(input())

    nums.append(num)

# Calculate and display the length of the longest increasing subsequence

length = longest_increasing_subsequence(nums)

print("Length of the longest increasing subsequence:", length)

Output:

Enter the number of elements: 4

Enter the numbers:

1

2

3

4

Length of the longest increasing subsequence: 4

This program prompts the user to enter the number of elements and allows them to input the numbers one by one. After gathering the input, it calls the longest_increasing_subsequence function with the nums list and stores the result in the length variable. Finally, it prints the length of the longest increasing subsequence.

You can run the program, enter the numbers, and it will calculate and display the length of the longest increasing subsequence based on the input.

Note: The program assumes valid integer inputs for the numbers. It does not perform extensive input validation or error handling.

Conclusion

Python's flexibility and powerful features make it an excellent language for competitive programming. Its extensive libraries, combined with the ability to write clean and concise code, contribute to efficient problem-solving. Engaging in competitive programming with Python not only sharpens technical skills but also nurtures logical thinking and time management abilities. With continuous practice and exploration of different problem domains, programmers can further enhance their competitive programming prowess in Python.

← Prev Next →