Coding Questions
Coding Questions
Coding Questions
Input Format
Two floating-point numbers: the first-place time and the average time.
Example
Python
def race_results(times):
if not times:
return None, 0
first_place_time = min(times)
average_time = sum(times) / len(times)
return first_place_time, average_time
# Example usage
print(race_results([12.5, 10.0, 11.2, 13.3])) # Output: (10.0, 11.5)
Java
#include <stdio.h>
*firstPlace = times[0];
double totalTime = 0;
int main() {
double times[] = {12.5, 10.0, 11.2, 13.3};
double firstPlace, average;
raceResults(times, 4, &firstPlace, &average);
printf("First Place Time: %.2f, Average Time: %.2f\n", firstPlace, average);
return 0;
}
2. In a magical forest, each animal has a unique identifier (ID). Some animals have
decided to form pairs based on their IDs. Your task is to find all the unique pairs
of animal IDs that can be formed.
Input Format
Python
def unique_pairs(animal_ids):
pairs = []
for i in range(len(animal_ids)):
for j in range(i + 1, len(animal_ids)):
pairs.append((animal_ids[i], animal_ids[j]))
return pairs
# Example usage
print(unique_pairs([1, 2, 3])) # Output: [(1, 2), (1, 3), (2, 3)]
Java
import java.util.ArrayList;
import java.util.List;
#include <stdio.h>
int main() {
int animalIds[] = {1, 2, 3};
uniquePairs(animalIds, 3);
return 0;
}
3. In a small village, there are treasure chests scattered around. Each chest has a
certain number of coins, and some chests have been cursed, causing them to give
negative coins. Your task is to find the maximum sum of coins you can collect from
a consecutive series of chests.
Input Format
Python
def max_treasure(chests):
max_sum = current_sum = 0
for coins in chests:
current_sum += coins
if current_sum < 0:
current_sum = 0
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage
print(max_treasure([2, -3, 4, -1, 2, 1, -5, 4])) # Output: 6
Java
#include <stdio.h>
int main() {
int chests[] = {2, -3, 4, -1, 2, 1, -5, 4};
printf("%d\n", maxTreasure(chests, 8)); // Output: 6
return 0;
}
4. The royal baker needs to prepare a special cake. Each ingredient has a specific
weight. The baker wants to know the total weight of the ingredients and the
heaviest ingredient used.
Input Format
Two floating-point numbers: the total weight and the heaviest ingredient.
Example
Python
def cake_ingredients(weights):
if not weights:
return 0, 0
total_weight = sum(weights)
heaviest = max(weights)
return total_weight, heaviest
# Example usage
print(cake_ingredients([1.2, 0.5, 2.3, 1.8])) # Output: (5.8, 2.3)
Java
double totalWeight = 0;
double heaviest = weights[0];
#include <stdio.h>
*totalWeight = 0;
*heaviest = weights[0];
int main() {
double weights[] = {1.2, 0.5, 2.3, 1.8};
double totalWeight, heaviest;
cakeIngredients(weights, 4, &totalWeight, &heaviest);
printf("Total Weight: %.2f, Heaviest Ingredient: %.2f\n", totalWeight,
heaviest);
return 0;
}
5. In an enchanted garden, flowers bloom in various colors, and each color has a
specific point value. Your task is to calculate the total points based on the
flowers picked by a gardener.
Input Format
Input: [5, 3, 8, 2]
Output: 18
Python
def total_flower_points(flowers):
total_points = 0
for points in flowers:
total_points += points
return total_points
if __name__ == "__main__":
print(total_flower_points([5, 3, 8, 2])) # Output: 18
Java
#include <stdio.h>
int main() {
int flowers[] = {5, 3, 8, 2};
printf("%d\n", totalFlowerPoints(flowers, 4)); // Output: 18
return 0;
}
6. A time traveler collects artifacts from different years. Each artifact has a
year associated with it. Your task is to find the range of years from the earliest
to the latest artifact collected.
Input Format
Python
def year_range(artifacts):
return max(artifacts) - min(artifacts)
# Example usage
print(year_range([1995, 2001, 1985, 2010])) # Output: 25
Java
#include <stdio.h>
int main() {
int artifacts[] = {1995, 2001, 1985, 2010};
printf("%d\n", yearRange(artifacts, 4)); // Output: 25
return 0;
}
7. In a mysterious library, each book has a unique ID, and some books are quite
old. Your task is to find the ID of the oldest book and the average ID of all the
books.
Input Format
Two integers: the ID of the oldest book and the average ID (rounded down)
Example
Python
def book_info(books):
oldest = min(books)
average = sum(books) // len(books)
return oldest, average
# Example usage
print(book_info([1001, 1002, 999, 1003])) # Output: (999, 1001)
Java
#include <stdio.h>
void bookInfo(int books[], int size, int* oldest, int* average) {
*oldest = books[0];
int total = 0;
int main() {
int books[] = {1001, 1002, 999, 1003};
int oldest, average;
bookInfo(books, 4, &oldest, &average);
printf("Oldest ID: %d, Average ID: %d\n", oldest, average); // Output: (999,
1001)
return 0;
}
8. A dragon hoards treasures in different forms, each with a specific value. Your
task is to calculate the total value of the treasures and find the highest value
among them.
Input Format
Python
def dragon_hoard(treasures):
total_value = sum(treasures)
highest_value = max(treasures)
return total_value, highest_value
# Example usage
print(dragon_hoard([200, 500, 1000, 300])) # Output: (2000, 1000)
Java
#include <stdio.h>
int main() {
int treasures[] = {200, 500, 1000, 300};
int totalValue, highestValue;
dragonHoard(treasures, 4, &totalValue, &highestValue);
printf("Total Value: %d, Highest Value: %d\n", totalValue, highestValue); //
Output: (2000, 1000)
return 0;
}
A list of integers representing the ingredient IDs and an integer representing the
ID to check.
Output Format
Python
# Example usage
print(check_ingredient([101, 102, 103, 104], 102)) # Output: Yes
Java
import java.util.Arrays;
#include <stdio.h>
int main() {
int ingredients[] = {101, 102, 103, 104};
printf("%s\n", checkIngredient(ingredients, 4, 102)); // Output: Yes
return 0;
}
Input: [3, 7, 5, 9]
Output: (24, 9)
Python
def timekeeper_clocks(clocks):
total_hours = sum(clocks)
highest_hour = max(clocks)
return total_hours, highest_hour
# Example usage
print(timekeeper_clocks([3, 7, 5, 9])) # Output: (24, 9)
Java
#include <stdio.h>
int main() {
int clocks[] = {3, 7, 5, 9};
int totalHours, highestHour;
timekeeperClocks(clocks, 4, &totalHours, &highestHour);
printf("Total Hours: %d, Highest Hour: %d\n", totalHours, highestHour); //
Output: (24, 9)
return 0;
}
Given an array of integers, write a function to reverse the order of the elements
in the array.
Approach:
One simple approach to reversing an array is to use two pointers – one at the
beginning and one at the end of the array. Swap the elements at these two pointers,
then move the pointers inward until they meet in the middle.
Solution:
python
def reverse_array(arr):
left = 0
right = len(arr) – 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
Given an array of integers, write a function to find all the duplicate elements in
the array.
Approach:
One approach is to use a hash table (dictionary in Python, HashMap in Java) to keep
track of the frequency of each element in the array. Then, we can iterate through
the hash table and add the elements with a frequency greater than 1 to the result
list.
Solution:
python
def find_duplicates(arr):
freq = {}
for num in arr:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
duplicates = [num for num, count in freq.items() if count > 1]
return duplicates
Space Complexity: O(n), as we are using a hash table to store the frequency of each
element.
Fibonacci Sequence
Problem Statement:
Approach:
The Fibonacci sequence is a series of numbers in which each number is the sum of
the two preceding ones, usually starting with 0 and 1. We can generate the
Fibonacci sequence using a simple loop.
Solution:
python
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib = [0, 1]
for i in range(2, n):
fib.append(fib[-1] + fib[-2])
return fib
Palindrome Check
Problem Statement:
Write a function to check if a given string is a palindrome (i.e., reads the same
forwards and backwards).
Approach:
Solution:
python
def is_palindrome(s):
left = 0
right = len(s) – 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
Space Complexity: O(1), as we are only using a constant amount of extra space.
Given the head of a singly linked list, write a function to reverse the order of
the nodes in the list.
Approach:
Solution:
python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_linked_list(head):
prev = None
curr = head
while curr is not None:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(1), as we are only using a constant amount of extra space.
Implement a binary search tree (BST) data structure, including functions to insert,
search, and delete nodes.
Approach:
A binary search tree is a tree-based data structure where each node has at most two
child nodes. The left child of a node contains a value less than the node’s value,
and the right child contains a value greater than the node’s value.
Solution:
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, val):
self.root = self._insert(self.root, val)
def _insert(self, node, val):
if not node:
return TreeNode(val)
if val < node.val:
node.left = self._insert(node.left, val)
else:
node.right = self._insert(node.right, val)
return node
return node
else:
if not node:
return None
else:
if not node.left:
return node.right
return node.left
node.val = self._min_value(node.right)
return node
node = node.left
return node.val
Time Complexity:
Insert: O(log n)
Search: O(log n)
Delete: O(log n)
Space Complexity: O(n), where n is the number of nodes in the BST.
Approach:
BFS and DFS are two fundamental graph traversal algorithms. BFS explores the graph
level by level, while DFS explores the graph as far as possible along each branch
before backtracking.
Solution:
python
queue = deque([start])
visited = set([start])
while queue:
node = queue.popleft()
visited.add(neighbor)
queue.append(neighbor)
return visited
stack = [start]
visited = set([start])
while stack:
node = stack.pop()
visited.add(neighbor)
stack.append(neighbor)
return visited
Time Complexity:
BFS: O(V + E), where V is the number of vertices and E is the number of edges in
the graph.
DFS: O(V + E), where V is the number of vertices and E is the number of edges in
the graph.
Space Complexity:
Given a set of items, each with a weight and a value, and a maximum weight
capacity, determine the maximum total value of items that can be included in a
knapsack without exceeding the weight limit.
Approach:
Solution:
python
n = len(weights)
if weights[i – 1] <= w:
else:
Time Complexity: O(n * capacity), where n is the number of items and capacity is
the maximum weight capacity.
Given a weighted graph, find the shortest path between two specified nodes.
Approach:
One of the most popular algorithms for finding the shortest path in a weighted
graph is Dijkstra’s algorithm. It uses a greedy approach to find the shortest path
by repeatedly selecting the node with the smallest distance from the unvisited
nodes.
Solution:
python
import heapq
distances[start] = 0
while heap:
continue
if current_node == end:
return current_distance
distances[neighbor] = distance
return -1