0% found this document useful (0 votes)
1 views

Code

The document outlines various programming problems categorized into Arrays, Numbers, Sorting, and String problems, providing explanations and example Python code for each. Key topics include finding smallest/largest numbers, removing duplicates, checking for palindromes, and implementing sorting algorithms. Each problem includes a brief description and a sample code snippet to demonstrate the solution.

Uploaded by

nivashini.j123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Code

The document outlines various programming problems categorized into Arrays, Numbers, Sorting, and String problems, providing explanations and example Python code for each. Key topics include finding smallest/largest numbers, removing duplicates, checking for palindromes, and implementing sorting algorithms. Each problem includes a brief description and a sample code snippet to demonstrate the solution.

Uploaded by

nivashini.j123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Problems on Arrays

1. Find the smallest number in an array


2. Find the largest number in an array
3. Second Smallest and Second Largest element in an array
4. Reverse a given array
5. Count frequency of each element in an array
6. Rearrange array in increasing-decreasing order
7. Calculate sum of the elements of the array
8. Rotate array by K elements - Block Swap Algorithm
9. Average of all elements in an array
10. Find the median of the given array
11. Remove duplicates from a sorted array
12. Remove duplicates from unsorted array
13. Adding Element in an array
14. Find all repeating elements in an array
15. Find all non-repeating elements in an array
16. Find all symmetric pairs in array
17. Maximum product subarray in an array
18. Replace each element of the array by its rank in the array
19. Sorting elements of an array by frequency
20. Rotation of elements of array- left and right
21. Finding equilibrium index of an array
22. Finding Circular rotation of an array by K positions
23. Sort an array according to the order defined by another
array
24. Search an element in an array
25. Check if Array is a subset of another array or not
Problems on Numbers
1. Check if a number is palindrome or not
2. Find all Palindrome numbers in a given range
3. Check if a number is prime or not
4. Prime numbers in a given range
5. Check if a number is armstrong number of not
6. Check if a number is perfect number
7. Even or Odd
8. Check weather a given number is positive or negative
9. Sum of first N natural numbers
10. Find Sum of AP Series
11. Program to find sum of GP Series
12. Greatest of two numbers
13. Greatest of three numbers
14. Leap Year or not
15. Reverse digits of a number
16. Maximum and Minimum digit in a number
17. Print Fibonacci upto Nth Term
18. Factorial of a number
19. Power of a number
20. Factors of a given number
21. Print all prime factors of the given number
22. Check if a number is a strong number or not
23. Check if a Number is Automorphic
24. GCD of two numbers
25. LCM of two numbers
26. Check if a number is Harshad number
27. Check if the number is abundant number or not
28. Sum of digits of a number
29. Sum of numbers in the given range
30. Permutations in which N people can occupy R seats in a
classroom
31. Program to add two fractions
32. Replace all 0s with 1s in a given integer
33. Can a number be expressed as a sum of two prime numbers
34. Calculate the area of circle
35. Program to find roots of a Quadratic Equation
36. Problems on Number System
37. Convert Binary to Decimal
38. Convert binary to octal
39. Decimal to Binary conversion
40. Convert decimal to octal
41. Convert octal to binary
42. Convert octal to decimal
43. Convert digits/numbers to words
Problems on Sorting
1. Bubble Sort Algorithm
2. Selection Sort Algorithm
3. Insertion Sort Algorithm
4. Quick Sort Algorithm
5. Merge sort algorithm
Problems on String
1. Check if a given string is palindrome or not
2. Count number of vowels, consonants, spaces in String
3. Find the ASCII value of a character
4. Remove all vowels from the string
5. Remove spaces from a string
6. Remove characters from a string except alphabets
7. Reverse a String
8. Remove brackets from an algebraic expression
9. Sum of the numbers in a String
10. Capitalize first and last character of each word
11. Calculate frequency of characters in a string
12. Find Non-repeating characters of a String
13. Check if two strings are anagram of each other
14. Count common sub-sequence in two strings
15. Check if two strings match where one string contains
wildcard characters
16. Return maximum occurring character in the input string
17. Remove all duplicates from the input string.
18. Print all the duplicates in the input string.
19. Remove characters from first string present in the second
string
20. Change every letter with the next lexicographic alphabet in
the given string
21. Write a program to find the largest word in a given string.
22. Write a program to sort characters in a string
23. Count number of words in a given string
24. Write a program to find a word in a given string which has
the highest number of repeated letters
25. Change case of each character in a string
26. Concatenate one string to another
27. Write a program to find a substring within a string. If
found display its starting position
28. Reverse words in a string

I. Arrays Problems
1. Find the smallest number in an array
Explanation: Go through each number in the array and keep track of the smallest
one found so far.
python
Copy
def find_smallest(arr):
smallest = arr[0]
for num in arr:
if num < smallest:
smallest = num
return smallest

or
def find_smallest(arr):
return min(arr)

# Example
array = [3, 1, 4, 1, 5, 9, 2, 6]
print(find_smallest(array)) # Output: 1

2. Find the largest number in an array

Explanation: Similar to finding the smallest, but track the largest instead.
python
Copy
def find_largest(arr):
largest = arr[0]
for num in arr:
if num > largest:
largest = num
return largest

def find_largest(arr):
return max(arr)

# Example
array = [3, 1, 4, 1, 5, 9, 2, 6]
print(find_largest(array)) # Output: 9

3. Second Smallest and Second Largest


Explanation: Remove duplicates, sort the array, and pick the second element from
the start and end.
python
Copy
def second_smallest_largest(arr):
unique_sorted = sorted(list(set(arr)))
if len(unique_sorted) < 2:
return None, None
return unique_sorted[1], unique_sorted[-2]

def second_smallest_largest(arr):
unique_sorted = sorted(set(arr))
if len(unique_sorted) < 2:
return None, None
return unique_sorted[1], unique_sorted[-2]

# Example
array = [3, 1, 4, 1, 5, 9, 2, 6]
print(second_smallest_largest(array)) #

4. Reverse an array

Explanation: Use slicing to reverse the array.


python
Copy
def reverse_array(arr):
return arr[::-1]
# Example
arr = [1, 2, 3, 4, 5]
print(reverse_array(arr))

5. Count frequency of each element

Explanation: Use a dictionary to count how many times each number appears.
python
Copy
from collections import defaultdict

def count_frequency(arr):
freq = defaultdict(int)
for num in arr:
freq[num] += 1
return freq

from collections import Counter

def count_frequency(arr):
return dict(Counter(arr))

# Example
array = [1, 2, 2, 3, 3, 3, 4]
print(count_frequency(array)) # Output: {1: 1, 2: 2, 3: 3, 4: 1}

6. Rearrange array in increasing-decreasing order

Explanation: Sort the first half in increasing order and the second half in decreasing
order.
python
Copy

def rearrange_inc_dec(arr):
arr.sort()
mid = len(arr) // 2
return arr[:mid] + arr[mid:][::-1]

# Example
array = [1, 2, 3, 4, 5, 6]
print(rearrange_inc_dec(array)) # Output: [1, 2, 3, 6, 5, 4]

7. Sum of array elements

Explanation: Add all numbers in the array.


python
Copy
def sum_of_array(arr):
return sum(arr)

arr = [1, 2, 3, 4, 5]
print(sum_of_elements(array)) # Output: 15

8. Rotate array by K elements (Block Swap)

Explanation: Move the first K elements to the end.


python
Copy
def rotate_array(arr, k):
k = k % len(arr) # Handle cases where k > array length
return arr[k:] + arr[:k]

9. Average of array elements

Explanation: Sum all elements and divide by the count.


python
Copy
def average_of_array(arr):
return sum(arr) / len(arr)

10. Find the median of an array

Explanation: Sort the array and pick the middle element (or average of two middle
elements).
python
Copy
def find_median(arr):
arr_sorted = sorted(arr)
n = len(arr_sorted)
if n % 2 == 1:
return arr_sorted[n // 2]
else:
return (arr_sorted[n // 2 - 1] + arr_sorted[n // 2]) / 2

11. Remove duplicates from a sorted array

Explanation: Keep only unique elements (convert to a set and back to a list).
python
Copy
def remove_duplicates_sorted(arr):
return list(set(arr))

12. Remove duplicates from an unsorted array

Explanation: Use a dictionary to track seen elements.


python
Copy
def remove_duplicates_unsorted(arr):
seen = {}
result = []
for num in arr:
if num not in seen:
seen[num] = True
result.append(num)
return result

13. Adding an element to an array

Explanation: Use append() to add an element at the end.


python
Copy
def add_element(arr, element):
arr.append(element)
return arr

14. Find all repeating elements

Explanation: Find numbers that appear more than once.


python
Copy
def find_repeating_elements(arr):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
return [num for num, count in freq.items() if count > 1]
15. Find all non-repeating elements

Explanation: Find numbers that appear only once.


python
Copy
def find_non_repeating_elements(arr):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
return [num for num, count in freq.items() if count == 1]

16. Find symmetric pairs in an array

Explanation: Find pairs (a, b) where (b, a) also exists.


python
Copy
def find_symmetric_pairs(arr):
pairs = set()
result = []
for (a, b) in arr:
if (b, a) in pairs:
result.append((a, b))
pairs.add((a, b))
return result

17. Maximum product subarray

Explanation: Track the maximum and minimum product at each step.


python
Copy
def max_product_subarray(arr):
max_prod = min_prod = result = arr[0]
for num in arr[1:]:
candidates = (num, max_prod * num, min_prod * num)
max_prod = max(candidates)
min_prod = min(candidates)
result = max(result, max_prod)
return result
18. Replace elements with their rank

Explanation: Sort the array and assign ranks.


python
Copy
def replace_with_rank(arr):
sorted_arr = sorted(arr)
rank_dict = {val: i+1 for i, val in enumerate(sorted_arr)}
return [rank_dict[num] for num in arr]

19. Sort by frequency

Explanation: Sort based on how often each element appears.


python
Copy
def sort_by_frequency(arr):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
return sorted(arr, key=lambda x: (-freq[x], x))

20. Left and right rotation

Explanation: Rotate left by moving the first K elements to the end (right rotation is
similar).
python
Copy
def left_rotate(arr, k):
k = k % len(arr)
return arr[k:] + arr[:k]

def right_rotate(arr, k):


k = k % len(arr)
return arr[-k:] + arr[:-k]

21. Equilibrium index


Explanation: Find an index where the sum of left elements equals the sum of right
elements.
python
Copy
def equilibrium_index(arr):
total_sum = sum(arr)
left_sum = 0
for i, num in enumerate(arr):
if left_sum == (total_sum - left_sum - num):
return i
left_sum += num
return -1

22. Circular rotation by K positions

Explanation: Similar to rotation, but handles wrapping around.


python
Copy
def circular_rotate(arr, k):
k = k % len(arr)
return arr[-k:] + arr[:-k]

23. Sort array by another array order

Explanation: Sort based on the order defined in another array.


python
Copy
def sort_by_order(arr, order):
order_dict = {val: idx for idx, val in enumerate(order)}
return sorted(arr, key=lambda x: order_dict.get(x, float('inf')))

24. Search an element in an array

Explanation: Check if the element exists in the array.


python
Copy
def search_element(arr, target):
return target in arr
25. Check if one array is a subset of another

Explanation: Check if all elements of arr2 are in arr1.


python
Copy
def is_subset(arr1, arr2):
return all(elem in arr1 for elem in arr2)

II. Numbers Problems


1. Check if a number is a palindrome

Explanation: Reverse the number and check if it's the same as the original.
python
Copy
def is_palindrome(num):
return str(num) == str(num)[::-1]

print(is_palindrome(121))

2. Find all palindromes in a range

Explanation: Check each number in the range for palindrome property.


python
Copy
def palindromes_in_range(start, end):
return [num for num in range(start, end+1) if is_palindrome(num)]

print(palindrome_range(10, 50)) # Output: [11, 22, 33, 44]

s = "madam"
print("Palindrome" if s == s[::-1] else "Not Palindrome")

num = 121
if str(num) == str(num)[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
3. Check if a number is prime

Explanation: A prime number has no divisors other than 1 and itself.

A prime number is only divisible by 1 and itself.

python
Copy
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

4. Find primes in a range

Explanation: Check each number in the range for primality.


python
Copy
def primes_in_range(start, end):
return [num for num in range(start, end+1) if is_prime(num)]

5. Check if a number is Armstrong

Explanation: Sum of digits raised to power of digit count equals the number.
Armstrong number = sum of digits^number of digits.

python
Copy
def is_armstrong(num):
digits = list(str(num))
power = len(digits)
return num == sum(int(d)**power for d in digits)

print(is_armstrong(153)) # Output: True


6. Check if a number is perfect

Explanation: Sum of proper divisors equals the number.


python
Copy
def is_perfect(num):
if num <= 1:
return False
divisors = [1]
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
divisors.extend([i, num//i])
return sum(set(divisors)) == num

7. Even or Odd

Explanation: Check divisibility by 2.


python
Copy
def is_even(num):
return num % 2 == 0

def is_odd(num):
return num % 2 != 0

8. Positive or Negative

Explanation: Check if the number is greater than or less than zero.


python
Copy
def is_positive(num):
return num > 0

def is_negative(num):
return num < 0

9. Sum of first N natural numbers

Explanation: Formula n*(n+1)/2 gives the sum.


python
Copy
def sum_natural_numbers(n):
return n * (n + 1) // 2

10. Sum of AP Series

Explanation: (n/2) * (2a + (n-1)d) where a is first term, d is common difference.

Formula for AP sum: (n/2) × [2a + (n - 1)d]

python
Copy
def sum_ap(a, d, n):
return (n / 2) * (2 * a + (n - 1) * d)

print(sum(2, 3, 5)) # Output: 40.0

11. Sum of GP Series

Explanation: a * (r^n - 1) / (r - 1) where a is first term, r is common ratio.

GP sum formula:
If ratio r ≠ 1: S = a × (rⁿ - 1) / (r - 1)
If r = 1: S = a × n

python
Copy
def sum_gp(a, r, n):
return a * (r**n - 1) // (r - 1) if r != 1 else a * n

12. Greatest of two numbers

Explanation: Compare two numbers and return the larger one.


python
Copy
def greatest_of_two(a, b):
return max(a, b)
13. Greatest of three numbers

Explanation: Compare three numbers and return the largest.


python
Copy
def greatest_of_three(a, b, c):
return max(a, b, c)

14. Leap Year or Not

Explanation: A leap year is divisible by 4, but not by 100 unless also divisible by 400.
python
Copy
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

15. Reverse digits of a number

Explanation: Convert to string, reverse, and convert back to integer.


python
Copy
def reverse_digits(num):
return int(str(num)[::-1])

16. Maximum and Minimum digit in a number

Explanation: Extract digits and find min/max.


python
Copy
def max_min_digit(num):
digits = [int(d) for d in str(num)]
return max(digits), min(digits)
17. Print Fibonacci up to Nth term

Explanation: Each number is the sum of the two preceding ones.


python
Copy
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

fibonacci(7) # Output: 0 1 1 2 3 5 8

18. Factorial of a number

Explanation: Multiply all integers from 1 to the number.


python
Copy
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

or
def factorial(n):
result = 1
for i in range(2, n+1):
result *= i
return result

print(factorial(5)) # Output: 120

19. Power of a number

Explanation: Multiply the number by itself exp times.


python
Copy
def power(base, exp):
return base ** exp
20. Factors of a number

Explanation: Find all numbers that divide the given number evenly.
python
Copy
def factors(num):
return [i for i in range(1, num+1) if num % i == 0]

21. Prime factors of a number

Explanation: Decompose the number into prime factors.


python
Copy
def prime_factors(num):
factors = []
divisor = 2
while num > 1:
while num % divisor == 0:
factors.append(divisor)
num //= divisor
divisor += 1
return factors

22. Check if a number is a strong number

Explanation: Sum of factorials of digits equals the number.


python
Copy
def is_strong(num):
digits = [int(d) for d in str(num)]
return num == sum(factorial(d) for d in digits)

23. Check if a number is Automorphic

Explanation: The number appears at the end of its square.


python
Copy
def is_automorphic(num):
square = num ** 2
return str(square).endswith(str(num))

24. GCD of two numbers (Euclidean Algorithm)

Explanation: Largest number that divides both without a remainder.


python
Copy
def gcd(a, b):
while b:
a, b = b, a % b
return a

25. LCM of two numbers

Explanation: Smallest number that is a multiple of both.


python
Copy
def lcm(a, b):
return (a * b) // gcd(a, b)

26. Check if a number is Harshad

Explanation: Number divisible by the sum of its digits.


python
Copy
def is_harshad(num):
digit_sum = sum(int(d) for d in str(num))
return num % digit_sum == 0

27. Check if a number is abundant

Explanation: Sum of proper divisors exceeds the number.


python
Copy
def is_abundant(num):
divisors = [1]
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
divisors.extend([i, num//i])
return sum(set(divisors)) > num

28. Sum of digits of a number

Explanation: Add all digits together.


python
Copy
def sum_of_digits(num):
return sum(int(d) for d in str(num))

29. Sum of numbers in a range

Explanation: Sum all numbers from start to end.


python
Copy
def sum_in_range(start, end):
return sum(range(start, end + 1))

30. Permutations of N people occupying R seats

Explanation: Number of ways to arrange N people in R seats.


python
Copy
def permutations(n, r):
result = 1
for i in range(n, n - r, -1):
result *= i
return result

31. Add two fractions

Explanation: Find a common denominator and add numerators.


python
Copy
def add_fractions(num1, den1, num2, den2):
lcm_den = lcm(den1, den2)
new_num = num1 * (lcm_den // den1) + num2 * (lcm_den // den2)
common_divisor = gcd(new_num, lcm_den)
return (new_num // common_divisor, lcm_den // common_divisor)

32. Replace all 0s with 1s in a number

Explanation: Convert to string, replace '0's with '1's, and convert back.
python
Copy
def replace_zero_with_one(num):
return int(str(num).replace('0', '1'))

33. Can a number be expressed as sum of two primes?

Explanation: Check if num - prime is also prime for any prime less than num.
python
Copy
def is_sum_of_two_primes(num):
if num < 2:
return False
primes = primes_in_range(2, num)
for p in primes:
if is_prime(num - p):
return True
return False

34. Area of a circle

Explanation: π * r² where r is the radius.


python
Copy
import math
def area_of_circle(radius):
return math.pi * (radius ** 2)

35. Roots of a quadratic equation


Explanation: Solve ax² + bx + c = 0 using discriminant.
python
Copy
import math
def quadratic_roots(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant < 0:
return "No real roots"
elif discriminant == 0:
root = -b / (2*a)
return (root, root)
else:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
return (root1, root2)

36. Number System Conversions

Binary to Decimal
python
Copy
def binary_to_decimal(binary_str):
return int(binary_str, 2)

Binary to Octal
python
Copy
def binary_to_octal(binary_str):
decimal = binary_to_decimal(binary_str)
return oct(decimal)[2:]

Decimal to Binary
python
Copy
def decimal_to_binary(decimal_num):
return bin(decimal_num)[2:]

Decimal to Octal
python
Copy
def decimal_to_octal(decimal_num):
return oct(decimal_num)[2:]

Octal to Binary
python
Copy
def octal_to_binary(octal_str):
decimal = int(octal_str, 8)
return bin(decimal)[2:]

Octal to Decimal
python
Copy
def octal_to_decimal(octal_str):
return int(octal_str, 8)

Digits to Words
python
Copy
def digits_to_words(num):
digit_words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "S
even", "Eight", "Nine"]
return ' '.join([digit_words[int(d)] for d in str(num)])

Sorting Algorithms
1. Bubble Sort

Explanation: Repeatedly swap adjacent elements if they are in the wrong order.
python
Copy
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

2. Selection Sort
Explanation: Find the minimum element and swap it with the first unsorted element.
python
Copy
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr

3. Insertion Sort

Explanation: Build the sorted array one element at a time by inserting each new
element in the correct position.
python
Copy
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr

4. Quick Sort

Explanation: Divide and conquer approach using a pivot element.


python
Copy
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)

5. Merge Sort

Explanation: Divide the array into halves, sort each half, and merge them.
python
Copy
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)

def merge(left, right):


result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result

String Problems
1. Check if a string is a palindrome

Explanation: Compare the string with its reverse.


python
Copy
def is_string_palindrome(s):
s = ''.join(c.lower() for c in s if c.isalnum())
return s == s[::-1]
2. Count vowels, consonants, and spaces

Explanation: Iterate through the string and count each category.


python
Copy
def count_chars(s):
vowels = consonants = spaces = 0
for char in s.lower():
if char == ' ':
spaces += 1
elif char in 'aeiou':
vowels += 1
elif char.isalpha():
consonants += 1
return vowels, consonants, spaces

3. ASCII value of a character

Explanation: Use ord() to get ASCII value.


python
Copy
def ascii_value(char):
return ord(char)

4. Remove vowels from a string

Explanation: Exclude vowels from the string.


python
Copy
def remove_vowels(s):
vowels = 'aeiouAEIOU'
return ''.join([c for c in s if c not in vowels])

5. Remove spaces from a string

Explanation: Replace spaces with empty strings.


python
Copy
def remove_spaces(s):
return s.replace(' ', '')

6. Remove non-alphabetic characters

Explanation: Keep only letters.


python
Copy
def keep_alphabets(s):
return ''.join([c for c in s if c.isalpha()])

7. Reverse a string

Explanation: Use slicing to reverse.


python
Copy
def reverse_string(s):
return s[::-1]

8. Remove brackets from an expression

Explanation: Exclude brackets ()[]{}.


python
Copy
def remove_brackets(s):
brackets = '()[]{}'
return ''.join([c for c in s if c not in brackets])

9. Sum of numbers in a string

Explanation: Extract numbers and sum them.


python
Copy
import re
def sum_numbers_in_string(s):
numbers = re.findall(r'\d+', s)
return sum(int(num) for num in numbers)
10. Capitalize first and last character of each word

Explanation: Capitalize the first and last letter of every word.


python
Copy
def capitalize_first_last(s):
words = s.split()
result = []
for word in words:
if len(word) == 1:
result.append(word.upper())
else:
new_word = word[0].upper() + word[1:-1] + word[-1].upper()
result.append(new_word)
return ' '.join(result)

11. Frequency of characters in a string

Explanation: Count occurrences of each character.


python
Copy
from collections import defaultdict
def char_frequency(s):
freq = defaultdict(int)
for char in s:
freq[char] += 1
return freq

12. Non-repeating characters in a string

Explanation: Find characters that appear only once.


python
Copy
def non_repeating_chars(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
return [char for char, count in freq.items() if count == 1]
13. Check if two strings are anagrams

Explanation: Check if both strings have the same character counts.


python
Copy
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)

14. Count common subsequences in two strings

Explanation: Count matching subsequences (complex DP problem).


python
Copy
def count_common_subsequences(s1, s2):
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
dp[i][j] = 1 + dp[i-1][j-1] + dp[i-1][j] + dp[i][j-1] - dp[
i-1][j-1]
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1]
return dp[m][n]

15. Check if a string matches a wildcard pattern

Explanation: Use fnmatch for wildcard matching.


python
Copy
import fnmatch
def wildcard_match(s, pattern):
return fnmatch.fnmatch(s, pattern)

16. Maximum occurring character in a string

Explanation: Find the character with the highest frequency.


python
Copy
def max_occurring_char(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
return max(freq, key=freq.get)

17. Remove all duplicates from a string

Explanation: Keep only the first occurrence of each character.


python
Copy
def remove_duplicates(s):
seen = set()
result = []
for char in s:
if char not in seen:
seen.add(char)
result.append(char)
return ''.join(result)

18. Print all duplicates in a string

Explanation: Print characters that appear more than once.


python
Copy
def print_duplicates(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
for char, count in freq.items():
if count > 1:
print(char, count)

19. Remove characters from first string present in second string

Explanation: Exclude characters that appear in the second string.


python
Copy
def remove_chars(s1, s2):
return ''.join([c for c in s1 if c not in s2])

20. Change every letter to the next lexicographic letter

Explanation: Shift each letter to the next one in the alphabet.


python
Copy
def next_lexicographic(s):
return ''.join([chr(ord(c) + 1) if c != 'z' else 'a' for c in s])

21. Find the largest word in a string

Explanation: Split the string and find the longest word.


python
Copy
def largest_word(s):
words = s.split()
return max(words, key=len)

22. Sort characters in a string

Explanation: Sort the string alphabetically.


python
Copy
def sort_string(s):
return ''.join(sorted(s))

23. Count words in a string

Explanation: Split the string and count words.


python
Copy
def count_words(s):
return len(s.split())
24. Find the word with the highest repeated letters

Explanation: For each word, count max repeated letters and pick the highest.
python
Copy
def word_with_most_repeats(s):
words = s.split()
max_repeats = 0
result = ""
for word in words:
freq = {}
for char in word:
freq[char] = freq.get(char, 0) + 1
current_max = max(freq.values(), default=0)
if current_max > max_repeats:
max_repeats = current_max
result = word
return result

25. Change case of each character in a string

Explanation: Swap uppercase and lowercase letters.


python
Copy
def swap_case(s):
return s.swapcase()

26. Concatenate two strings

Explanation: Join two strings together.


python
Copy
def concatenate_strings(s1, s2):
return s1 + s2

27. Find a substring in a string

Explanation: Check if a substring exists and return its starting index.


python
Copy
def find_substring(s, sub):
return s.find(sub)

28. Reverse words in a string

Explanation: Split the string and reverse the word order.


python
Copy
def reverse_words(s):
return ' '.join(s.split()[::-1])

You might also like