Accenture conducted its Cognitive and Technical Assessment on June 26, 2023, which included multiple programming-related questions.
During the Coding assessment, each participant was tasked with solving two coding-related questions from the following list:
Here are the questions that were asked during the assessment along with their answers(mainly consist of brute-force approach):
(Comment down how we can optimised it);
Question 1: Special Numbers
Problem Statement
you are given a function:
int DesiredArray(int Arr, int N, int k):The function accepts an array 'Arr' of size 'N' and an integer 'k'.
You have to find the 'K' smallest integers that are not divisible by any of the 'N' integers and return the sum of all 'K' integers.
Note:
Example:
Input:
K: 4
N: 5
Arr: [2,3,4,5,6]Output:
32Explanation:
First, K smallest non-divisible by Arr_i integers will be 1, 7, 11, 13. Hence the sum will be 32.
The custom input format for the above case:
5 4
2 3 4 5 6(The first line represents 'N' and 'K', the second line represents the element of the array 'Arr')
Sample input
K: 4
N: 4
Arr : [3,6,9,12]Sample Output
12The custom input format for the above case:
4 4
3 6 9 12(The first line represents 'N' and 'K', the second line represents the element of the array 'Arr')
Instructions:
Solution:
a. Intuition:
The code aims to find the K smallest integers that are not divisible by any of the N integers. It uses a brute force approach to iterate through numbers and checks divisibility using the isDivisible function.
b. Approach
c. Time Complexity:
The time complexity of the code is O(K * N log N) because of sorting the divisors array.
d. Space Complexity:
The space complexity of the code is O(N) for storing the divisors array.
Code:
C++ Code:
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isDivisible(int num, const vector<int>& divisors) {
for (int divisor : divisors) {
if (num % divisor == 0) {
return true;
}
}
return false;
}
int DesiredArray(int* Arr, int N, int K) {
vector<int> divisors(Arr, Arr + N);
sort(divisors.begin(), divisors.end());
int sum = 0;
int num = 1;
int count = 0;
while (count < K) {
if (!isDivisible(num, divisors)) {
sum += num;
count++;
}
num++;
}
return sum;
}
int main() {
int testcases;
cin>>testcases;
// while(testcases--){
int N, K;
cin >> N >> K;
int* Arr = new int[N];
for (int i = 0; i < N; i++) {
cin >> Arr[i];
}
int result = DesiredArray(Arr, N, K);
cout << result << endl;
delete[] Arr;
// }
return 0;
}Java Code:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static boolean isDivisible(int num, int[] divisors) {
for (int divisor : divisors) {
if (num % divisor == 0) {
return true;
}
}
return false;
}
public static int desiredArray(int[] arr, int N, int K) {
int[] divisors = Arrays.copyOf(arr, N);
Arrays.sort(divisors);
int sum = 0;
int num = 1;
int count = 0;
while (count < K) {
if (!isDivisible(num, divisors)) {
sum += num;
count++;
}
num++;
}
return sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testcases = scanner.nextInt();
// while (testcases-- > 0) {
int N = scanner.nextInt();
int K = scanner.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = scanner.nextInt();
}
int result = desiredArray(arr, N, K);
System.out.println(result);
// }
}
}Python
def is_divisible(num, divisors):
for divisor in divisors:
if num % divisor == 0:
return True
return False
def desired_array(arr, N, K):
divisors = sorted(arr)
sum = 0
num = 1
count = 0
while count < K:
if not is_divisible(num, divisors):
sum += num
count += 1
num += 1
return sum
testcases = int(input())
for _ in range(testcases):
N, K = map(int, input().split())
arr = list(map(int, input().split()))
result = desired_array(arr, N, K)
print(result)a. Approach:
The code follows a brute-force approach to solve the problem.
c. Time Complexity:
The time complexity of the code is O(K * N), where K is the number of desired non-divisible integers and N is the size of 'Arr'. This is because for each candidate number, the code iterates through all the elements in 'Arr' to check for divisibility.
d. Space Complexity:
The space complexity of the code is O(K), where K is the number of desired non-divisible integers. This is because it uses an unordered set ('nonDivisible') to store the non-divisible numbers, which can have a maximum size of K.
Overall, the code employs a straightforward approach to solve the problem but may not be the most efficient solution. It checks divisibility for each number individually, which can lead to longer execution times for larger inputs. Consideration of more optimized algorithms or number theory principles can improve the efficiency of the solution.
Code:
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int DesiredArray(int* Arr, int N, int K) {
unordered_set<int> nonDivisible;
for (int i = 1; nonDivisible.size() < K; i++) {
bool divisible = false;
for (int j = 0; j < N && Arr[j] * Arr[j] <= i; j++) {
if (i % Arr[j] == 0) {
divisible = true;
break;
}
}
if (!divisible) {
nonDivisible.insert(i);
}
}
int sum = 0;
for (int num : nonDivisible) {
sum += num;
}
return sum;
}
int main() {
int testcases;
cin >> testcases;
// while (testcases--) {
int N, K;
cin >> N >> K;
int* Arr = new int[N];
for (int i = 0; i < N; i++) {
cin >> Arr[i];
}
int result = DesiredArray(Arr, N, K);
cout << result << endl;
delete[] Arr;
// }
return 0;
}2. Add Alternate Nodes in Linked List
Problem Statement
There is a singly linked list represented by the following structure:
struct node
{
int data;
struct Node* next;
};Implement the following function:
struct Node* AddAlternateNodes(struct Node* head);The function accepts a pointer to the start of the linked list , 'head' as its argument . Implement the function to modify the given list in such a way that origin added to the value of next to the next node and return the modified list.
Note:
Example:
Input:
head: 1-> 2 -> 3 -> 4 -> 5 -> 6 -> 7
Output:
1 -> 2 -> 4 -> 6 -> 8 -> 10 -> 12
Explanation:
Adding original value of the node to its next to next node,
Replace value of '3' with 1 + 3 = 4
Replace value of '4' with 2 + 4 = 6
Replace value of '5' with 3 + 5 = 8
Replace value of '6' with 4 + 6 = 10
Replace value of '7' with 5 + 7 = 12
Thus obtained linked list is 1 -> 2 -> 4 -> 6 -> 8 -> 10 ->12
The custom input format for the above case:
7
1 2 3 4 5 6 7(The first line represents the number of nodes, the second line represents the linked list)
Sample input:
head : 2 -> 1 -> 9 -> 2Sample output:
2 -> 1 -> 11 -> 3 The custom input format for the above case:
4
2 1 9 2 (The first line represents the number of nodes, the second line represents the linked list)
Instructions:
a. Intuition
The code is designed to modify a singly linked list as follows:
For each node in the list (except the first two nodes), add the value of the current node to the value of the next to next node and update the value of the current node with the sum.
b. Approach
c. Time complexity:
Creating the linked list from an array takes O(n) time, where n is the length of the array.
Modifying the linked list also takes O(n) time, as we are traversing the list once.
Displaying the linked list takes O(n) time.
Overall, the time complexity of the code is O(n).
d. Space complexity
The space complexity is O(n) as we are creating a linked list of size n, where n is the length of the array.
Code:
C++
// Definition of the Node structure
struct Node {
int val;
Node* next;
Node(int x) : val(x), next(nullptr) {}
};
// Function to create a linked list from an array
Node* createLinkedListFromArray(vector<int>& arr) {
if (arr.empty()) {
return nullptr;
}
Node* dummy = new Node(-1);
Node* temp = new Node(arr[0]);
dummy->next = temp;
for (int i = 1; i < arr.size(); i++) {
temp->next = new Node(arr[i]);
temp = temp->next;
}
return dummy->next;
}
// Function to add alternate nodes
void addAlternateNodes(Node* head) {
if (head == nullptr) return;
Node* current = head->next;
int prevVal, currVal, nextVal;
prevVal = head->val;
currVal = current->val;
while (current != nullptr && current->next != nullptr) {
current = current->next;
nextVal = current->val;
current->val = prevVal + nextVal;
prevVal = currVal;
currVal = nextVal;
}
}
// Function to display the linked list
void displayLinkedList(Node* head) {
Node* current = head;
while (current != nullptr) {
cout << current->val << " ";
current = current->next;
}
cout << endl;
}
// Main function
int main() {
int n; cin>>n;
vector<int> arr(n);
for(int i=0; i<n; i++){
cin>>arr[i];
}
Node* head = createLinkedListFromArray(arr);
addAlternateNodes(head);
displayLinkedList(head);
return 0;
}
3. Distinct and Duplicate Integers
Problem Statement
Implement the following function:
def AddDistinctDuplicate(a,b,c,d):The function accepts four integers 'a','b','c' and 'd' as its argument . Implement the function to find the sum of distinct numbers and subtract the duplicate number and return the difference (sum of distinct number - duplicate number).
Examples:
Input:
a:5
b:4
c:4
d:9Output
10Explanation:
2 distinct number are 5 and 9. Sum of distinct number = 5+9 = 14. Duplicate number = 4. Difference = Sum of distinct numbers - Duplicate number = 14 - 4 = 10. Thus, output is 10.
The custom input format for the above case:
5
4
4
9(The first line represent 'a'. the second line represent 'b', the third line represent 'c', the fourth line represent 'd')
Sampe input
a: -1
b: 3
c: 8
d: -6Sample Output
4The custom input format for the above case:
-1
3
8
-6(The first line represent 'a'. the second line represent 'b', the third line represent 'c', the fourth line represent 'd')
Instructions:
a. Intuition
The code aims to find the sum of distinct numbers and subtract the duplicate number from it. To achieve this, it utilizes an unordered set data structure to track the distinct numbers encountered. By inserting each element into the set, it identifies whether the number is distinct or a duplicate.
b. Approach:
Create an empty unordered set called distinct_nums to store the distinct numbers.
Initialize variables distinct_sum to keep track of the sum of distinct numbers and duplicate to store the duplicate number.
For each input element a, b, c, and d:
Check if the element can be inserted into the distinct_nums set using insert().
If the element can be inserted (i.e., it is distinct), add it to the distinct_sum.
If the element cannot be inserted (i.e., it is a duplicate), assign it as the duplicate number.
Calculate the difference between the distinct_sum and the duplicate number.
Return the calculated difference as the result.
c. Time and Space Complexity:
Time Complexity:
The code iterates over the input elements once, performing insertions and lookups in the unordered set. Since the number of elements is fixed (4 in this case), the time complexity is O(1).
Space Complexity:
The code uses an unordered set to store the distinct numbers. In the worst case, all elements are distinct, resulting in a space complexity of O(4), which simplifies to O(1).
Overall, the approach has constant time complexity and space complexity, making it very efficient for this specific problem. The use of the unordered set allows for efficient lookup and insertion operations, ensuring the uniqueness of the distinct numbers.
Code:
C++
#include <unordered_set>
using namespace std;
int AddDistinctDuplicate(int a, int b, int c, int d) {
unordered_set<int> distinct_nums;
int distinct_sum = 0;
int duplicate = 0;
// Check for distinct numbers and calculate their sum
if (distinct_nums.insert(a).second) {
distinct_sum += a;
} else {
duplicate = a;
}
if (distinct_nums.insert(b).second) {
distinct_sum += b;
} else {
duplicate = b;
}
if (distinct_nums.insert(c).second) {
distinct_sum += c;
} else {
duplicate = c;
}
if (distinct_nums.insert(d).second) {
distinct_sum += d;
} else {
duplicate = d;
}
return distinct_sum - duplicate;
}a. Intuition:
The problem requires finding the sum of distinct numbers and subtracting the duplicate number from it. To solve this, the code utilizes a map data structure to count the frequencies of the input elements. By iterating over the elements, it determines which numbers are distinct and calculates their sum, while also identifying the duplicate number to subtract it later.
b. Approach:
Create an empty map called frequency to store the frequencies of the elements.
Iterate over the input elements a, b, c, and d.
For each element:
Check if it exists as a key in the frequency map.
c. Time and Space Complexity:
Time Complexity:
The code iterates over the input elements once, resulting in a time complexity of O(1) since the number of elements is fixed (4 in this case).
Space Complexity:
The code uses a map to store the frequencies of the elements. In the worst case, there can be 4 distinct elements, resulting in a space complexity of O(4), which simplifies to O(1).
Overall, the approach has constant time complexity and space complexity, making it very efficient for this specific problem.
C++
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int AddDistinctDuplicate(int a, int b, int c, int d) {
vector<int> elements = {a, b, c, d};
map<int, int> frequency;
// Store element frequencies in the map
for (int element : elements) {
frequency[element]++;
}
int distinct_sum = 0;
int duplicate = 0;
// Calculate sum of distinct numbers and find the duplicate
for (const auto& entry : frequency) {
if (entry.second == 1) {
distinct_sum += entry.first;
} else {
duplicate = entry.first;
}
}
return distinct_sum - duplicate;
}
int main() {
int a, b, c, d;
// Read inputs
cin >> a >> b >> c >> d;
// Calculate the result
int result = AddDistinctDuplicate(a, b, c, d);
// Print the result
cout << result << endl;
return 0;
}Python3
def AddDistinctDuplicate(a, b, c, d):
elements = [a, b, c, d]
frequency = {}
# Store element frequencies in the dictionary
for element in elements:
frequency[element] = frequency.get(element, 0) + 1
distinct_sum = 0
duplicate = 0
# Calculate sum of distinct numbers and find the duplicate
for entry in frequency.items():
if entry[1] == 1:
distinct_sum += entry[0]
else:
duplicate = entry[0]
return distinct_sum - duplicate
# Main function
if __name__ == "__main__":
a = int(input())
b = int(input())
c = int(input())
d = int(input())
# Calculate the result
result = AddDistinctDuplicate(a, b, c, d)
# Print the result
print(result)4. Lettered Number
Problem Statement:
you are required to implement the follwing function:
int LetteredNumberSum(char[] str, int len);The function accepts string 'str' ('str1' in case of Python) as its argument. Implement the function which returns sum of number equivalents of each letter in the given string 'str'.
The number equivalents are as follows:
A = 1
B = 10
C = 100
D = 1000
E = 10000
F = 100000
G = 1000000Assumption: 'str' contains upper case letters only
Note:
Number equivalent for any letter other than (A,B,C,D,E,F,G) is 0
Computed value lies with in integer range
Return 0 if 'str' is null (None, in case of Python)
Example:
Input:
DCCBAAOutput:
1212Explanation:
Sum = 1000 + 100 + 100 + 10 + 1 + 1 = 1212The custom input format for the above case:
6
DCCBAA(The first line represents the length of the string, the second line represents the string)
Sample input
GBCESample Output
1010110The custom input format for the above case:
4
GBCE(The first line represents the length of the string, the second line represents the string)
Instructions:
a. Intuition
The function LetteredNumberSum aims to calculate the sum of number equivalents of each letter in a given string. Each letter corresponds to a specific number value, and the task is to accumulate the sum of these number values.
b. Approach:
c. Time and Space Complexity:
The time complexity of this function is O(n), where n is the length of the input string. This is because we need to iterate through each character in the string once.
The space complexity is O(1) since we only use a constant amount of additional space to store the sum and other variables.
Code
C++
#include <iostream>
using namespace std;
int LetteredNumberSum(char* str, int len) {
if (str == nullptr) {
return 0;
}
int sum = 0;
for (int i = 0; i < len; i++) {
char letter = str[i];
int ans = 0;
switch (letter) {
case 'A':
ans = 1;
break;
case 'B':
ans = 10;
break;
case 'C':
ans = 100;
break;
case 'D':
ans = 1000;
break;
case 'E':
ans = 10000;
break;
case 'F':
ans = 100000;
break;
case 'G':
ans = 1000000;
break;
default:
ans = 0;
break;
}
sum += ans;
}
return sum;
}
int main() {
char str[] = "GBCE";
int len = sizeof(str) - 1;
int result = LetteredNumberSum(str, len);
cout << "Sum: " << result << endl;
return 0;
}5. Evaluate the given expression
Problem Statement
You are given a funtion,
int EvaluateExpression(char* expr);The function accepts a mathematical expression 'expr' as parameter. Implement the function to evaluate the given expression 'expr' and return the evaluated value.
Assumption:
Note:
Example:
Input:
expr : 2+3+5*4/2Output:
15Explanation:
2 + 3 + 5 * 4/2 = 2 + 3 + 10 = 15, hence 15 is the evaluated value.
The custom input format for the above case:
9
2 + 3+ 5* 4/2(The first line represents the length of the string, the second line represents the string)
Sample input
expr: 22 +15 - 2*7/3Sample Output
33The custom input format for the above case:
9
22 +15 - 2*7/3(The first line represents the length of the string, the second line represents the string)
Instructions:
a. Intuition:
The code aims to evaluate a mathematical expression by following the rules of operator precedence and performing the necessary operations. It uses stacks to store numbers and operators and iterates through the expression character by character.
b. Approach:
The code starts by checking if the input expression is null. It initializes two stacks, one for numbers and another for operators. It then iterates through the expression character by character.
If the current character is a space, it skips to the next character. If it is a digit, it parses the number by continuously multiplying the existing number by 10 and adding the digit value. The parsed number is then pushed onto the numbers stack.
If the current character is an operator, the code handles the precedence of operators. It compares the precedence of the current operator with the operators at the top of the stack.
If the topmost operator has higher precedence, it performs the operation using the top two numbers from the numbers stack and the top operator from the operators stack. The result is then pushed back to the numbers stack. This process continues until the stack is empty or the topmost operator has lower precedence than the current operator. Finally, the current operator is pushed onto the operators stack.
After processing all characters, the code evaluates any remaining operators and numbers by performing the corresponding operations. The final result is obtained from the top of the numbers stack.
c. Time Complexity:
The time complexity of this approach depends on the length of the expression. In the worst case, where the expression contains n characters, the code iterates through each character once. Therefore, the time complexity is O(n).
d. Space Complexity:
The space complexity is determined by the number of operators encountered in the expression. In the worst case, where there are m operators, the code uses two stacks to store the numbers and operators. Therefore, the space complexity is O(m).
Code:
C++
#include <iostream>
#include <stack>
using namespace std;
int EvaluateExpression(char* expr) {
if (expr == nullptr) {
return 0;
}
stack<int> numbers;
stack<char> operators;
int i = 0;
while (expr[i] != '\0') {
if (expr[i] == ' ') {
// Skip spaces
i++;
continue;
}
if (isdigit(expr[i])) {
// If current character is a digit, parse the number
int num = 0;
while (isdigit(expr[i])) {
num = num * 10 + (expr[i] - '0');
i++;
}
numbers.push(num);
} else {
// If current character is an operator, handle precedence
while (!operators.empty() && ((operators.top() == '*' || operators.top() == '/') ||
(operators.top() == '+' || operators.top() == '-') && (expr[i] == '+' || expr[i] == '-'))) {
int num2 = numbers.top();
numbers.pop();
int num1 = numbers.top();
numbers.pop();
char op = operators.top();
operators.pop();
// Perform the operation based on the operator
int result;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
// Push the result back to the numbers stack
numbers.push(result);
}
// Push the current operator to the operators stack
operators.push(expr[i]);
i++;
}
}
// Evaluate remaining operators and numbers
while (!operators.empty()) {
int num2 = numbers.top();
numbers.pop();
int num1 = numbers.top();
numbers.pop();
char op = operators.top();
operators.pop();
int result;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
numbers.push(result);
}
// Return the final result
return numbers.top();
}
int main() {
int length;
cin >> length;
char expr[length];
cin.ignore();
cin.getline(expr, length + 1);
int result = EvaluateExpression(expr);
cout << result << endl;
return 0;
}
Python
def EvaluateExpression(expr):
if expr is None:
return 0
numbers = []
operators = []
i = 0
while i < len(expr):
if expr[i] == ' ':
# Skip spaces
i += 1
continue
if expr[i].isdigit():
# If current character is a digit, parse the number
num = 0
while i < len(expr) and expr[i].isdigit():
num = num * 10 + int(expr[i])
i += 1
numbers.append(num)
else:
# If current character is an operator, handle precedence
while operators and ((operators[-1] == '*' or operators[-1] == '/') or
(operators[-1] == '+' or operators[-1] == '-') and (expr[i] == '+' or expr[i] == '-')):
num2 = numbers.pop()
num1 = numbers.pop()
op = operators.pop()
# Perform the operation based on the operator
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
elif op == '/':
result = num1 // num2
# Push the result back to the numbers list
numbers.append(result)
# Push the current operator to the operators list
operators.append(expr[i])
i += 1
# Evaluate remaining operators and numbers
while operators:
num2 = numbers.pop()
num1 = numbers.pop()
op = operators.pop()
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
elif op == '/':
result = num1 // num2
numbers.append(result)
# Return the final result
return numbers[-1]
length = int(input())
expr = input()
result = EvaluateExpression(expr)
print("Result:", result)6. Maximum Element And Its Index
Problem Statement:
You are given a function,
Void MaxInArray(int arr[],int length);The function accepts an integer array 'arr' of size 'length' as its argument. Implement the function to find the maximum element of the array and print the element and its index to the standard output (STDOUT) . The maximum element and its index should be printed in separate lines.
Notes:
Exampe 1:
23 45 82 27 66 12 78 13 71 86Output:
86
9Explanation:
86 is the maximum element of array at index 9.
The custon input format for the above case:
10
23 45 82 27 66 12 78 13 71 86(the first line repersent 'length', the second line repersents the element of the array 'arr')
Example 2:
1 9 11 144 6 7 112 95Output 2:
144
3The custom input format for the above case:
8
1 9 11 144 6 7 112 95(the first line repersent 'length', the second line repersents the elements of the array 'arr')
Instructions:
a. Intuition:
The code aims to find the maximum element in an integer array and its corresponding index.
b. Approach:
c. Time Complexity:
The time complexity of the code is O(n), where n is the length of the array. This is because it iterates through each element of the array once.
d. Space Complexity:
The space complexity of the code is O(1) because it uses a constant amount of extra space to store the maximum value and the index.
Code
C
void MaxInArray(int arr[], int length){
int max = INT_MIN, index =-1;
for(int i =0; i<length; i++){
if(arr[i]> max)
{
max = arr[i];
index =i;
}
}
printf("%d\n%d\n", max, index);
}
Java
class Solution {
public static void MaxInArray(int[] arr, int length) {
int max = Integer.MIN_VALUE;
int index = -1;
for (int i = 0; i < length; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
System.out.println(max);
System.out.println(index);
}
}
7. Fine Number
Problem Statement
You are given a function:
int FineNumber(int* a, int* b, int n, int m);The function accepts two arrays 'a' and 'b' of size 'n' and 'm' respectively. Implement the function to compute a fine number and return the same.
A fine number is the greatest number that can be obtained by taking the difference of two numbers such that one of the two numbers is taken from array 'a' and the other is taken from array 'b'.
Example:
Input:
n: 5
m: 6
a: 1 2 3 4 5
b: 10 12 34 2 4 89Output:
88Explanation:
Here, the greatest difference is between a 1 from array 'a' and 89 from array 'b'.
**the custom input format for the above case:
5 6
1 2 3 4 5
10 12 34 2 4 89(The first line represent 'n' and 'm', the second line represents the elements of the array 'a', and the third line represents the elements of the array 'b'.)
Sample input
n: 4
m: 3
a: 6 7 8 11
b: 3 1 2Sample output
10The custom input format for the above case:
4 3
6 7 8 11
3 1 2(The first line represent 'n' and 'm', the second line represents the elements of the array 'a', and the third line represents the elements of the array 'b'.)
Instructions:
A. Intuition:
The code aims to find the maximum difference between any two numbers, where one number is from vector a and the other number is from vector b.
B. Approach:
C. Time Complexity:
The time complexity of the code is O(n * m), where n is the size of vector a and m is the size of vector b. This is because the code uses nested loops to iterate over all possible pairs of numbers from both vectors.
D. Space Complexity:
The space complexity of the code is O(n + m), where n is the size of vector a and m is the size of vector b. This is because the code uses two additional vectors (a and b) to store the input numbers.
Code
#include <iostream>
#include <vector>
#include <cmath>
#include <climits>
using namespace std;
int findFineNumber(int x,vector<int>& a,vector<int>& b) {
int max_diff = INT_MIN; // Initialize the maximum difference with negative infinity
for (int num_a : a) {
for (int num_b : b) {
int diff = abs(num_a - num_b); // Calculate the difference between num_a and num_b
if (diff > max_diff) {
max_diff = diff; // Update the maximum difference if the current difference is greater
}
}
}
return max_diff;
}
int main() {
int n ; cin>>n;
int m ; cin>>m;
vector<int> a(n),b(m);
for(int i =0; i<n; i++){
cin>>a[i];
}
for(int i =0; i<m; i++){
cin>>b[i];
}
int result = findFineNumber(n, a, b);
cout << result <<endl;
return 0;
}
Java
class Main {
public static int findFineNumber(int x, List<Integer> a, List<Integer> b) {
int max_diff = Integer.MIN_VALUE; // Initialize the maximum difference with negative infinity
for (int num_a : a) {
for (int num_b : b) {
int diff = Math.abs(num_a - num_b); // Calculate the difference between num_a and num_b
if (diff > max_diff) {
max_diff = diff; // Update the maximum difference if the current difference is greater
}
}
}
return max_diff;
}8. Mearge and Rearrange
Problem Statement
You are given a function,
char* MergeStrings(char* str1, char* str2);The function accepts strings 'str1' and 'str2' as its arguments, Implement the function to generate a string by iterating through each character of given string.
Assumption: String contain lower case characters only.
Note:
Example:
Input:
str1: are
str2: denimOutput:
aeeimnrdExplaination:
Iterations 1 to n( = 4 )
i = 1 : a _ _ _ _ _ _ d (a<d)
i = 2 : a e _ _ _ _ r d (e<r)
i = 3 : a e e _ _ n r d (e<n)
i = 4 : a e e i m n r dThus, final output = aeeimnrd
The custum input format for the above case:
3
are
5
denim(The first line represents the length of the first string 'str1', the second line represents the first string 'str1', the third line represents length of the second string 'str2', the fourth line represents the second string 'str2')
Sample input
str1: cape
str2: portSample Output
capetropthe custom input format for the above case:
4
cape
4
port(The first line represents the length of the first string 'str1', the second line represents the first string 'str1', the third line represents length of the second string 'str2', the fourth line represents the second string 'str2')
Instructions:
a. Intuition
The function named MergeStrings that takes two string inputs str1 and str2. It merges the strings by interleaving their characters based on a specific condition. Here's an explanation of the code:
b. Approach
Time Complexity
The code has a while loop that iterates until the smaller length between len1 and len2 is reached. This loop has a complexity of O(min(len1, len2)) since it depends on the size of the smaller input string.
The code also has two extend operations that append the remaining characters from the longer string to the merged list. These operations have a complexity of O(max(len1, len2) - min(len1, len2)), which is the difference between the lengths of the two input strings.
Lastly, the join operation at the end has a complexity of O(len(merged)) since it concatenates all the characters in the merged list.
Therefore, the overall time complexity of the code can be expressed as O(max(len1, len2)) since the dominant factor is the length of the longer input string.
Space complexity
The code uses a list merged to store the merged string. The maximum size of this list will be the combined length of the two input strings, i.e., len1 + len2. Hence, the space complexity of the code is O(len1 + len2).
In summary, the time complexity is O(max(len1, len2)) and the space complexity is O(len1 + len2).
Code:
Python
def merge_strings(str1, str2):
if str1 is None and str2 is None:
return None
if str1 is None:
return str2
if str2 is None:
return str1
len1 = len(str1)
len2 = len(str2)
merged = []
i = 0
while i < len1 and i < len2:
if str1[i] < str2[i]:
merged.append(str1[i])
merged.append(str2[i])
else:
merged.append(str2[i])
merged.append(str1[i])
i += 1
if len1 < len2:
merged.extend(str2[i:])
elif len1 > len2:
merged.extend(str1[i:])
return ''.join(merged)
9. Sum of digits
Problem Statement
You are required to implement the following function:
int DifferenceSumOfDigits(int* arr, int n);The function accepts an array 'arr' of 'n' positive integers as its argument. Let's suppose:
f(x) = Sum of digits of an integerYou are required to calculate the value of the following:
F1= [f(arr[0]) + f(arr[1]) + f(arr[2]) + ..........+ f(arr[n-1])] %10
F2 = [(arr[0] + arr[1] + arr[2] + .........+ arr[n-1])] % 10
F = F1 - F2and return the value of F.
Note: n > 0
Example:
Input:
arr: 11 14 16 10 9 8 24 5 4 3
n: 10Output:
-4Explanation:
The value of F1 is (1 + 1) + (1 + 4) + (1 + 6) + (1 + 0) + (9) + (8) + (2 + 4) + (5) + (4) + (3) which is equal to 50 and (50 % 10) is 0 and value of F2 is (11 + 14 + 16 + 10 + 9 + 8 + 24 + 5 + 4 + 3) which is equal to 104 and (104 % 10 ) is 4 , the value of F is (0-4), hence -4 is returned.
The custom input format for the above case:
10
11 14 16 10 9 8 24 5 4 3 (The first line represents 'n', the second line represents the elements of the array 'arr')
Sample input
arr: 16 18 20
n: 3Sample output:
4The custom input format for the above case:
3
16 18 20 (The first line represents 'n', the second line represents the elements of the array 'arr')
Instructions:
a. Intuition:
We calculates the difference between two values, F1 and F2, using a given formula. It involves summing the digits of each element in an array and performing modulo operations to obtain the final difference value.
b. Approach
c. Time and Space Complexity:
Time Complexity:
The time complexity of the sumOfDigits function is O(log10(num)), where num is the input number. The DifferenceSumOfDigits function iterates through each element of the array once, resulting in a time complexity of O(n). Overall, the time complexity is determined by the larger of these two operations, resulting in O(n) in this case.
Space Complexity:
The space complexity is O(1) as the code uses a fixed amount of memory to store variables regardless of the input size. The space required for arr and other local variables is considered constant.
Code:
C++
#include <iostream>
int sumOfDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
int DifferenceSumOfDigits(int arr[], int n) {
int f1 = 0;
int f2 = 0;
for (int i = 0; i < n; i++) {
f1 += sumOfDigits(arr[i]);
f2 += arr[i];
}
int f = (f1%10) - (f2%10);
return f;
}
int main() {
int n;
std::cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
int result = DifferenceSumOfDigits(arr, n);
std::cout << result << std::endl;
return 0;
}
Java
import java.util.Scanner;
public class Main {
public static int sumOfDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
public static int differenceSumOfDigits(int[] arr, int n) {
int f1 = 0;
int f2 = 0;
for (int i = 0; i < n; i++) {
f1 += sumOfDigits(arr[i]);
f2 += arr[i];
}
int f = (f1 % 10) - (f2 % 10);
return f;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int result = differenceSumOfDigits(arr, n);
System.out.println(result);
}
}
10. Small Number Problem
Problem Statement:
Implement the following function:
int * NextSmallerNumber(int a[], int m);The function accepts an integer array 'a' of size m. Replace each number of array with nearest smaller number on its right in the array.
Assumption: All integers are > 0.
Note:
Example:
Input:
a: 3 2 11 7 6 5 6 1 Output:
2 1 7 6 5 1 1 -1Explanation:
Every number is replaced with the 1st smaller number on its right, ('3' -> '2', '2' -> '1', '11' -> '7' , '7' -> '6', '6' ->'5', '5' -> '1', '6' -> '1' and '1' -> '-1'
The custom input format for the above case:
8
3 2 11 7 6 5 6 1(The first line represent 'm', the second line represent the elements of the array 'a')
Sample input
a: 10 5 4 5 3 2 1Sample Output
5 4 3 3 2 1 -1The custom input format for the above case:
7
10 5 4 5 3 2 1(The fisrt line represent 'm', the second line represents the element of the array 'a')
Instructions:
a. Intuition:
The given code aims to find the next smaller element for each element in the given list a and store the results in another list result.
b. Approach
c. Time complexity:
The given code traverses the list a once in reverse order. In each iteration, elements are pushed and popped from the stack. The time complexity of this code is O(N), where N is the number of elements in the list a.
d. Space complexity:
The code uses additional space for the result list and the stack. The space complexity is O(N), where N is the number of elements in the list a.
Code
Java:
import java.util.*;
public class NextSmallerNumber {
public static int[] nextSmallerNumber(int[] a) {
int n = a.length;
int[] result = new int[n];
Arrays.fill(result, -1);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() >= a[i]) {
stack.pop();
}
if (!stack.isEmpty()) {
result[i] = stack.peek();
}
stack.push(a[i]);
}
return result;
}
C++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
vector<int> nextSmallerNumber(vector<int>& a) {
int n = a.size();
vector<int> result(n, -1);
stack<int> stack;
for (int i = n - 1; i >= 0; i--) {
while (!stack.empty() && stack.top() >= a[i]) {
stack.pop();
}
if (!stack.empty()) {
result[i] = stack.top();
}
stack.push(a[i]);
}
return result;
}
int main() {
int n; cin>>n;
vector<int>a(n);
for(int i =0; i<n; i++){
cin>>a[i];
}
vector<int> result = nextSmallerNumber(a);
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}11. Marching People
Problem Statement:
Infinite number of people are crossing a 2-D plane.They march in such a way that each integral x coordinate will have exactly one person who moves along it in positive y direction, starting form(x,0).
You have to implement the following functions:
int MaximumBarrier(int n, int** barrier);The function takes an integer matrix 'barrier' having 'n' rows and '3' columns where n denotes the number of barriers. The ith barrier is defined by (xi, yi,di), which means that the barrier is blocking all the people who want to pass through points lying on line segment connecting(xi,yi) and (xi+di,yi). Once a person encounters a barrier, he stops moving.
Given all the barriers, your task is to find the total number of people who will be blocked at some point in their march.
Assumption:
Notes:
Example:
Input:
n:2
x y d
Barrier 1 : 2 3 3
Barrier 2 : 4 6 4Output:
7Explanation:

1st barrier blocks people of x- coordinates(2,3,4,5), similarly, 2nd barrier blocks people of x-cordinates(4,5,6,7,8), forming a total of '7' blocked people (excluding overlapped values (4,5) for 2nd barrier).
The custom input for the above case:
2
2 3 3
4 6 4 (The first line represents 'n', the next 'n' lines each represent ith barrier.)
Sample input
n: 3
x y d
barrier 1: 1 1 2
barrier 2: 6 5 3
barrier 3: 11 4 4Sample Output
12The custom input format for the above case:
3
1 1 2
6 5 3
11 4 4(The first line represents 'n' , the next 'n' lines each represents i-th barrier.)
Instructions:
a. Intuition:
The code aims to calculate the total number of y-values that are blocked based on the given barriers. It uses an unordered set to keep track of the unique x-coordinates that are blocked.
b. Approach:
c. Time complexity:
The time complexity of the code is O(n * d), where n is the number of barriers and d is the maximum difference between the starting and ending x-coordinates among all barriers. This is because the code iterates through each barrier and performs an operation for each x-coordinate within the range of the barrier.
d. Space complexity:
The space complexity of the code is O(k), where k is the number of unique x-coordinates that are blocked. The code uses an unordered set to store the blocked x-coordinates, and the size of the set represents the number of unique x-coordinates.
Code
Java:
import java.util.HashSet;
import java.util.Set;
public class Main {
public static int MaximumBarrier(int[][] barrier) {
Set<Integer> a = new HashSet<>();
for (int[] i : barrier) {
for (int j = i[0]; j <= i[0] + i[2]; j++) {
if (!a.contains(j)) {
a.add(j);
}
}
}
return a.size();
}
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int MaximumBarrier(vector<vector<int>>& barrier) {
unordered_set<int> a;
for (auto& i : barrier) {
for (int j = i[0]; j <= i[0] + i[2]; j++) {
if (a.find(j) == a.end()) {
a.insert(j);
}
}
}
return a.size();
}
int main( ) {
int n; cin>>n;
vector<vector<int>> barrier = {{2,3,3},{4, 6, 4}};
int result = MaximumBarrier(barrier);
cout << result << endl;
return 0;
}
12. Number of Cards
Problem Statement:
Arrangement of cards used for building pyramids are shown in the followin image:

Figure-1 : Level- 3 Pyramid

Figure -2: Level -2 Pyramid
you are required to implement the following function:
int CardsPyramid(int n);The function accepts an integer 'n' as an argument. The integer 'n' denotes level of pyramid. You are required to calculate the number of cards. required to build a pyramid of level 'n' and return the number of cards % 1000007.
Note:
Assumptions:
The number of cards required to build a pyramid of level 1 are 2
Input:
n: 2Output:
7Explaination:
Cards required to build a pyramid of level 1 are 2, adding 1 more level to the pyramid will require 5 more cards, thus a total of 7 cards are needed to build a pyramid of level 2. Hence 7 % 1000007 is returned.
The custum input format for the above case:
2(The line represent 'n')
Sample input
n: 3Sample Output
15 The custum input format for the above case:
3(The line represent 'n')
Instructions:
a. Intuition:
The code aims to calculate the number of cards required to build a pyramid of a given level 'n'. The pyramid is built by stacking cards in a specific pattern, and the number of cards needed increases with each level.
b. Approach:
The code uses a simple mathematical formula to calculate the number of cards required. It multiplies the level 'n' by a formula (3 * n + 1) / 2, which represents the number of cards needed for a pyramid of that level. It then returns the result modulo 1000007 to ensure the value stays within a specific range.
c. Time complexity:
The time complexity of the code is O(1) because it performs a constant number of mathematical operations to calculate the result based on the given level 'n'.
d. Space complexity:
The space complexity of the code is O(1) because it does not use any additional data structures or allocate memory dynamically. It only uses a few integer variables to store the input and intermediate results.
Code:
Java
import java.util.Scanner;
public class CardsPyramid {
public static int calculateCards(int n) {
if (n == 0) {
return -1;
}
int cards = (n * (3 * n + 1)) / 2;
return cards % 1000007;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int result = calculateCards(n);
System.out.println(result);
}
}
C++
#include<iostream>
using namespace std;
int CardsPyramid(int n){
if(n==0){
return -1;
}
int cards = n*(3* n+1)/2;;
return cards % 1000007;
}
int main(){
int n; cin>>n;
int result = CardsPyramid(n);
cout<<result<<endl;
return 0;
}
13. Ball and Box Problem
Problem Statement
Implement the following function:
int NumberOfBalls(int arr[], int n);The function accepts a non-negative integer array 'arr' of size 'n' as its argument. Every Kth element in the array is the number of balls in the Kth row of a box. Every Kth row of the box needs (K+1)^2 balls, where 0 <= K <= (n-1). Implement the function to find the number of balls required to complete each row of the box and return the total number of balls required.
Assumption: arr[k] <= (k+1)^2
Note:
1. Return -1 if the array is null (or None in the case of Python).
2. Array indexing starts from 0.Example:
Input:
Arr: 1 2 7 13Output:
7Explanation:
Number of balls each row needs Number of balls each row has
1 1
4 2
9 7
16 13
Total number of balls required = 0 + 2 + 2 + 3 = 7. Thus, the output is 7.Custom input format for the above case:
4
1 2 7 13(The first line represents the size of the array, the second line represents the elements of the array)
Sample input:
arr: 0 3 5Sample Output:
6Custom input format for the above case:
3
0 3 5(The first line represents the size of the array, the second line represents the elements of the array)
Instructions:
Intuition:
The code aims to calculate the minimum number of balls needed to complete a set of rows, where each row requires an increasing number of balls. The number of balls needed for a specific row is determined by a mathematical formula. The goal is to calculate the total number of balls needed for all the rows and check if there are enough balls to meet the requirements.
Approach:
The code defines a function NumberOfBalls that takes an integer array arr and an integer n as input. arr represents the number of balls in each row, and n is the size of the array.
Two variables are declared: totalBalls and extraBalls, both of type long long. totalBalls will store the total number of balls required, and extraBalls will keep track of the accumulated balls as we iterate through the rows.
The code uses a for loop to iterate through each row in the array arr.
Inside the loop, the code does the following:
It adds the number of balls in the current row to the extraBalls variable.
It updates the totalBalls variable by adding the value of extraBalls. - This represents the total number of balls required up to the current row.
The code calculates the expected number of balls needed for the current row using the formula (K+1)*(K+2)/2, where K is the current row number (i). This is stored in the expectedBalls variable.
It checks if extraBalls (the actual number of balls) is less than expectedBalls (the expected number of balls for the current row). If this condition is true, it means there are not enough balls to complete the current row, so the function returns -1 to indicate that it's not possible to complete the rows with the given number of balls.
If all rows can be completed with the available balls, the function returns totalBalls, representing the total number of balls required.
Time Complexity:
The time complexity of the code is O(n) because
- it iterates through the array once, where n is the size of the input array arr.
- All other operations inside the loop are constant time.Space Complexity:
The space complexity is O(1) because
- the code uses a constant amount of additional memory regardless of the size of the input.
- The memory usage is mainly for the two variables totalBalls and extraBalls, and
- a few integer variables used for calculations.Code:
#include <iostream>
using namespace std;
long long NumberOfBalls(int arr[], int n) {
long long totalBalls = 0;
long long extraBalls = 0;
for (int i = 0; i < n; i++) {
extraBalls += arr[i]; // Add balls in the current row
totalBalls += extraBalls; // Update the total balls required
// Calculate the expected balls needed for the current row
long long expectedBalls = (1LL * (i + 1) * (i + 2)) / 2;
if (extraBalls < expectedBalls) {
// If we don't have enough balls for the current row, return -1
return -1;
}
}
return totalBalls;
}
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
long long result = NumberOfBalls(arr, n);
cout << result << endl;
return 0;
}14. Maximum revenue garage
Problem Statement
A garage is represented as:
struct Garage
{
int bikes;
int cars;
int trucks;
};Implement the function:
int MaxRevenue(struct Garage garages[], int m);The function accepts an array garages of type Garage, consisting of m elements as its argument. Each element of garages consists of three non-negative integers: bikes, cars, and trucks, referring to the count of bikes, cars, and trucks in a garage, respectively. The cost of servicing a bike, car, and truck are 100, 250, and 500, respectively. Implement the function to calculate revenue generated by each garage and return the maximum revenue generated.
Revenue generated by a garage = (100 * bikes) + (250 * cars) + (500 * trucks)
Note:
1. Computed value lies within the integer range.
2. Return -1 if garages is null (or None in the case of Python).Example:
Input:
Bikes: Cars: Trucks:
Garage 1: 6 8 2
Garage 2: 5 7 8
Garage 3: 14 10 11
Garage 4: 11 13 5Output:
9400Explanation:
The task is to calculate the revenue generated by each garage and return the maximum revenue generated.
Revenue Calculation:
The revenue generated by each garage is calculated using the formula:
Revenue = (100 * Bikes) + (250 * Cars) + (500 * Trucks)Let's calculate the revenue for each garage:
Garage 1:
Revenue = (100 * 6) + (250 * 8) + (500 * 2) = 600 + 2000 + 1000 = 3600
Garage 2:
Revenue = (100 * 5) + (250 * 7) + (500 * 8) = 500 + 1750 + 4000 = 6250
Garage 3:
Revenue = (100 * 14) + (250 * 10) + (500 * 11) = 1400 + 2500 + 5500 = 9400
Garage 4:
Revenue = (100 * 11) + (250 * 13) + (500 * 5) = 1100 + 3250 + 2500 = 6850Among these garages, the one that generates the maximum revenue is Garage 3 with a revenue of 9400.
So, the function should return 9400 as the maximum revenue generated by any of the garages in the input list.
Sample input
4
6 8 2
5 7 8
14 10 11
11 13 5Sample Output
9400Instructions:
Approach:
We define a Garage struct to represent each garage's count of bikes, cars, and trucks.
The MaxRevenue function takes a vector of garages as input and calculates the revenue for each garage using the provided formula.
It keeps track of the maximum revenue found so far.
In the main function, we read the number of garages (m) and create a vector of garages with the specified counts for each type of vehicle.
We call the MaxRevenue function to find the maximum revenue among all the garages and then print the result.
Time Complexity: O(m)
Reading the input data (counts of vehicles for each garage) takes O(m) time, where 'm' is the number of garages.
The MaxRevenue function iterates through each garage once, performing constant-time calculations for each. Therefore, the loop's time complexity is O(m).
Finding the maximum revenue using max also takes O(m) time because we compare each garage's revenue.
Thus, the overall time complexity of the program is O(m).
Space Complexity: O(m)
The space complexity is determined by the memory used to store the vector of garages. Each garage occupies a constant amount of space (3 integers), and there are 'm' garages in total.
Therefore, the space complexity of the program is O(m) due to the storage of input data in the vector.
Other variables used in the program take constant space and do not contribute significantly to the space complexity.
Code:
#include <iostream>
#include <vector>
using namespace std;
struct Garage {
int bikes;
int cars;
int trucks;
};
int MaxRevenue(vector<Garage>& garages, int m) {
int maxRevenue = 0;
for (const Garage& garage : garages) {
int revenue = (100 * garage.bikes) + (250 * garage.cars) + (500 * garage.trucks);
maxRevenue = max(maxRevenue, revenue);
}
return maxRevenue;
}
int main() {
int m;
cin >> m; // Number of garages
vector<Garage> garages(m);
for (int i = 0; i < m; i++) {
cin >> garages[i].bikes >> garages[i].cars >> garages[i].trucks;
}
int result = MaxRevenue(garages, m);
cout << result << endl;
return 0;
}15. Sum of Numbers
Problem Statement
You are required to implement the following function:
int SumPrimeIndices(int *arr, int n);The function accepts an array 'arr' of 'n' integers as its argument. You are required to calculate the sum of numbers at prime indices in the array 'arr' and return the result.
Note:
1. If 'arr' is empty or null (in the case of Python), return -1.
2. 1 is not a prime number.
3. 0-based indexing is used in 'arr'.Example:
Input:
Arr: 10 -12 2 5 3 15 17 21 -3 -4
N: 10Output:
43Explanation:
The numbers in 'arr' at prime indices are (2, 5, 15, 21), and their sum is 43, hence 43 is returned.
The custom input format for the above case:
10
10 -12 2 5 3 15 17 21 -3 -4(The first line represents 'n', and the second line represents the elements of the array 'arr'.)
Sample input:
Arr: -1 2 -3 55 51 34 5 -4 66 8 63 45
N: 12Sample Output:
127The custom input format for the above case:
12
-1 2 -3 55 51 34 5 -4 66 8 63 45(The first line represents 'n', and the second line represents the elements of the array 'arr'.)
Explanation:
The numbers in 'arr' at prime indices are (-3, 55, 34, -4, 45), and their sum is 127, hence 127 is returned.
Instructions:
1. Intuition:
The code aims to find the sum of elements at prime indices in an array. It does so by iterating through the elements, checking if each index is prime, and if so, adding the element at that index to the sum.
2. Approach:
Here's how the code works step by step:
It starts by including the necessary libraries and namespaces (iostream and vector).
The SumPrimeIndices function takes two arguments: a vector of integers Arr and an integer n representing the number of elements in Arr.
It initializes an empty vector Arr2 to store prime indices.
If n is less than or equal to 1, it returns -1 as per the problem statement.
Otherwise, it enters a loop that iterates from 2 to n-1, checking for prime indices:
For each index i, it initializes a boolean variable is_prime as true.
Then, it enters another loop from 2 to i-1 to check for factors. If i is divisible by any number in this range, it sets is_prime to false and breaks out of the loop.
If is_prime is still true after the inner loop, it means i is prime, so it adds i to the Arr2 vector.
After finding all prime indices, it initializes a variable sum1 to store the sum of elements at prime indices.
It enters a loop to calculate the sum:
For each index i in Arr2, it adds Arr[i] to sum1.
Finally, it returns sum1.
In the main function:
3. Time Complexity:
The time complexity of this code is O(n^2) because it uses nested loops. The outer loop runs from 2 to n-1, and for each index i, the inner loop runs from 2 to i-1.
4. Space Complexity:
The space complexity is O(k), where k is the number of prime indices in the range [2, n-1]. In the worst case, all indices in this range are prime, so the space complexity is O(n).
Code
C++ code:
#include <iostream>
#include <vector>
using namespace std;
int SumPrimeIndices(vector<int> Arr, int n) {
vector<int> Arr2;
if (n <= 1) {
return -1;
} else {
for (int i = 2; i < n; i++) {
bool is_prime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
Arr2.push_back(i);
}
}
int sum1 = 0;
for (int i : Arr2) {
sum1 += Arr[i];
}
return sum1;
}
}
int main() {
int n;cin >> n;
vector<int> Arr(n);
for (int i = 0; i < n; i++) {
cin >> Arr[i];
}
cout << SumPrimeIndices(Arr, n) << endl;
return 0;
}
Python code:
def SumPrimeIndices(Arr, n):
Arr2 = []
if n <= 1:
return -1
else:
for i in range(2, n):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
Arr2.append(i)
sum1 = 0
for i in Arr2:
sum1 += Arr[i]
return sum1
def main():
n = int(input())
Arr = list(map(int, input().split()))
result = SumPrimeIndices(Arr, n)
print(result)
if __name__ == "__main__":
main()
16. Decryt the string
Problem Statement
Implement the following function:
char* Decrypt(char str[], int n);The function accepts a string 'str' of size 'n' as its argument. Implement the function to decrypt the given 'str' in such a way that each character of the string is replaced as follows:
('a' -> 'z', 'b' -> 'y', 'c' -> 'x', 'd' -> 'w', 'e' -> 'v', 'f' -> 'u', 'g' -> 't', 'h' -> 's', 'i' -> 'r', 'j' -> 'q', 'k' -> 'p', 'l' -> 'o', 'm' -> 'n', 'n' -> 'm', 'o' -> 'l', 'p' -> 'k', 'q' -> 'j', 'r' -> 'i', 's' -> 'h', 't' -> 'g', 'u' -> 'f', 'v' -> 'e', 'w' -> 'd', 'x' -> 'c', 'y' -> 'b', 'z' -> 'a').
Return the decrypted string.
Assumption:
Note:
Example:
Input:
Str: vmxibkgrlmOutput:
EncryptionExplanation:
The input string is decrypted as follows:
Str Decrypt
V e
M n
X c
I r
B y
K p
G t
R i
L o
M nThus, the output string is 'encryption'.
Custom Input Format for the above case:
10
vmxibkgrlmSample Input:
Str: xovziSample Output:
ClearCustom Input Format for the above case:
5
xovziExplanation:
The input string is decrypted as follows:
Str Decrypt
X C
o l
v e
z a
i rThus, the output string is 'clear'.
Instructions:
1. Intuition:
The code aims to decrypt a given string by replacing each character according to a specified pattern. To achieve this, it creates a mapping for character replacement and then iterates through the input string, updating each character based on the mapping.
2. Approach:
The code begins by creating a mapping for character replacement using an array called mapping. The mapping is constructed such that each character is replaced as follows: 'a' with 'z', 'b' with 'y', 'c' with 'x', and so on.
It then reads the length of the input string (n) and the input string (str) from the standard input.
Next, it checks if the input string is empty or NULL (when n is less than or equal to 0). If the input string is empty or NULL, it prints "NULL" and exits.
If the input string is valid, it proceeds to decrypt the string by iterating through each character.
During the iteration, it checks if the character is a lowercase letter ('a' to 'z'). If it is, it replaces the character with its corresponding decrypted character using the mapping array.
Finally, it prints the decrypted string to the standard output.
3. Time Complexity:
The time complexity of this code is O(n), where n is the length of the input string. This is because it iterates through the input string once, performing constant-time operations for each character.
4. Space Complexity:
The space complexity of this code is O(1) because it uses a fixed-size mapping array of size 26 to store the character replacements. The space required does not depend on the size of the input string, making it constant space.
Code
C++:
#include <iostream>
#include <cstring>
using namespace std;
char* Decrypt(char str[], int n) {
// Create a mapping for character replacement
char mapping[26];
for (int i = 0; i < 26; i++) {
mapping[i] = 'a' + 25 - i;
}
// Iterate through the input string and replace characters
for (int i = 0; i < n; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = mapping[str[i] - 'a'];
}
}
return str;
}
int main() {
int n;
cin >> n;
// Check if the input string is NULL
if (n <= 0) {
cout << "NULL" << endl;
return 0;
}
char str[n];
cin >> str;
char* result = Decrypt(str, n);
cout << result << endl;
return 0;
}IMPORTANT TIPS