Code
Code
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
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
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 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
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}
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]
arr = [1, 2, 3, 4, 5]
print(sum_of_elements(array)) # Output: 15
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
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))
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]
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))
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
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
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)
7. Even or Odd
def is_odd(num):
return num % 2 != 0
8. Positive or Negative
def is_negative(num):
return num < 0
python
Copy
def sum_ap(a, d, n):
return (n / 2) * (2 * a + (n - 1) * d)
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
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)
fibonacci(7) # Output: 0 1 1 2 3 5 8
or
def factorial(n):
result = 1
for i in range(2, n+1):
result *= i
return result
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]
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'))
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
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
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)
String Problems
1. Check if a string is a palindrome
7. Reverse a string
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