Coding Questions

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 19

1. In a race, each participant's finish time is recorded.

You need to find out who


finished first and how long it took them. Additionally, you need to find the
average finish time of all participants.

Input Format

A list of floating-point numbers representing finish times.


Output Format

Two floating-point numbers: the first-place time and the average time.
Example

Input: [12.5, 10.0, 11.2, 13.3]


Output: (10.0, 11.5)

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

public class Main {


public static double[] raceResults(double[] times) {
if (times.length == 0) return new double[]{-1, 0};

double firstPlaceTime = times[0];


double totalTime = 0;

for (double time : times) {


if (time < firstPlaceTime) firstPlaceTime = time;
totalTime += time;
}

double averageTime = totalTime / times.length;


return new double[]{firstPlaceTime, averageTime};
}

public static void main(String[] args) {


double[] results = raceResults(new double[]{12.5, 10.0, 11.2, 13.3});
System.out.println("First Place Time: " + results[0] + ", Average Time: " +
results[1]);
}
}

#include <stdio.h>

void raceResults(double times[], int size, double* firstPlace, double* average) {


if (size == 0) {
*firstPlace = -1;
*average = 0;
return;
}

*firstPlace = times[0];
double totalTime = 0;

for (int i = 0; i < size; i++) {


if (times[i] < *firstPlace) *firstPlace = times[i];
totalTime += times[i];
}

*average = totalTime / size;


}

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

A list of integers representing animal IDs.


Output Format

A list of unique pairs of animal IDs.


Input: [1, 2, 3]
Output: [(1, 2), (1, 3), (2, 3)]

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;

public class Main {


public static List<int[]> uniquePairs(int[] animalIds) {
List<int[]> pairs = new ArrayList<>();
for (int i = 0; i < animalIds.length; i++) {
for (int j = i + 1; j < animalIds.length; j++) {
pairs.add(new int[]{animalIds[i], animalIds[j]});
}
}
return pairs;
}

public static void main(String[] args) {


List<int[]> result = uniquePairs(new int[]{1, 2, 3});
for (int[] pair : result) {
System.out.println("Pair: " + pair[0] + ", " + pair[1]);
}
}
}

#include <stdio.h>

void uniquePairs(int animalIds[], int size) {


for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
printf("Pair: %d, %d\n", animalIds[i], animalIds[j]);
}
}
}

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

A list of integers representing the coins in each chest.


Output Format

An integer representing the maximum sum of coins from consecutive chests.


Example

Input: [2, -3, 4, -1, 2, 1, -5, 4]


Output: 6

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

public class Main {


public static int maxTreasure(int[] chests) {
int maxSum = 0, currentSum = 0;
for (int coins : chests) {
currentSum += coins;
if (currentSum < 0) currentSum = 0;
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}

public static void main(String[] args) {


System.out.println(maxTreasure(new int[]{2, -3, 4, -1, 2, 1, -5, 4})); //
Output: 6
}
}

#include <stdio.h>

int maxTreasure(int chests[], int size) {


int maxSum = 0, currentSum = 0;
for (int i = 0; i < size; i++) {
currentSum += chests[i];
if (currentSum < 0) currentSum = 0;
if (currentSum > maxSum) maxSum = currentSum;
}
return maxSum;
}

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

A list of floating-point numbers representing the weights of the ingredients.


Output Format

Two floating-point numbers: the total weight and the heaviest ingredient.
Example

Input: [1.2, 0.5, 2.3, 1.8]


Output: (5.8, 2.3)

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

public class Main {


public static double[] cakeIngredients(double[] weights) {
if (weights.length == 0) return new double[]{0, 0};

double totalWeight = 0;
double heaviest = weights[0];

for (double weight : weights) {


totalWeight += weight;
if (weight > heaviest) heaviest = weight;
}

return new double[]{totalWeight, heaviest};


}

public static void main(String[] args) {


double[] results = cakeIngredients(new double[]{1.2, 0.5, 2.3, 1.8});
System.out.println("Total Weight: " + results[0] + ", Heaviest Ingredient:
" + results[1]);
}
}

#include <stdio.h>

void cakeIngredients(double weights[], int size, double* totalWeight, double*


heaviest) {
if (size == 0) {
*totalWeight = 0;
*heaviest = 0;
return;
}

*totalWeight = 0;
*heaviest = weights[0];

for (int i = 0; i < size; i++) {


*totalWeight += weights[i];
if (weights[i] > *heaviest) *heaviest = weights[i];
}
}

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

A list of integers representing the points for each flower.


Output Format

An integer representing the total points earned from the flowers.


Example

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

public class Main {


public static int totalFlowerPoints(int[] flowers) {
int totalPoints = 0;
for (int points : flowers) {
totalPoints += points;
}
return totalPoints;
}

public static void main(String[] args) {


System.out.println(totalFlowerPoints(new int[]{5, 3, 8, 2})); // Output:
18
}
}

#include <stdio.h>

int totalFlowerPoints(int flowers[], int size) {


int totalPoints = 0;
for (int i = 0; i < size; i++) {
totalPoints += flowers[i];
}
return totalPoints;
}

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

A list of integers representing the years.


Output Format

An integer representing the range of years (latest year - earliest year).


Input: [1995, 2001, 1985, 2010]
Output: 25

Python

def year_range(artifacts):
return max(artifacts) - min(artifacts)

# Example usage
print(year_range([1995, 2001, 1985, 2010])) # Output: 25

Java

public class Main {


public static int yearRange(int[] artifacts) {
int minYear = artifacts[0];
int maxYear = artifacts[0];

for (int year : artifacts) {


if (year < minYear) minYear = year;
if (year > maxYear) maxYear = year;
}

return maxYear - minYear;


}

public static void main(String[] args) {


System.out.println(yearRange(new int[]{1995, 2001, 1985, 2010})); //
Output: 25
}
}

#include <stdio.h>

int yearRange(int artifacts[], int size) {


int minYear = artifacts[0];
int maxYear = artifacts[0];

for (int i = 1; i < size; i++) {


if (artifacts[i] < minYear) minYear = artifacts[i];
if (artifacts[i] > maxYear) maxYear = artifacts[i];
}
return maxYear - minYear;
}

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

A list of integers representing book IDs.


Output Format

Two integers: the ID of the oldest book and the average ID (rounded down)
Example

Input: [1001, 1002, 999, 1003]


Output: (999, 1001)

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

public class Main {


public static int[] bookInfo(int[] books) {
int oldest = books[0];
int total = 0;

for (int id : books) {


if (id < oldest) oldest = id;
total += id;
}

int average = total / books.length;


return new int[]{oldest, average};
}

public static void main(String[] args) {


int[] result = bookInfo(new int[]{1001, 1002, 999, 1003});
System.out.println("(" + result[0] + ", " + result[1] + ")"); // Output:
(999, 1001)
}
}

#include <stdio.h>
void bookInfo(int books[], int size, int* oldest, int* average) {
*oldest = books[0];
int total = 0;

for (int i = 0; i < size; i++) {


if (books[i] < *oldest) *oldest = books[i];
total += books[i];
}

*average = total / size;


}

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

A list of integers representing the values of the treasures.


Output Format

Two integers: the total value and the highest value.


Example

Input: [200, 500, 1000, 300]


Output: (2000, 1000)

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

public class Main {


public static int[] dragonHoard(int[] treasures) {
int totalValue = 0;
int highestValue = treasures[0];

for (int value : treasures) {


totalValue += value;
if (value > highestValue) highestValue = value;
}

return new int[]{totalValue, highestValue};


}
public static void main(String[] args) {
int[] result = dragonHoard(new int[]{200, 500, 1000, 300});
System.out.println("(" + result[0] + ", " + result[1] + ")"); // Output:
(2000, 1000)
}
}

#include <stdio.h>

void dragonHoard(int treasures[], int size, int* totalValue, int* highestValue) {


*totalValue = 0;
*highestValue = treasures[0];

for (int i = 0; i < size; i++) {


*totalValue += treasures[i];
if (treasures[i] > *highestValue) *highestValue = treasures[i];
}
}

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;
}

9. A wizard brews a secret potion using various magical ingredients, each


represented by a unique integer ID. Your task is to identify if a specific
ingredient ID is used in the potion.
Input Format

A list of integers representing the ingredient IDs and an integer representing the
ID to check.
Output Format

A string indicating whether the ingredient ID is used ("Yes" or "No").


Example

Input: [101, 102, 103, 104], 102


Output: Yes

Python

def check_ingredient(ingredients, id_to_check):


return "Yes" if id_to_check in ingredients else "No"

# Example usage
print(check_ingredient([101, 102, 103, 104], 102)) # Output: Yes

Java

import java.util.Arrays;

public class Main {


public static String checkIngredient(int[] ingredients, int idToCheck) {
return Arrays.stream(ingredients).anyMatch(id -> id == idToCheck) ? "Yes" :
"No";
}

public static void main(String[] args) {


System.out.println(checkIngredient(new int[]{101, 102, 103, 104},
102)); // Output: Yes
}
}

#include <stdio.h>

const char* checkIngredient(int ingredients[], int size, int idToCheck) {


for (int i = 0; i < size; i++) {
if (ingredients[i] == idToCheck) {
return "Yes";
}
}
return "No";
}

int main() {
int ingredients[] = {101, 102, 103, 104};
printf("%s\n", checkIngredient(ingredients, 4, 102)); // Output: Yes
return 0;
}

10. A timekeeper has a collection of clocks, each representing a specific hour.


Your task is to calculate the total hours represented by the clocks and find the
clock showing the highest hour.
Input Format

A list of integers representing the hours of the clocks.


Output Format

Two integers: the total hours and the highest hour.


Example

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

public class Main {


public static int[] timekeeperClocks(int[] clocks) {
int totalHours = 0;
int highestHour = clocks[0];

for (int hour : clocks) {


totalHours += hour;
if (hour > highestHour) highestHour = hour;
}

return new int[]{totalHours, highestHour};


}

public static void main(String[] args) {


int[] result = timekeeperClocks(new int[]{3, 7, 5, 9});
System.out.println("(" + result[0] + ", " + result[1] + ")"); // Output:
(24, 9)
}
}

#include <stdio.h>

void timekeeperClocks(int clocks[], int size, int* totalHours, int* highestHour) {


*totalHours = 0;
*highestHour = clocks[0];

for (int i = 0; i < size; i++) {


*totalHours += clocks[i];
if (clocks[i] > *highestHour) *highestHour = clocks[i];
}
}

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;
}

Accenture Coding Questions: Beginner-Level


Array Reversal
Problem Statement:

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

Time Complexity: O(n), where n is the length of the input array.

Space Complexity: O(1), as we are modifying the input array in-place.

Finding Duplicates in an Array


Problem Statement:

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

Time Complexity: O(n), where n is the length of the input array.

Space Complexity: O(n), as we are using a hash table to store the frequency of each
element.

Fibonacci Sequence
Problem Statement:

Write a function to generate the first n numbers in the Fibonacci sequence.

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

Time Complexity: O(n), where n is the number of Fibonacci numbers to generate.

Space Complexity: O(n), as we are storing the generated Fibonacci numbers in a


list.

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:

To check if a string is a palindrome, we can compare the characters at the


beginning and end of the string, then move inwards until we reach the middle of the
string.

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

Time Complexity: O(n), where n is the length of the input string.

Space Complexity: O(1), as we are only using a constant amount of extra space.

Accenture Coding Questions: Intermediate-Level


Linked List Reversal
Problem Statement:

Given the head of a singly linked list, write a function to reverse the order of
the nodes in the list.
Approach:

To reverse a linked list, we can use a three-pointer approach. We maintain three


pointers: prev, curr, and next. We iterate through the list, updating the pointers
to reverse the links between the nodes.

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.

Binary Search Tree Implementation


Problem Statement:

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

def search(self, val):

return self._search(self.root, val)

def _search(self, node, val):

if not node or node.val == val:

return node

if val < node.val:

return self._search(node.left, val)

else:

return self._search(node.right, val)

def delete(self, val):

self.root = self._delete(self.root, val)

def _delete(self, node, val):

if not node:

return None

if val < node.val:

node.left = self._delete(node.left, val)

elif val > node.val:

node.right = self._delete(node.right, val)

else:

if not node.left:

return node.right

elif not node.right:

return node.left

node.val = self._min_value(node.right)

node.right = self._delete(node.right, node.val)

return node

def _min_value(self, node):


while node.left:

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.

Breadth-First Search/Depth-First Search


Problem Statement:

Implement a function to perform Breadth-First Search (BFS) or Depth-First Search


(DFS) on a graph represented as an adjacency list.

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

from collections import deque

def bfs(graph, start):

queue = deque([start])

visited = set([start])

while queue:

node = queue.popleft()

for neighbor in graph[node]:

if neighbor not in visited:

visited.add(neighbor)

queue.append(neighbor)

return visited

def dfs(graph, start):

stack = [start]

visited = set([start])

while stack:
node = stack.pop()

for neighbor in graph[node]:

if neighbor not in visited:

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:

BFS: O(V), as we are using a queue to store the visited nodes.


DFS: O(V), as we are using a stack to store the visited nodes.
Accenture Coding Questions: Advanced-Level
Dynamic Programming Problem (e.g., Knapsack Problem)
Problem Statement:

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:

The Knapsack problem is a classic dynamic programming problem. We can solve it


using a 2D array to store the maximum value that can be obtained for each weight
capacity and number of items.

Solution:

python

def knapsack(weights, values, capacity):

n = len(weights)

dp = [[0] * (capacity + 1) for _ in range(n + 1)]

for i in range(1, n + 1):

for w in range(1, capacity + 1):

if weights[i – 1] <= w:

dp[i][w] = max(dp[i – 1][w], dp[i – 1][w – weights[i – 1]] +


values[i – 1])

else:

dp[i][w] = dp[i – 1][w]


return dp[n][capacity]

Time Complexity: O(n * capacity), where n is the number of items and capacity is
the maximum weight capacity.

Space Complexity: O(n * capacity), as we are using a 2D array to store the


intermediate results.

Graph Algorithm (e.g., Shortest Path)


Problem Statement:

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

def dijkstra(graph, start, end):

distances = {node: float(‘inf’) for node in graph}

distances[start] = 0

heap = [(0, start)]

while heap:

current_distance, current_node = heapq.heappop(heap)

if current_distance > distances[current_node]:

continue

if current_node == end:

return current_distance

for neighbor, weight in graph[current_node].items():

distance = current_distance + weight

if distance < distances[neighbor]:

distances[neighbor] = distance

heapq.heappush(heap, (distance, neighbor))

return -1

You might also like