Coding Sheet Questions and Python Solutions
Coding Sheet Questions and Python Solutions
Solutions
95 coding questions extracted from the original coding sheet, each paired with a clean,
working Python solution.
1. Two Sum
Q. Given an array of integers nums and an integer target,
return indices of the two numbers such that they add up to
target.
You may assume that each input would have exactly one
solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Python Solution:
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
Example 1:
Input: nums = [5, 8, 1, 4, 7]
Output: 1
Explanation: Among all the elements, 1 is the minimum value.
Example 2:
Input: nums = [3,2,4]
Output: 2
Example 3:
Input: nums = [3,3]
Output: 3
Python Solution:
def find_smallest(nums):
min_val = nums[0]
for n in nums[1:]:
if n < min_val:
min_val = n
return min_val
print(find_smallest([5, 8, 1, 4, 7])) # 1
3. Find the Largest Element in an Array
Q. Given an array of integers, find and return the largest
element.
Example 1 :
Input: nums = [10, 20, 4, 45, 99]
Output: 99
Example 2 :
Input: nums = [5, 14, 7, 66, 9]
Output: 66
Example 3 :
Input: nums = [1, 7, 88, 19]
Output: 88
Python Solution:
def find_largest(nums):
max_val = nums[0]
for n in nums[1:]:
if n > max_val:
max_val = n
return max_val
Example 1 :
Input: [1, 7, 4, 7, 1, 5]
Output: Second Smallest: 2, Second Largest: 5
Example 2 :
Input: [1, 2, 4, 7, 7, 6]
Output: Second Smallest: 2, Second Largest: 6
Example 3 :
Input: [1, 8, 4, 7]
Output: Second Smallest: 4, Second Largest: 7
Python Solution:
def second_smallest_largest(nums):
large = second_large = float('-inf')
small = second_small = float('inf')
for n in nums:
if n > large:
second_large, large = large, n
elif large > n > second_large:
second_large = n
if n < small:
second_small, small = small, n
elif small < n < second_small:
second_small = n
return second_small, second_large
Example 1:
Input: nums = [5, 4, 3, 2, 1]
Output: [1, 2, 3, 4, 5]
Explanation: All elements are flipped to their opposite positions.
Example 2:
Input: nums = [10, 20]
Output: [20, 10]
Example 3:
Input: nums = [1, 1, 2]
Output: [2, 1, 1]
Python Solution:
def reverse_array(nums):
left, right = 0, len(nums) - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums
Example 1:
Input: nums = [10, 5, 10, 15, 10, 5]
Output: 10: 3, 5: 2, 15: 1
Explanation: Element 10 appears 3 times, 5 appears 2 times, and 15
appears once.
Example 2:
Input: nums = [2, 2, 3, 4, 4, 2]
Output: 2: 3, 3: 1, 4: 2
Example 3:
Input: nums = [1, 1, 1]
Output: 1: 3
Python Solution:
def count_frequency(nums):
freq = {}
for n in nums:
freq[n] = [Link](n, 0) + 1
return freq
Example 1:
Input: nums = [8, 7, 1, 6, 5, 9]
Output: [1, 5, 6, 9, 8, 7]
Explanation: Sorted array is [1,5,6,7,8,9]. First half [1,5,6] is
ascending, second half [7,8,9] is reversed.
Example 2:
Input: nums = [4, 2, 7]
Output: [2, 7, 4]
Example 3:
Input: nums = [1, 2, 3, 4]
Output: [1, 2, 4, 3]
Python Solution:
def rearrange_inc_dec(nums):
[Link]()
mid = len(nums) // 2
first_half = nums[:mid]
second_half = nums[mid:][::-1]
return first_half + second_half
Example 1:
Input: nums = [1, 2, 3, 4]
Output: 10
Explanation: 1 + 2 + 3 + 4 = 10
Example 2:
Input: nums = [5, 5, 5]
Output: 15
Example 3:
Input: nums = [-1, 1]
Output: 0
Python Solution:
def array_sum(nums):
total = 0
for n in nums:
total += n
return total
print(array_sum([1, 2, 3, 4])) # 10
9. Rotate Array Left by K (Block Swap Algorithm)
Q. Rotate the array elements to the left by k positions
using the Block Swap Algorithm.
Example 1:
Input: nums = [1, 2, 3, 4, 5], k = 2
Output: [3, 4, 5, 1, 2]
Explanation: The first 2 elements [1, 2] are moved to the end.
Example 2:
Input: nums = [10, 20, 30], k = 1
Output: [20, 30, 10]
Example 3:
Input: nums = [1, 2, 3, 4], k = 4
Output: [1, 2, 3, 4]
Python Solution:
def block_swap_reverse(nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
Example 1:
Input: nums = [1, 2, 3, 4, 5], k = 2
Output: [3, 4, 5, 1, 2]
Explanation: The first 2 elements [1, 2] are moved to the end.
Example 2:
Input: nums = [10, 20, 30], k = 1
Output: [20, 30, 10]
Example 3:
Input: nums = [1, 2, 3, 4], k = 4
Output: [1, 2, 3, 4]
Python Solution:
def block_swap_reverse(nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
Example 1:
Input: nums = [1, 2, 3, 4, 5]
Output: 3.0
Explanation: Sum is 15, total elements are 5. Average = 15 / 5 = 3.0.
Example 2:
Input: nums = [10, 20, 30]
Output: 20.0
Example 3:
Input: nums = [5, 5, 5, 5]
Output: 5.0
Python Solution:
def average(nums):
return sum(nums) / len(nums)
Example 1:
Input: nums = [1, 3, 4, 2, 6, 5, 8]
Output: 4
Explanation: Sorted array is [1, 2, 3, 4, 5, 6, 8]. The middle element
is 4.
Example 2:
Input: nums = [2, 4, 1, 3]
Output: 2.5
Explanation: Sorted: [1, 2, 3, 4]. Average of middle two: (2+3)/2 =
2.5.
Example 3:
Input: nums = [10, 100, 50]
Output: 50
Python Solution:
def median(nums):
s = sorted(nums)
n = len(s)
mid = n // 2
if n % 2 == 1:
return s[mid]
return (s[mid - 1] + s[mid]) / 2
print(median([1, 3, 4, 2, 6, 5, 8])) # 4
print(median([2, 4, 1, 3])) # 2.5
13. Remove Duplicates from a Sorted Array
Q. Given a sorted array, remove the duplicate elements in-
place so that each unique element appears only once.
Example 1:
Input: nums = [1, 1, 2, 2, 3]
Output: [1, 2, 3]
Explanation: The first 3 elements are now unique.
Example 2:
Input: nums = [0, 0, 1]
Output: [0, 1]
Example 3:
Input: nums = [1, 2, 3]
Output: [1, 2, 3]
Python Solution:
def remove_duplicates_sorted(nums):
if not nums:
return 0
i = 0
for j in range(1, len(nums)):
if nums[i] != nums[j]:
i += 1
nums[i] = nums[j]
return nums[:i + 1]
Example 1:
Input: nums = [4, 3, 9, 2, 4, 1, 10, 89, 34, 3, 2]
Output: [4, 3, 9, 2, 1, 10, 89, 34]
Explanation: All subsequent occurrences of 4, 3, and 2 are removed.
Example 2:
Input: nums = [1, 2, 1, 2]
Output: [1, 2]
Example 3:
Input: nums = [5, 4, 3]
Output: [5, 4, 3]
Python Solution:
def remove_duplicates_unsorted(nums):
seen = set()
result = []
for n in nums:
if n not in seen:
[Link](n)
[Link](n)
return result
Example 1:
Input: nums = [1, 2, 3, 1, 2, 4]
Output: [1, 2]
Explanation: Both 1 and 2 appear twice in the array.
Example 2:
Input: nums = [10, 20, 30]
Output: []
Example 3:
Input: nums = [5, 4, 5, 4, 5]
Output: [5, 4]
Python Solution:
def find_repeating(nums):
freq = {}
for n in nums:
freq[n] = [Link](n, 0) + 1
return [n for n, c in [Link]() if c > 1]
Example 1:
Input: nums = [1, 2, -1, 1, 3, 1]
Output: [2, -1, 3]
Explanation: 1 appears three times, while 2, -1, and 3 appear only
once.
Example 2:
Input: nums = [1, 1, 2, 2]
Output: []
Example 3:
Input: nums = [10, 20, 30]
Output: [10, 20, 30]
Python Solution:
def find_non_repeating(nums):
freq = {}
for n in nums:
freq[n] = [Link](n, 0) + 1
return [n for n in nums if freq[n] == 1]
Example 1:
Input: pairs = [[1, 2], [3, 4], [2, 1], [4, 3]]
Output: [[1, 2], [3, 4]]
Explanation: (1, 2) and (2, 1) are symmetric; (3, 4) and (4, 3) are
symmetric.
Example 2:
Input: pairs = [[1, 5], [2, 3], [5, 1]]
Output: [[1, 5]]
Example 3:
Input: pairs = [[1, 2], [2, 3]]
Output: []
Python Solution:
def find_symmetric_pairs(pairs):
seen = {}
result = []
for a, b in pairs:
if [Link](b) == a:
[Link]([a, b])
else:
seen[a] = b
return result
Example 1:
Input: nums = [2, 3, -2, 4]
Output: 6
Explanation: Subarray [2, 3] gives the maximum product 2 x 3 = 6.
Example 2:
Input: nums = [-2, 0, -1]
Output: 0
Example 3:
Input: nums = [1, 2, 3]
Output: 6
Python Solution:
def max_product_subarray(nums):
max_so_far = min_so_far = result = nums[0]
for n in nums[1:]:
if n < 0:
max_so_far, min_so_far = min_so_far, max_so_far
max_so_far = max(n, max_so_far * n)
min_so_far = min(n, min_so_far * n)
result = max(result, max_so_far)
return result
Example 1:
Input: nums = [40, 10, 30, 20]
Output: [4, 1, 3, 2]
Explanation: 10 is the smallest (Rank 1), 20 is next (Rank 2), then 30
(Rank 3), and 40 (Rank 4).
Example 2:
Input: nums = [10, 10, 10]
Output: [1, 1, 1]
Example 3:
Input: nums = [5, 8, 2]
Output: [2, 3, 1]
Python Solution:
def replace_with_rank(nums):
sorted_unique = sorted(set(nums))
rank = {val: i + 1 for i, val in enumerate(sorted_unique)}
return [rank[n] for n in nums]
Example 1:
Input: nums = [1, 2, 2, 3, 3, 3]
Output: [3, 3, 3, 2, 2, 1]
Explanation: 3 appears most (3 times), followed by 2, then 1.
Example 2:
Input: nums = [4, 4, 5, 5]
Output: [4, 4, 5, 5]
Example 3:
Input: nums = [10, 5, 10]
Output: [10, 10, 5]
Python Solution:
def sort_by_frequency(nums):
freq = {}
for n in nums:
freq[n] = [Link](n, 0) + 1
return sorted(nums, key=lambda x: (-freq[x], x))
Example 1 (Right):
Input: nums = [1, 2, 3, 4, 5], k = 2
Output: [4, 5, 1, 2, 3]
Example 2 (Left):
Input: nums = [1, 2, 3, 4, 5], k = 2
Output: [3, 4, 5, 1, 2]
Example 3:
Input: nums = [10, 20], k = 1
Output (Right): [20, 10]
Python Solution:
def rotate_right(nums, k):
n = len(nums)
k %= n
return nums[-k:] + nums[:-k] if k else nums[:]
Example 1:
Input: nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: At index 3 (value 6), Left sum: 1+7+3 = 11, Right sum:
5+6 = 11.
Example 2:
Input: nums = [1, 2, 3]
Output: -1
Example 3:
Input: nums = [2, 1, -1]
Output: 0
Python Solution:
def equilibrium_index(nums):
total = sum(nums)
left_sum = 0
for i, n in enumerate(nums):
right_sum = total - left_sum - n
if left_sum == right_sum:
return i
left_sum += n
return -1
print(equilibrium_index([1, 7, 3, 6, 5, 6])) # 3
23. Check if Array is a Subset of Another Array
Q. Given two arrays, check if the first array is a subset of
the second array.
Example 1:
Input: arr1 = [1, 3, 4], arr2 = [1, 2, 3, 4, 5]
Output: True
Example 2:
Input: arr1 = [6, 7], arr2 = [1, 2, 3, 4]
Output: False
Example 3:
Input: arr1 = [1], arr2 = [1]
Output: True
Python Solution:
def is_subset(arr1, arr2):
set2 = set(arr2)
return all(x in set2 for x in arr1)
Example 1:
Input: nums = [1, 3, 5, 7, 9], target = 5
Output: 2
Explanation: 5 is located at index 2.
Example 2:
Input: nums = [10, 20], target = 30
Output: -1
Example 3:
Input: nums = [5], target = 5
Output: 0
Python Solution:
def binary_search(nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Example 3:
Input: matrix = [[1]], target = 1
Output: true
Python Solution:
def search_matrix(matrix, target):
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
low, high = 0, m * n - 1
while low <= high:
mid = (low + high) // 2
row, col = divmod(mid, n)
val = matrix[row][col]
if val == target:
return True
elif val < target:
low = mid + 1
else:
high = mid - 1
return False
Example 1:
Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2],
start = 0, end = 2
Output: 0.25000
Explanation: Path $0 \to 1 \to 2$ has probability $0.5 \times 0.5 =
0.25.
Example 2:
Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
Output: 0.00000
Python Solution:
import heapq
prob = [0.0] * n
prob[start] = 1.0
heap = [(-1.0, start)]
while heap:
neg_p, node = [Link](heap)
p = -neg_p
if node == end:
return p
if p < prob[node]:
continue
for nei, edge_p in graph[node]:
new_p = p * edge_p
if new_p > prob[nei]:
prob[nei] = new_p
[Link](heap, (-new_p, nei))
return 0.0
Example 1:
Input: Students (id, name), Subjects (name), Examinations
(student_id, subject_name)
Output: A table showing every student-subject pair with their
respective attendance count.
Python Solution:
# SQL solution (not a Python-executable problem)
"""
SELECT s.student_id, s.student_name, sub.subject_name,
COUNT(e.subject_name) AS attended_exams
FROM Students s
CROSS JOIN Subjects sub
LEFT JOIN Examinations e
ON s.student_id = e.student_id
AND sub.subject_name = e.subject_name
GROUP BY s.student_id, s.student_name, sub.subject_name
ORDER BY s.student_id, sub.subject_name;
"""
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Python Solution:
def next_permutation(nums):
n = len(nums)
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i >= 0:
j = n - 1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1:] = reversed(nums[i + 1:])
return nums
Example 1:
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: numRows = 1
Output: [[1]]
Example 3:
Input: numRows = 3
Output: [[1],[1,1],[1,2,1]]
Python Solution:
def generate_pascals_triangle(numRows):
triangle = []
for i in range(numRows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
[Link](row)
return triangle
print(generate_pascals_triangle(5))
# [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
30. Trapping Rain Water
Q. Givan an non-negative integers representing an elevation
map where the width of each bar is 1, compute how much
water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Example 3:
Input: height = [2,0,2]
Output: 2
Python Solution:
def trap_rain_water(height):
if not height:
return 0
left, right = 0, len(height) - 1
left_max, right_max = height[left], height[right]
total = 0
while left < right:
if height[left] < height[right]:
left += 1
left_max = max(left_max, height[left])
total += left_max - height[left]
else:
right -= 1
right_max = max(right_max, height[right])
total += right_max - height[right]
return total
print(trap_rain_water([0,1,0,2,1,0,1,3,2,1,2,1])) # 6
31. Same Tree
Q. Given the roots of two binary trees p and q, write a
function to check if they are the same or not. Two binary
trees are considered the same if they are structurally
identical and the nodes have the same value.
Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false
Python Solution:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
[Link] = val
[Link] = left
[Link] = right
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Python Solution:
class ListNode:
def __init__(self, val=0, next=None):
[Link] = val
[Link] = next
def reverse_linked_list(head):
prev = None
curr = head
while curr:
nxt = [Link]
[Link] = prev
prev = curr
curr = nxt
return prev
33. Set Matrix Zeroes
Q. Given an mxn integer matrix, if an element is 0, set its
entire row and column to 0's. Do it in-place.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Example 3:
Input: matrix = [[1,0]]
Output: [[0,0]]
Python Solution:
def set_matrix_zeroes(matrix):
m, n = len(matrix), len(matrix[0])
first_row_has_zero = any(matrix[0][j] == 0 for j in range(n))
first_col_has_zero = any(matrix[i][0] == 0 for i in range(m))
if first_row_has_zero:
for j in range(n):
matrix[0][j] = 0
if first_col_has_zero:
for i in range(m):
matrix[i][0] = 0
return matrix
34. Spiral Matrix
Q. Givan an mxn matrix, return all elements of the matrix in
spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Example 3:
Input: matrix = [[1]]
Output: [1]
Python Solution:
def spiral_order(matrix):
result = []
if not matrix:
return result
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for j in range(left, right + 1):
[Link](matrix[top][j])
top += 1
for i in range(top, bottom + 1):
[Link](matrix[i][right])
right -= 1
if top <= bottom:
for j in range(right, left - 1, -1):
[Link](matrix[bottom][j])
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
[Link](matrix[i][left])
left += 1
return result
print(spiral_order([[1,2,3],[4,5,6],[7,8,9]])) # [1,2,3,6,9,8,7,4,5]
35. Palindrome Partitioning IV (Split into 3 Palindromes)
Q. Given a string s, return true if it is possible to split the
string s into three non-empty palindromic substrings.
Otherwise, return false.
Example 1:
Input: s = "abcbdd"
Output: true
Explanation: "a", "bcb", "dd" are all palindromes.
Example 2:
Input: s = "bcbddxy"
Output: false
Python Solution:
def can_split_3_palindromes(s):
n = len(s)
is_pal = [[False] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
if s[i] == s[j] and (j - i < 2 or is_pal[i + 1][j - 1]):
is_pal[i][j] = True
print(can_split_3_palindromes("abcbdd")) # True
print(can_split_3_palindromes("bcbddxy")) # False
36. Employee Bonus (SQL)
Q. Write an SQL query to report the name and bonus
amount of each employee with a bonus less than 1000.
Example 1:
Input: Employee table (empId, name), Bonus table (empId, bonus)
Output: Employees with bonuses < 1000 or no bonus at all.
Python Solution:
# SQL solution (not a Python-executable problem)
"""
SELECT [Link], [Link]
FROM Employee e
LEFT JOIN Bonus b ON [Link] = [Link]
WHERE [Link] < 1000 OR [Link] IS NULL;
"""
Example 1:
Input: L = 10, R = 20
Output: 11, 13, 17, 19
Explanation: Between 10 and 20, these numbers are only divisible by
1 and themselves.
Example 2:
Input: L = 1, R = 10
Output: 2, 3, 5, 7
Example 3:
Input: L = 30, R = 35
Output: 31
Python Solution:
def primes_in_range(L, R):
def is_prime(x):
if x < 2:
return False
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0:
return False
return True
Example 1:
Input: N = 2519
Output: Max: 9, Min: 1
Example 2:
Input: N = 108
Output: Max: 8, Min: 0
Example 3:
Input: N = 444
Output: Max: 4, Min: 4
Python Solution:
def max_min_digit(n):
n = abs(n)
max_digit, min_digit = 0, 9
if n == 0:
return 0, 0
while n > 0:
digit = n % 10
max_digit = max(max_digit, digit)
min_digit = min(min_digit, digit)
n //= 10
return max_digit, min_digit
print(max_min_digit(2519)) # (9, 1)
39. Print All Prime Factors of a Number
Q. Given a number N, find and print all its prime factors.
Prime factors are the prime numbers that multiply together
to give the original number.
Example 1:
Input: N = 60
Output: 2, 2, 3, 5
Example 2:
Input: N = 13
Output: 13
Example 3:
Input: N = 90
Output: 2, 3, 3, 5
Python Solution:
def prime_factors(n):
factors = []
while n % 2 == 0:
[Link](2)
n //= 2
i = 3
while i * i <= n:
while n % i == 0:
[Link](i)
n //= i
i += 2
if n > 2:
[Link](n)
return factors
print(prime_factors(60)) # [2, 2, 3, 5]
40. Check if a Number is a Strong Number
Q. Determine if a given number is a Strong Number. A
number is "Strong" if the sum of the factorials of its digits
is equal to the number itself.
Example 1:
Input: 145
Output: Yes
Explanation: 1! + 4! + 5! = 1 + 24 + 120 = 145.
Example 2:
Input: 123
Output: No
Example 3:
Input: 2
Output: Yes (2! = 2)
Python Solution:
from math import factorial
def is_strong_number(n):
total = sum(factorial(int(d)) for d in str(n))
return total == n
print(is_strong_number(145)) # True
41. Check if a Number is Automorphic
Q. Check if a number is Automorphic. An Automorphic
number is a number whose square ends with the same digits
as the number itself.
Example 1:
Input: 25
Output: Yes
Explanation: 25^2 = 625. Since 625 ends with 25, it is Automorphic.
Example 2:
Input: 7
Output: No (7^2 = 49, does not end in 7)
Example 3:
Input: 6
Output: Yes (6^2 = 36)
Python Solution:
def is_automorphic(n):
square = n * n
return str(square).endswith(str(n))
Example 1:
Input: A = 12, B = 18
Output: 6
Example 2:
Input: A = 7, B = 5
Output: 1
Example 3:
Input: A = 20, B = 100
Output: 20
Python Solution:
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(12, 18)) # 6
43. LCM of Two Numbers
Q. Calculate the Least Common Multiple (LCM) of two
integers A and B.
Example 1:
Input: A = 4, B = 6
Output: 12
Example 2:
Input: A = 15, B = 20
Output: 60
Example 3:
Input: A = 3, B = 7
Output: 21
Python Solution:
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(lcm(4, 6)) # 12
44. Check if a Number is a Harshad Number
Q. Determine if a given number is a Harshad Number. A
Harshad number is an integer that is divisible by the sum of
its digits.
Example 1:
Input: 18
Output: Yes
Explanation: Sum of digits is 1+8=9. Since 18 is divisible by 9, it is
Harshad.
Example 2:
Input: 15
Output: No (Sum = 6, 15 is not divisible by 6)
Example 3:
Input: 21
Output: Yes
Python Solution:
def is_harshad(n):
digit_sum = sum(int(d) for d in str(n))
return n % digit_sum == 0
print(is_harshad(18)) # True
45. Check if a Number is an Abundant Number
Q. Check if a number is an Abundant Number. A number is
abundant if the sum of its proper divisors (excluding the
number itself) is greater than the number.
Example 1:
Input: 12
Output: Yes
Explanation: Divisors of 12 are 1, 2, 3, 4, 6. Sum is 16. Since 16 > 12,
it is Abundant.
Example 2:
Input: 18
Output: Yes (Sum of divisors = 21)
Example 3:
Input: 7
Output: No (Sum of divisors = 1)
Python Solution:
def is_abundant(n):
total = 0
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
if i != n:
total += i
j = n // i
if j != i and j != n:
total += j
return total > n
print(is_abundant(12)) # True
46. Permutations: N People in R Seats
Q. Find the total number of ways N people can be arranged
in R available seats. This is calculated using the permutation
formula.
Example 1:
Input: N = 5, R = 3
Output: 60
Example 2:
Input: N = 10, R = 2
Output: 90
Example 3:
Input: N = 6, R = 6
Output: 720
Python Solution:
def permutations_nr(n, r):
result = 1
for i in range(n, n - r, -1):
result *= i
return result
print(permutations_nr(5, 3)) # 60
47. Replace All 0s with 1s in a Number
Q. Given an integer, replace every occurrence of the digit
'0' with the digit '1' and print the modified number.
Example 1:
Input: 10205
Output: 11215
Example 2:
Input: 100
Output: 111
Example 3:
Input: 789
Output: 789
Python Solution:
def replace_zero_with_one(n):
return int(str(n).replace('0', '1'))
print(replace_zero_with_one(10205)) # 11215
48. Roots of a Quadratic Equation
Q. Given coefficients a, b, and c of a quadratic equation
ax^2 + bx + c = 0, find all possible roots.
Example 1:
Input: a=1, b=-5, c=6
Output: Roots: 3, 2
Example 2:
Input: a=1, b=-2, c=1
Output: Roots: 1, 1
Example 3:
Input: a=1, b=1, c=1
Output: Complex Roots
Python Solution:
import cmath
Example 1:
Input: 1011
Output: 11
Explanation: (1 x 2^3) + (0 x 2^2) + (1 \times 2^1) + (1 x 2^0) = 8 + 0
+ 2 + 1 = 11.
Example 2:
Input: 100
Output: 4
Example 3:
Input: 1111
Output: 15
Python Solution:
def binary_to_decimal(binary_str):
return int(binary_str, 2)
print(binary_to_decimal("1011")) # 11
50. Convert Binary to Octal
Q. Convert a given binary number (base-2) into its
equivalent octal (base-8) representation.
Example 1:
Input: 110011
Output: 63
Explanation: Group digits into threes from right to left: (110)(011).
110 = 6 and 011 = 3.
Example 2:
Input: 1010
Output: 12
Example 3:
Input: 11111
Output: 37
Python Solution:
def binary_to_octal(binary_str):
decimal = int(binary_str, 2)
return oct(decimal)[2:]
print(binary_to_octal("110011")) # '63'
51. Convert Decimal to Binary
Q. Given a decimal number (base-10), convert it into its
equivalent binary (base-2) string.
Example 1:
Input: 10
Output: 1010
Example 2:
Input: 7
Output: 111
Example 3:
Input: 1
Output: 1
Python Solution:
def decimal_to_binary(n):
return bin(n)[2:]
print(decimal_to_binary(10)) # '1010'
52. Convert Decimal to Octal
Q. Given a decimal number (base-10), convert it into its
equivalent octal (base-8) form.
Example 1:
Input: 64
Output: 100
Example 2:
Input: 15
Output: 17
Example 3:
Input: 2
Output: 2
Python Solution:
def decimal_to_octal(n):
return oct(n)[2:]
print(decimal_to_octal(64)) # '100'
53. Convert Octal to Binary
Q. Convert a given octal number (base-8) into its equivalent
binary (base-2) form.
Example 1:
Input: 37
Output: 11111
Explanation: 3 = 011 and 7 = 111. Combining them gives 011111, leading
zeros can be removed.
Example 2:
Input: 5
Output: 101
Example 3:
Input: 12
Output: 1010
Python Solution:
def octal_to_binary(octal_str):
decimal = int(octal_str, 8)
return bin(decimal)[2:]
print(octal_to_binary("37")) # '11111'
54. Convert Octal to Decimal
Q. Given an octal number (base-8), find its decimal (base-
10) equivalent.
Example 1:
Input: 63
Output: 51
Explanation: (6 x 8^1) + (3 x 8^0) = 48 + 3 = 51.
Example 2:
Input: 100
Output: 64
Example 3:
Input: 7
Output: 7
Python Solution:
def octal_to_decimal(octal_str):
return int(octal_str, 8)
print(octal_to_decimal("63")) # 51
55. Convert a Number to English Words
Q. Convert a non-negative integer into its English word
representation.
Example 1:
Input: 123
Output: "One Hundred Twenty Three"
Example 2:
Input: 10
Output: "Ten"
Example 3:
Input: 5000
Output: "Five Thousand"
Python Solution:
below_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety"]
def three_digit_words(n):
if n == 0:
return ""
if n < 20:
return below_20[n] + " "
if n < 100:
return tens[n // 10] + " " + three_digit_words(n % 10)
return below_20[n // 100] + " Hundred " + three_digit_words(n % 100)
def number_to_words(n):
if n == 0:
return "Zero"
groups = ["", "Thousand", "Million", "Billion"]
words = ""
i = 0
while n > 0:
if n % 1000 != 0:
words = three_digit_words(n % 1000) + groups[i] + " " + words
n //= 1000
i += 1
return [Link]()
Example 1:
Input: "Hello World"
Output: Vowels: 3, Consonants: 7, Spaces: 1
Example 2:
Input: "Java 101"
Output: Vowels: 2, Consonants: 2, Spaces: 1
Example 3:
Input: "aeiou"
Output: Vowels: 5, Consonants: 0, Spaces: 0
Python Solution:
def count_vowels_consonants_spaces(s):
vowels = consonants = spaces = 0
for ch in s:
lower = [Link]()
if lower in "aeiou":
vowels += 1
elif lower == ' ':
spaces += 1
elif [Link]():
consonants += 1
return vowels, consonants, spaces
Example 1:
Input: "Placito"
Output: "Plct"
Example 2:
Input: "Apple"
Output: "ppl"
Example 3:
Input: "XYZ"
Output: "XYZ"
Python Solution:
def remove_vowels(s):
return ''.join(ch for ch in s if [Link]() not in "aeiou")
print(remove_vowels("Placito")) # "Plct"
58. Remove Spaces from a String
Q. Given a string, remove all the white spaces present in it.
Example 1:
Input: "A B C"
Output: "ABC"
Example 2:
Input: " Hello World "
Output: "HelloWorld"
Python Solution:
def remove_spaces(s):
return [Link](" ", "")
Example 1:
Input: "Java@123!"
Output: "Java"
Python Solution:
def keep_only_alphabets(s):
return ''.join(ch for ch in s if [Link]())
print(keep_only_alphabets("Java@123!")) # "Java"
60. Remove Brackets from an Algebraic Expression
Q. Given an algebraic expression as a string, remove all
parentheses (brackets) from it and return the resulting
string.
Example 1:
Input: "(a+b)=c"
Output: "a+b=c"
Example 2:
Input: "((a-b)+c)"
Output: "a-b+c"
Example 3:
Input: "a+b"
Output: "a+b"
Python Solution:
def remove_brackets(s):
return ''.join(ch for ch in s if ch not in "()")
print(remove_brackets("(a+b)=c")) # "a+b=c"
61. Sum of All Digits in a String
Q. Given a string containing alphanumeric characters, find
the sum of all numerical digits present in the string.
Example 1:
Input: "1abc23"
Output: 6 (1+2+3)
Example 2:
Input: "Hello"
Output: 0
Example 3:
Input: "55"
Output: 10
Python Solution:
def sum_of_digits_in_string(s):
return sum(int(ch) for ch in s if [Link]())
print(sum_of_digits_in_string("1abc23")) # 6
62. Capitalize First and Last Character of Each Word
Q. Given a string, capitalize the first and last character of
every word in it.
Example 1:
Input: "hello world"
Output: "HellO WorlD"
Example 2:
Input: "java"
Output: "JavA"
Example 3:
Input: "a b c"
Output: "A B C"
Python Solution:
def capitalize_first_last(s):
words = [Link]()
result = []
for word in words:
if len(word) == 1:
[Link]([Link]())
else:
[Link](word[0].upper() + word[1:-1] + word[-1].upper())
return ' '.join(result)
Example 1:
Input: "apple"
Output: a:1, p:2, l:1, e:1
Example 2:
Input: "aba"
Output: a:2, b:1
Example 3:
Input: "zzz"
Output: z:3
Python Solution:
def char_frequency(s):
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
return freq
Example 1:
Input: "swiss"
Output: "w i"
Example 2:
Input: "aabbc"
Output: "c"
Example 3:
Input: "abc"
Output: "a b c"
Python Solution:
def non_repeating_chars(s):
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
return [ch for ch in s if freq[ch] == 1]
Example 1:
Input: "listen", "silent"
Output: True
Example 2:
Input: "hello", "world"
Output: False
Example 3:
Input: "anagram", "nagaram"
Output: True
Python Solution:
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
Example 1:
Input: "abc", "abc"
Output: 7
Example 2:
Input: "a", "b"
Output: 0
Example 3:
Input: "ajblqcpdx", "aefgabcpy"
Output: 11
Python Solution:
def count_common_subsequences(s1, s2):
n, m = len(s1), len(s2)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = 1
for j in range(m + 1):
dp[0][j] = 1
for i in range(1, n + 1):
for j in range(1, m + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
else:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]
return dp[n][m] - 1 # subtract the empty subsequence
print(count_common_subsequences("abc", "abc")) # 7
67. Remove Characters of String A Present in String B
Q. Remove all occurrences of characters in the first string
that appear in the second string.
Example 1:
Input: "apple", "peer"
Output: "al"
Example 2:
Input: "hello", "ol"
Output: "he"
Example 3:
Input: "abc", "def"
Output: "abc"
Python Solution:
def remove_chars_present_in(s1, s2):
to_remove = set(s2)
return ''.join(ch for ch in s1 if ch not in to_remove)
Example 1:
Input: "abc"
Output: "bcd"
Example 2:
Input: "xyz"
Output: "yza"
Example 3:
Input: "Java"
Output: "Kbwb"
Python Solution:
def shift_to_next_letter(s):
result = []
for ch in s:
if ch == 'z':
[Link]('a')
elif ch == 'Z':
[Link]('A')
elif [Link]():
[Link](chr(ord(ch) + 1))
else:
[Link](ch)
return ''.join(result)
print(shift_to_next_letter("abc")) # "bcd"
print(shift_to_next_letter("xyz")) # "yza"
69. Find the Largest Word in a String
Q. Given a sentence or a string of words, identify and
return the word that has the maximum number of
characters. If multiple words have the same maximum
length, return the first one encountered.
Example 1:
Input: "Google Chrome is a web browser"
Output: "browser"
Explanation: The lengths are: Google(6), Chrome(6), is(2), a(1),
web(3), browser(7). "browser" is the longest.
Example 2:
Input: "Microsoft Azure"
Output: "Microsoft"
Example 3:
Input: "I am learning Python"
Output: "learning"
Python Solution:
def largest_word(sentence):
words = [Link]()
max_word = ""
for word in words:
if len(word) > len(max_word):
max_word = word
return max_word
Example 1:
Input: "abcdef gghhkkk apple"
Output: "gghhkkk"
Explanation: "gghhkkk" has 'k' repeated 3 times, which is the
highest in this string.
Example 2:
Input: "hello world"
Output: "hello" ( 'l' is repeated twice)
Example 3:
Input: "no repeats here"
Output: "repeats" ( 'e' is repeated twice)
Python Solution:
def word_with_highest_repeated_char(sentence):
words = [Link]()
best_word = words[0] if words else ""
best_freq = 0
for word in words:
freq = {}
for ch in word:
freq[ch] = [Link](ch, 0) + 1
local_max = max([Link]())
if local_max > best_freq:
best_freq = local_max
best_word = word
return best_word
Example 1:
Input: "PlaCito"
Output: "pLAcITO"
Example 2:
Input: "JAVA is FUN"
Output: "java IS fun"
Example 3:
Input: "123 abc"
Output: "123 ABC"
Python Solution:
def swap_case(s):
return [Link]()
print(swap_case("PlaCito")) # "pLAcITO"
72. Find a Substring within a String (Index Search)
Q. Search for a specific substring within a main string. If
the substring exists, return the index of its first
occurrence; otherwise, return -1.
Example 1:
Input: String: "takeuforward", Substring: "forward"
Output: 5
Explanation: The substring "forward" starts at index 5 of
"takeuforward".
Example 2:
Input: String: "hello", Substring: "world"
Output: -1
Example 3:
Input: String: "programming", Substring: "gram"
Output: 3
Python Solution:
def find_substring(s, sub):
return [Link](sub)
print(find_substring("takeuforward", "forward")) # 5
73. Caesar Cipher (Letters and Digits)
Q. Implement a custom Caesar Cipher that shifts both
alphabetic characters (A-Z, a-z) and numeric digits (0-9) by
a given key. Alphabets wrap around within 26 characters,
and digits wrap around within 10. Symbols like "-" remain
unchanged.
Example 1:
Input: Text: "All the best", Key: 1
Output: "Bmm uif gftu"
Example 2:
Input: Text: "5-abc", Key: 2
Output: "7-cde"
Example 3:
Input: Text: "Hello", Key: -1
Output: "INVALID INPUT"
Python Solution:
def caesar_cipher(text, key):
if key < 0:
return "INVALID INPUT"
result = []
for ch in text:
if [Link]():
base = ord('A') if [Link]() else ord('a')
[Link](chr((ord(ch) - base + key) % 26 + base))
elif [Link]():
[Link](chr((ord(ch) - ord('0') + key) % 10 + ord('0')))
else:
[Link](ch)
return ''.join(result)
Example 1:
Input: n=20, k=2, j=3, m=12, p=12
Output: 10
Explanation: 6 monkeys eat 12 bananas (12/2), 4 eat 12 peanuts
(12/3). 20 - (6+4) = 10.
Example 2:
Input: n=10, k=2, j=2, m=1, p=1
Output: 8 (The last 2 monkeys eat the remaining fractions).
Example 3:
Input: m=0, p=0
Output: 20 (No monkeys leave).
Python Solution:
def monkeys_remaining(n, k, j, m, p):
import math
banana_eaters = [Link](m / k) if k else 0
peanut_eaters = [Link](p / j) if j else 0
remaining = n - (banana_eaters + peanut_eaters)
return max(remaining, 0)
Example 1:
Input: s = "aabc"
Output: "1c1b2a"
Explanation: Step 1: a2b1c1. Step 2 (Reverse): 1c1b2a.
Example 2:
Input: s = "aaaaa"
Output: "5a"
Example 3:
Input: s = "abc"
Output: "1c1b1a"
Python Solution:
def encrypt_string(s):
if not s:
return ""
compressed = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
[Link](s[i - 1] + str(count))
count = 1
[Link](s[-1] + str(count))
encoded = ''.join(compressed)
return encoded[::-1]
print(encrypt_string("aabc")) # "1c1b2a"
print(encrypt_string("aaaaa")) # "5a"
76. Minimum '*' or '#' to Balance a String
Q. Given a string S (input consisting) of ‘*’ and ‘#’. The
length of the string is variable. The task is to find the
minimum number of ‘*’ or ‘#’ to make it a valid string. The
string is considered valid if the number of ‘*’ and ‘#’ are
equal. The ‘*’ and ‘#’ can be at any position in the string.
Note: The output will be a positive or negative integer based on number
of ‘*’ and ‘#’ in the input string.
(*>#): positive integer
(#>*): negative integer
(#=*): 0
Example 1:
Input: ###***
Output: 0
Example 2:
Input: ***#
Output: 2
Example 3:
Input: ##*
Output: -1
Python Solution:
def balance_star_hash(s):
counter = 0
for ch in s:
if ch == '*':
counter += 1
elif ch == '#':
counter -= 1
return counter
print(balance_star_hash("###***")) # 0
print(balance_star_hash("***#")) # 2
print(balance_star_hash("##*")) # -1
77. Count and Say Sequence
Q. The count-and-say sequence is a sequence of digit
strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n) is the run-length encoding of
countAndSay(n - 1).
Run-length encoding (RLE) is a string compression method
that works by replacing consecutive identical characters
(repeated 2 or more times) with the concatenation of the
character and the number marking the count of the
characters (length of the run). For example, to compress
the string "3322251" we replace "33" with "23", replace
"222" with "32", replace "5" with "15" and replace "1" with
"11". Thus the compressed string becomes "23321511".
Given a positive integer n, return the nth element of the
count-and-say sequence.
Example 1:
Input: ###***
Output: 0
Example 2:
Input: ***#
Output: 2
Example 3:
Input: ##*
Output: -1
Python Solution:
def count_and_say(n):
result = "1"
for _ in range(n - 1):
next_result = []
i = 0
while i < len(result):
count = 1
while i + 1 < len(result) and result[i] == result[i + 1]:
i += 1
count += 1
next_result.append(str(count) + result[i])
i += 1
result = ''.join(next_result)
return result
print(count_and_say(4)) # "1211"
78. Sort Characters by Corresponding Numeric Values
Q. You are given two arrays: a[] (integers) and b[]
(characters). The i-th value of a[] corresponds to the i-th
value of b[]. Sort the array b[] based on the numerical
values in a[]. After every character, print a whitespace.
Example 1:
Input: a[] = {3, 1, 2}, b[] = {'G', 'E', 'K'}
Output: E K G
Explanation: 1 corresponds to 'E', 2 to 'K', and 3 to 'G'. Sorting by
numbers gives E, K, G.
Example 2:
Input: a[] = {10, 5}, b[] = {'Z', 'A'}
Output: A Z
Example 3:
Input: a[] = {1, 2, 3}, b[] = {'X', 'Y', 'Z'}
Output: X Y Z
Python Solution:
def sort_chars_by_values(a, b):
pairs = sorted(zip(a, b), key=lambda x: x[0])
return ' '.join(ch for _, ch in pairs) + ' '
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price=1) and sell on day 5 (price=6),
profit = 6-1 = 5.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0 (No profit possible).
Example 3:
Input: prices = [1, 10]
Output: 9
Python Solution:
def max_profit(prices):
if not prices:
return 0
min_price = prices[0]
best_profit = 0
for price in prices[1:]:
best_profit = max(best_profit, price - min_price)
min_price = min(min_price, price)
return best_profit
print(max_profit([7, 1, 5, 3, 6, 4])) # 5
80. Count Sundays in N Days
Q. Jack loves Sundays. Given a starting day of the month
(e.g., "Monday") and a total number of days n, count how
many Sundays fall within that period.
Example 1:
Input: start = "Monday", n = 13
Output: 2
Explanation: Sundays fall on the 7th and 14th. Within 13 days, there
are 2 Sundays (assuming day 1 is the start).
Example 2:
Input: start = "Sunday", n = 1
Output: 1
Example 3:
Input: start = "Saturday", n = 5
Output: 1
Python Solution:
def count_sundays(start, n):
days = ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"]
start_idx = [Link](start)
days_to_first_sunday = (6 - start_idx) % 7
if n <= days_to_first_sunday:
return 0
return 1 + (n - days_to_first_sunday - 1) // 7
print(count_sundays("Monday", 13)) # 2
81. Longest Consecutive Sequence
Q. Given an integer array A of size N, return the length of
the longest successive sequence. A sequence is successive
when adjacent elements have an absolute difference of 1.
Example 1:
Input: A = [5, 8, 3, 2, 1, 4], N = 6
Output: 5
Explanation: The sequence is [1, 2, 3, 4, 5].
Example 2:
Input: A = [1, 9, 3, 10, 4, 20, 2]
Output: 4 ([1, 2, 3, 4])
Example 3:
Input: A = [10, 5, 100]
Output: 1
Python Solution:
def longest_consecutive_sequence(nums):
num_set = set(nums)
longest = 0
for x in num_set:
if x - 1 not in num_set:
length = 1
while x + length in num_set:
length += 1
longest = max(longest, length)
return longest
print(longest_consecutive_sequence([5, 8, 3, 2, 1, 4])) # 5
82. Split a String into Exactly 3 Palindromes
Q. Given a string, split it into exactly 3 palindromic
substrings. Choose the smallest possible split for the first
substring, then the smallest for the second, leaving a third
palindromic substring. If impossible, print "Impossible".
Example 1:
Input: nayannamantenet
Output: nayannamantenet
Example 2:
Input: aaaaa
Output: aaaaa
Example 3:
Input: abc
Output: Impossible
Python Solution:
def is_palindrome(s):
return s == s[::-1]
def split_into_3_palindromes(s):
n = len(s)
for i in range(1, n - 1):
first = s[0:i]
if not is_palindrome(first):
continue
for j in range(i + 1, n):
second = s[i:j]
third = s[j:n]
if is_palindrome(second) and is_palindrome(third):
return first + " | " + second + " | " + third
return "Impossible"
print(split_into_3_palindromes("aaaaa"))
83. Two-Wheelers and Four-Wheelers (Vehicles & Wheels)
Q. An automobile company manufactures both Two-
Wheelers (TW) and Four-Wheelers (FW). Given the total
number of vehicles (V) and the total number of wheels (W),
find the exact number of Two-Wheelers and Four-
Wheelers to manufacture.
Example 1:
Input: V = 200, W = 540
Output: TW = 130, FW = 70
Explanation: 130 + 70 = 200 vehicles. (70 x 4) + (130 x 2) = 540
wheels.
Example 2:
Input: V = 100, W = 200
Output: TW = 100, FW = 0
Example 3:
Input: V = 5, W = 100
Output: INVALID INPUT (Wheels cannot exceed 4 x V).
Python Solution:
def vehicles_and_wheels(V, W):
if W % 2 != 0 or W < 2 * V or W > 4 * V:
return "INVALID INPUT"
four_wheelers = (W - 2 * V) // 2
two_wheelers = V - four_wheelers
return two_wheelers, four_wheelers
Example 1:
Input: 2000
Output: Time Estimated: 25 minutes
Example 2:
Input: 0
Output: Time Estimated: 0 minutes
Example 3:
Input: 8000
Output: OVERLOADED
Python Solution:
def washing_machine_time(weight):
if weight < 0:
return "INVALID INPUT"
if weight == 0:
return "Time Estimated: 0 minutes"
if weight <= 2000:
return "Time Estimated: 25 minutes"
if weight <= 4000:
return "Time Estimated: 35 minutes"
if weight <= 7000:
return "Time Estimated: 45 minutes"
return "OVERLOADED"
Example 1:
Input: 20, 30, 40, 50, 2, 3, 14
Output: Total Income 2000 INR
Example 2:
Input: 10, 60
Output: Total Income 500 INR
Example 3:
Input: 130
Output: INVALID INPUT (Age must be \le 120).
Python Solution:
def total_doctor_income(ages):
total = 0
for age in ages:
if age <= 0 or age > 120:
return "INVALID INPUT"
if age < 17:
total += 200
elif age <= 40:
total += 400
else:
total += 300
return f"Total Income {total} INR"
Example 1:
Input: 10 (Binary: 1010)
Output: 5 (Toggled: 0101)
Example 2:
Input: 7 (Binary: 111)
Output: 0
Example 3:
Input: 1
Output: 0
Python Solution:
def toggle_all_bits(n):
if n == 0:
return 1
num_bits = n.bit_length()
mask = (1 << num_bits) - 1
return n ^ mask
Example 1:
Input: str = "bbbaaabbaba", L = 3
Output: 3 (Sets: bbb, aaa, bba, ba. Set 2 has three 'a's).
Example 2:
Input: str = "aaaaa", L = 2
Output: 2
Example 3:
Input: str = "bbbbb", L = 1
Output: 0
Python Solution:
def max_a_in_window(s, L):
best = 0
for i in range(0, len(s), L):
window = s[i:i + L]
best = max(best, [Link]('a'))
return best
print(max_a_in_window("bbbaaabbaba", 3)) # 3
88. Total Handshakes at a Meeting
Q. At a meeting, every person shakes hands with every
other person exactly once. Given the total number of people
N who attended, calculate the total count of handshakes
that took place.
Example 1:
Input: N = 1
Output: 0
Explanation: A lonely person has no one to shake hands with.
Example 2:
Input: N = 2
Output: 1
Explanation: Person A shakes hands with Person B.
Example 3:
Input: N = 10
Output: 45
Python Solution:
def total_handshakes(n):
return n * (n - 1) // 2
print(total_handshakes(10)) # 45
89. Count Fake Palindrome Substrings
Q. A "fake palindrome" is a string that can be rearranged
(permuted) to form a real palindrome. Given a string S, find
the number of different contiguous substrings that are
fake palindromes.
Example 1:
Input: S = "ABAB"
Output: 7
Explanation: Substrings: A, B, A, B, ABA, BAB, ABAB are all fake
palindromes.
Example 2:
Input: S = "AAA"
Output: 6
Example 3:
Input: S = "ABC"
Output: 3 (A, B, C)
Python Solution:
def count_fake_palindromes(s):
mask_count = {0: 1}
mask = 0
total = 0
for ch in s:
bit = 1 << (ord([Link]()) - ord('A'))
mask ^= bit
total += mask_count.get(mask, 0)
for b in range(26):
total += mask_count.get(mask ^ (1 << b), 0)
mask_count[mask] = mask_count.get(mask, 0) + 1
return total
print(count_fake_palindromes("ABAB")) # 7
90. Max Root-to-Leaf Path Sum Not Divisible by K
Q. Find the maximum sum path from the root to any leaf
node in a binary tree such that the total sum of the path is
not divisible by a given integer
Example 1:
Input: Nodes = 7, K = 5, Tree: 3->8->10
Output: 21
Explanation: Path 3-8-10 sum is 21. $21 \pmod 5 \neq 0.
Example 2:
Input: Nodes = 3, K = 2, Values = [2, 2, 2]
Output: -1 (All paths sum to 4, which is divisible by 2).
Example 3:
Input: K = 1
Output: -1 (Every sum is divisible by 1).
Python Solution:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
[Link] = val
[Link] = left
[Link] = right
dfs(root, 0)
return best[0]
91. Kriya - Maximize Sum with No Adjacent Picks
Q. You have m series of numbers from 1 to n. A "Kriya" on
number x removes x-1 and x+1. You cannot perform a Kriya
on adjacent numbers. Maximize the sum of chosen numbers
across all series.
Example 1:
Input: n = 4
Output: 6 (For one series)
Explanation: Choose {2, 4}. Sum = 2+4=6. If we chose 3, neighbors 2
and 4 vanish, total sum = 3+1=4.
Example 2:
Input: n = 3
Output: 4 (Choose 1 and 3)
Example 3:
Input: n = 5
Output: 9 (Choose 1, 3, 5)
Python Solution:
def kriya_max_sum(n):
if n == 0:
return 0
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = max(dp[i - 1], i + dp[i - 2])
return dp[n]
print(kriya_max_sum(4)) # 6
print(kriya_max_sum(5)) # 9
92. Smallest N-Digit Number with Perfect Square Digit-Sum
Q. You are given an integer input n which signifies the
number of digits. Your task is to find the minimum possible
n-digit number such that the sum of the squares of its
digits is a perfect square. The digit '0' must not be
present, and the resulting number must be the smallest
possible valid number. Since n can be as large as 10^6, you
must construct the answer as a string rather than iterating
through all numbers.
Example 1:
Input: n=3
Output: 122 (Explanation: 1^2+2^2+2^2 = 9 = 3^2).
Example 2:
Input: n=1
Output: 1 (Explanation: 1^2 = 1 = 1^2).
Example 3:
Input: n=2
Output: 34 (Explanation: 3^2+4^2 = 25 = 5^2).
Python Solution:
def smallest_n_digit_number(n):
for i in range(1, 10):
s = (n - 1) + i * i
root = int(s ** 0.5)
if root * root == s:
return '1' * (n - 1) + str(i)
for i in range(1, 10):
for j in range(1, 10):
s = (n - 2) + i * i + j * j
root = int(s ** 0.5)
if root * root == s:
return '1' * (n - 2) + str(i) + str(j)
return ""
print(smallest_n_digit_number(3)) # "122"
print(smallest_n_digit_number(2)) # "34"
93. Minimum Swaps to Move Max Element to Center
Q. Given an N x N matrix of distinct integers where N is
always odd. Your task is to move the maximum element of
the matrix to the exact center. You can swap adjacent rows
or adjacent columns. Each swap counts as 1 move; find the
minimum number of swaps required.
Example 1:
Input: N=5, Max element at [2][2]
Output: 0.
Example 2:
Input: N=3, Max element at [0][0]
Output: 2 (1 row swap + 1 column swap).
Example 3:
Input: N=5, Max element at [0][4]
Output: 4 (2 row swaps + 2 column swaps).
Python Solution:
def min_swaps_to_center(N, r, c):
center = N // 2
return abs(r - center) + abs(c - center)
print(min_swaps_to_center(5, 2, 2)) # 0
print(min_swaps_to_center(3, 0, 0)) # 2
94. Task Scheduler with Cooldown
Q. You are a chef with a list of tasks (dishes). Each task
takes 1 unit of time. After cooking a dish, you cannot cook
that same dish again for at least N units of time (cooldown).
During cooldown, you can cook other dishes. If no dishes
are available, you must stay idle ("NOTHING"). Minimize
the total time and return the sequence.
Example 1:
Input: tasks=["A", "A", "A", "B", "B", "B"], n=2
Output: ['A', 'B', 'NOTHING', 'A', 'B', 'NOTHING', 'A', 'B'].
Example 2:
Input: tasks=["A", "A"], n=1
Output: ['A', 'NOTHING', 'A'].
Example 3:
Input: tasks=["A", "B", "C"], n=3
Output: ['A', 'B', 'C'].
Python Solution:
import heapq
from collections import Counter, deque
print(task_scheduler(["A","A","A","B","B","B"], 2))
# ['A', 'B', 'NOTHING', 'A', 'B', 'NOTHING', 'A', 'B']
95. Round a Floating-Point Number to 2 Decimals
Q. You are given a floating-point number X. Your task is to
round this number to exactly two decimal places. If the
third decimal digit is 5 or greater, round up the second
digit. If it is less than 5, keep the second digit as is.
Example 1:
Input: 9.678
Output: 9.68.
Example 2:
Input: 0.005
Output: 0.01.
Example 3:
Input: 1.444
Output: 1.44.
Python Solution:
def round_two_decimals(x):
return int(x * 100 + 0.5) / 100.0
print(round_two_decimals(9.678)) # 9.68
print(round_two_decimals(0.005)) # 0.01
print(round_two_decimals(1.444)) # 1.44