Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

TECHNICAL

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

TECHNICAL

Work Assigned By Sree Saran


Date: 20/09/2024 Mukund Kumar

Question 1

How to Attempt?
Conditional Subarrays
You have sorted box of numbers stored in an integer array A and you want to find all the “mini
boxes” (subarrays) that meet a special rule. This rule says that the sum of the smallest and biggest
number in each mini box must be less than or equal to a given number X. Remember the original
box is already sorted, so the smallest number is always at the beginning and the biggest one is at
the end of the mini box you create. Your task is to find and return an integer value representing
the number of mini boxes that can be made which the rule.

Input Specification:
Input1: An integer N, representing size of array
Input2: An integer X, representing the comparison value.
Input3: An integer array A, representing the sorted box of numbers.

Output Specification:
Return an integer value representing the number of mini boxes that can be made which follow the
rule.

Example 1:
Input1: 4
Input2: 5
Input3: [1, 2, 3, 4]
Output: 4

Explanation:
1. Subarrays:
o [1]: The smallest and largest numbers are 1 and 1, and their sum is 1 + 1 = 2 (less
than or equal to 5).
o [1, 2]: The smallest and largest numbers are 1 and 2, and their sum is 1 + 2 = 3
(less than or equal to 5).
o [2]: The smallest and largest numbers are 2 and 2, and their sum is 2 + 2 = 4 (less
than or equal to 5).
o [1, 3]: The sum is 1 + 3 = 4, also valid.
2. Other subarrays like [1, 2, 3] or [3, 4] have sums greater than 5 and should be excluded.

Example 2:
Input1: 4
Input2: 21
Input3: [7, 8, 12, 13]
Output: 7

Explanation:
1. Array: [7, 8, 12, 13]
2. X: 21
We need to find all subarrays where the sum of the smallest and largest numbers in each subarray
is less than or equal to 21.
Let's consider all subarrays:
 Subarray [7]: The sum is 7 + 7 = 14 (less than 21).
 Subarray [7, 8]: The sum is 7 + 8 = 15 (less than 21).
 Subarray [7, 8, 12]: The sum is 7 + 12 = 19 (less than 21).
 Subarray [7, 8, 12, 13]: The sum is 7 + 13 = 20 (less than 21).
 Subarray [8]: The sum is 8 + 8 = 16 (less than 21).
 Subarray [8, 12]: The sum is 8 + 12 = 20 (less than 21).
 Subarray [8, 12, 13]: The sum is 8 + 13 = 21 (equal to 21).
 Subarray [12]: The sum is 12 + 12 = 24 (greater than 21, invalid).
 Subarray [12, 13]: The sum is 12 + 13 = 25 (greater than 21, invalid).
 Subarray [13]: The sum is 13 + 13 = 26 (greater than 21, invalid).

Algorithm: General Approach (Two-Pointer Method)


1. Initialize two pointers: One starting from the left (i = 0) and another (j) moving from i to
the right.
2. For every position i, increment j and check if the sum of A[i] + A[j] is less than or equal to
X.
o If the sum is valid, count all subarrays between i and j.
o If not, move i forward and reset j.
3. Return the total count.

Code: C
#include <stdio.h>

// Function to count valid subarrays


int countSubarrays(int A[], int N, int X) {
int count = 0; // to store the number of valid subarrays
int i = 0, j = N - 1; // two pointers

while (i <= j) {
if (A[i] + A[j] <= X) {
// All subarrays between i and j are valid
count += (j - i + 1);
i++; // move the left pointer forward
} else {
j--; // move the right pointer backward
}
}
return count;
}

int main() {
int N, X; // variables for size of array and comparison value

// Take input for the size of the array


scanf("%d", &N);
int A[N]; // declare the array based on the input size

// Take input for the array elements


for (int i = 0; i < N; i++) {
scanf("%d", &A[i]);
}

// Take input for the comparison value


scanf("%d", &X);

// Call the function and print the result


int result = countSubarrays(A, N, X);
printf("%d\n", result);

return 0;
}

Code: Java
import java.util.Scanner;
import java.util.Arrays;

public class ConditionalSubarrays {

public static int countSubarrays(int[] A, int N, int X) {


int count = 0; // to store the number of valid subarrays
int i = 0, j = N - 1; // two pointers

while (i <= j) {
if (A[i] + A[j] <= X) {
// All subarrays between i and j are valid
count += (j - i + 1);
i++; // move the left pointer forward
} else {
j--; // move the right pointer backward
}
}
return count;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Take input for the size of the array


System.out.print("Enter the size of the array: ");
int N = sc.nextInt();

// Take input for the comparison value X


int X = sc.nextInt();
// Take input for the array elements
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = sc.nextInt();
}

// Ensure the array is sorted (if not already sorted by the user)
Arrays.sort(A);

// Call the function and print the result


int result = countSubarrays(A, N, X);
System.out.println(result);

// Close the scanner


sc.close();
}
}

Code: Python
def count_subarrays(A, N, X):
count = 0 # to store the number of valid subarrays
i=0
j = N - 1 # two pointers

while i <= j:
if A[i] + A[j] <= X:
# All subarrays between i and j are valid
count += (j - i + 1)
i += 1 # move the left pointer forward
else:
j -= 1 # move the right pointer backward

return count

# Taking input from the user


N = int(input("Enter the size of the array: "))
X = int(input("Enter the comparison value (X): "))
A = list(map(int, input("Enter the sorted array elements separated by space: ").split()))

# Ensure the array is sorted


A.sort()

# Call the function and print the result


result = count_subarrays(A, N, X)
print(result)

Question 2

How to Attempt?
Smart Shopping
You are given an array of N elements representing the prices of each item. You are also given a
discount offer that allows you to buy K items at a reduced price. The discount offer works as, for
every most expensive K items you decide to buy, the cost of the maximum priced item out of
those K items will be waived off.

Your task is to find and return an integer value representing the total cost after applying the
maximum discount offer.

Input Specification:
Input1: An integer value N representing the number of items.
Input2: An integer value K, representing the number of items to buy at a reduced price.
Input3: An integer array representing the prices of items.

Output Specification:
Return an integer value representing the total cost achievable using the given maximum discount
offer.

Example 1:
Input1: 5
Input2: 2
Input3: [10, 20, 30, 40, 50]
Output: 100

Explanation:
To maximize the discount, we should pick the K most expensive items in descending order:
 Items sorted: [50, 40, 30, 20, 10]
 Groups of K items: [50, 40] (waive off the most expensive item: 50) and [30, 20] (waive off
the most expensive item: 30)
 Total cost after discounts: 40 + 20 + 10 = 70

Example 2:
Input1: 6
Input2: 3
Input3: [5, 15, 10, 25, 20, 30]
Output: 60

Explanation:
To maximize the discount, we should pick the K most expensive items in descending order:
 Items sorted: [30, 25, 20, 15, 10, 5]
 Groups of K items: [30, 25, 20] (waive off the most expensive item: 30) and [15, 10, 5]
(waive off the most expensive item: 15)
 Total cost after discounts: 25 + 20 + 10 + 5 = 60

Algorithm:
1. Sort the Array: Sort the array of prices in descending order.
2. Calculate Cost:
 Initialize total_cost to 0. Iterate through the sorted list in chunks of size K, and for
each chunk:
 Add the sum of the chunk to total_cost excluding the maximum price of that
chunk.
3. Return the Total Cost: After processing all chunks, return total_cost.

Code Logic Explanation:


1. Sorting: The prices are sorted in descending order to easily pick the most expensive items.
2. Chunk Processing: Iterate over the sorted array in chunks of K, skipping the most
expensive item in each chunk.
3. Total Cost Calculation: The total cost is computed by summing up the items' costs while
excluding the highest-priced item in each chunk.

Code: C
#include <stdio.h>
#include <stdlib.h>

// Comparator function for sorting in descending order


int compare(const void *a, const void *b) {
return (*(int *)b - *(int *)a);
}

int calculateTotalCost(int prices[], int N, int K) {


// Sort the array in descending order
qsort(prices, N, sizeof(int), compare);

int total_cost = 0;
int i = 0;

while (i < N) {
int chunk_end = i + K;
if (chunk_end > N) chunk_end = N; // Ensure we don't go out of bounds

// Add the sum of this chunk, excluding the maximum item


for (int j = i; j < chunk_end; j++) {
if (j == i) {
continue; // Skip the most expensive item
}
total_cost += prices[j];
}

// Move to the next chunk


i += K;
}

return total_cost;
}

int main() {
int N, K;

// Input size of the array


scanf("%d", &N);
// Input number of items to buy at a reduced price
scanf("%d", &K);

int *prices = (int *)malloc(N * sizeof(int));

// Input the prices of items


for (int i = 0; i < N; i++) {
scanf("%d", &prices[i]);
}

// Calculate and print the total cost after applying discounts


int result = calculateTotalCost(prices, N, K);
printf("%d\n", result);

// Free allocated memory


free(prices);

return 0;
}

Code: Java
import java.util.Arrays;
import java.util.Scanner;

public class MaxDiscountOffer {

public static int calculateTotalCost(int[] prices, int N, int K) {


// Sort the array in descending order
Arrays.sort(prices);
int[] sortedPrices = new int[N];
for (int i = 0; i < N; i++) {
sortedPrices[i] = prices[N - 1 - i];
}

int totalCost = 0;
int i = 0;

while (i < N) {
int chunkEnd = i + K;
if (chunkEnd > N) chunkEnd = N; // Ensure we don't go out of bounds

// Add the sum of this chunk, excluding the maximum item


for (int j = i + 1; j < chunkEnd; j++) {
totalCost += sortedPrices[j];
}

// Move to the next chunk


i += K;
}
return totalCost;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input the size of the array


int N = scanner.nextInt();

// Input the number of items to buy at a reduced price


int K = scanner.nextInt();

int[] prices = new int[N];

// Input the prices of items


for (int i = 0; i < N; i++) {
prices[i] = scanner.nextInt();
}

// Calculate and print the total cost after applying discounts


int result = calculateTotalCost(prices, N, K);
System.out.println(result);

// Close the scanner


scanner.close();
}
}

Code: Python
def calculate_total_cost(prices, K):
# Sort the array in descending order
prices.sort(reverse=True)

total_cost = 0
i=0
N = len(prices)

while i < N:
# Calculate the end index of the current chunk
chunk_end = min(i + K, N)

# Add the sum of this chunk, excluding the maximum item (first in the chunk)
for j in range(i + 1, chunk_end):
total_cost += prices[j]

# Move to the next chunk


i += K

return total_cost

def main():
# Take input for the size of the array
N = int(input())

# Take input for the number of items to buy at a reduced price


K = int(input())

# Take input for the array elements


prices = [int(input()) for _ in range(N)]

# Calculate and print the total cost after applying discounts


result = calculate_total_cost(prices, K)
print(result)

if __name__ == "__main__":
main()

Question 3

How to Attempt?
Magical Library
In a magical library, each bookshelf is represented by a two-dimensional array A, where each row
of the 2D array A[i] represents the series value of a book.
A row is considered magical if the sum of the odd values of the series of a book is even. Your task
is to find and return an integer value representing the number of magical rows.

Input Specification:
Input1: An integer value representing the number of rows in the 2D array.
Input2: An integer value representing the number of columns in the 2D array.
Input3: A 2D integer array where each row represents a series of books.

Output Specification:
Return an integer value representing the number of magical rows.

Example 1:
Input1: 3
Input2: 4
Input3: [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
Output: 3

Explanation:
Row 1: [1, 2, 3, 4] → Odd numbers: [1, 3] → Sum = 4 (Even) → Magical row
Row 2: [5, 6, 7, 8] → Odd numbers: [5, 7] → Sum = 12 (Even) → Magical row
Row 3: [9, 10, 11, 12] → Odd numbers: [9, 11] → Sum = 20 (Even) → Magical row
Output: 3 magical rows
Example 2:
Input1:
Input2:
Input3:
Output: 7

Explanation:

Algorithm Count Magical Rows:


1. Input:
o Read two integers m (number of rows) and n (number of columns).
o Read a 2D array arr[m][n] representing the series of books.
2. Initialize Variables:
o Initialize magicalRows = 0 to keep track of the count of magical rows.
3. Iterate Through Each Row:
o For each row i from 0 to m-1:
 Initialize oddSum = 0 to store the sum of odd numbers in the current row.
4. Iterate Through Each Element of the Row:
o For each column j from 0 to n-1 in row i:
 Check if the element arr[i][j] is odd (i.e., arr[i][j] % 2 != 0).
 If the element is odd, add it to oddSum.
5. Check if the Row is Magical:
o After processing all elements in the current row:
 Check if oddSum % 2 == 0 (i.e., if the sum of odd numbers is even).
 If true, increment magicalRows by 1.
6. Return the Result:
o After processing all rows, return the value of magicalRows.

Code: C
#include <stdio.h>

// Function to count magical rows


int countMagicalRows(int m, int n, int arr[m][n]) {
int magicalRows = 0;

// Traverse through each row


for (int i = 0; i < m; i++) {
int oddSum = 0;

// Check each element in the row


for (int j = 0; j < n; j++) {
if (arr[i][j] % 2 != 0) {
// If the element is odd, add it to the oddSum
oddSum += arr[i][j];
}
}

// Check if the sum of odd numbers is even


if (oddSum % 2 == 0) {
magicalRows++;
}
}

return magicalRows;
}

int main() {
// Input section
int m, n;

// Read the number of rows and columns


scanf("%d", &m);
scanf("%d", &n);

// Declare a 2D array to store the values


int arr[m][n];

// Reading the elements of the 2D array


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &arr[i][j]);
}
}

// Function call to count magical rows


int result = countMagicalRows(m, n, arr);

// Output the result


printf("%d\n", result);

return 0;
}

Code: Java
import java.util.Scanner;

public class MagicalLibrary {

// Function to count magical rows


public static int countMagicalRows(int[][] arr, int m, int n) {
int magicalRows = 0;

// Traverse each row


for (int i = 0; i < m; i++) {
int oddSum = 0;

// Traverse each element in the row


for (int j = 0; j < n; j++) {
if (arr[i][j] % 2 != 0) {
// Add to oddSum if the element is odd
oddSum += arr[i][j];
}
}

// Check if the sum of odd numbers is even


if (oddSum % 2 == 0) {
magicalRows++;
}
}

return magicalRows;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input number of rows and columns


int m = sc.nextInt();
int n = sc.nextInt();

// Declare a 2D array
int[][] arr = new int[m][n];

// Input the elements of the 2D array


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
}
}

// Call function to count magical rows


int result = countMagicalRows(arr, m, n);

// Output the result


System.out.println(result);

sc.close();
}
}

Code: Python
def count_magical_rows(arr, m, n):
magical_rows = 0

# Traverse each row


for i in range(m):
odd_sum = 0

# Traverse each element in the row


for j in range(n):
if arr[i][j] % 2 != 0:
# Add to odd_sum if the element is odd
odd_sum += arr[i][j]

# Check if the sum of odd numbers is even


if odd_sum % 2 == 0:
magical_rows += 1

return magical_rows

# Main function to take user input


def main():
# Input number of rows and columns
m = int(input())
n = int(input())

# Declare a 2D list to store the values


arr = []

# Input the elements of the 2D list


for i in range(m):
row = list(map(int, input().split())) # Input a row as a list of integers
arr.append(row)

# Call the function to count magical rows


result = count_magical_rows(arr, m, n)

# Output the result


print(result)

# Call the main function


if __name__ == "__main__":
main()

Question 4

How to Attempt?
Palindromic String Count
Jack broke a toy which consisted of a string A. The toy was broken in such a way that some letters
were still present and some lost. Jack decided to replace the missing letters with ‘?’. He can
generate palindromic string by replacing ‘?’ with any letter from ‘a’ to ‘z’. Jack has a favourite
number M. You task is to find and return an integer value representing the total number of
palindromic strings modulo M that he can generate by replacing ‘?’ with any letter from ‘a’ to ‘z’.

Note: String S contains lowercase alphabets only

Input Specification:
Input1: An integer value M
Input2: An string S representing a word with missing characters.

Output Specification:
Return an integer value representing the total number of palindromic words Jack can form after
performing modulo with a given integer M.

Example 1:
Input1: 3
Input2: ca?d

Output: 3

Explanation:
Here the given string is ca?d and M is S. If we replace ‘?’ with ‘a’ then the string becomes “caad”
which is not a palindrome. It will never be a palindrome even if we replace ‘?’ with any letter
between a to z. Therefore 0 is returned as the output.

Example 2:
Input1: 7
Input2: a?ba?
Output: 26

Explanation:
All 26 alphabetical inputs between ‘a’ to ‘z’ can make given string ‘a?ba?’ palindrom.

Algorithm:
1. Initialize count = 1 to keep track of the number of valid palindrome combinations.
2. Iterate through the first half of the string (since the second half is its mirror image).
Let i be the index from 0 to n // 2 - 1.
For each character pair (S[i], S[n-i-1]):
 If both are ?, multiply count by 26 because there are 26 possibilities to make this
pair.
 If one is ? and the other is a letter, there is only 1 way to match them, so count
remains unchanged.
 If both are letters but not equal, a palindrome is impossible, return 0.
3. After completing the loop, return count % M.

Time Complexity:
 O(n/2) → Simplifies to O(n) where n is the length of the string, as we only traverse half the
string to check for palindrome formation.
Space Complexity:
 O(1) → We use a constant amount of space aside from the input string.
This algorithm efficiently calculates the number of valid palindromic strings Jack can generate,
modulo M.

Code: C
#include <stdio.h>
#include <string.h>

int countPalindromicStrings(int M, char S[]) {


int n = strlen(S);
int count = 1; // Initialize the count of possible palindromic strings
// Traverse only the first half of the string
for (int i = 0; i < n / 2; i++) {
char left = S[i];
char right = S[n - i - 1];

// Both are '?'


if (left == '?' && right == '?') {
count = (count * 26) % M;
}
// One is '?' and the other is a character
else if (left == '?' || right == '?') {
// Do nothing, as only one choice matches the other character
continue;
}
// Both are characters but not equal
else if (left != right) {
return 0; // No palindrome can be formed
}
}

// If the string length is odd, handle the middle character


if (n % 2 == 1 && S[n / 2] == '?') {
count = (count * 26) % M;
}

return count;
}

int main() {
int M;
char S[100];

// Taking user input


scanf("%d", &M);

scanf("%s", S);

// Calling the function and printing the result


int result = countPalindromicStrings(M, S);
printf("%d\n", result);

return 0;
}

Code: Java
import java.util.Scanner;

public class PalindromicStringCount {

public static int countPalindromicStrings(int M, String S) {


int n = S.length();
int count = 1; // Initialize the count of possible palindromic strings

// Traverse only the first half of the string


for (int i = 0; i < n / 2; i++) {
char left = S.charAt(i);
char right = S.charAt(n - i - 1);

// Both are '?'


if (left == '?' && right == '?') {
count = (count * 26) % M;
}
// One is '?' and the other is a character
else if (left == '?' || right == '?') {
// Do nothing, as only one choice matches the other character
continue;
}
// Both are characters but not equal
else if (left != right) {
return 0; // No palindrome can be formed
}
}

// If the string length is odd, handle the middle character


if (n % 2 == 1 && S.charAt(n / 2) == '?') {
count = (count * 26) % M;
}

return count;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Taking user input


int M = scanner.nextInt();
scanner.nextLine(); // Consume newline

String S = scanner.nextLine();

// Calling the function and printing the result


int result = countPalindromicStrings(M, S);
System.out.println(result);

scanner.close();
}
}

Code: Python
def count_palindromic_strings(M, S):
n = len(S)
count = 1 # Initialize the count of possible palindromic strings
# Traverse only the first half of the string
for i in range(n // 2):
left = S[i]
right = S[n - i - 1]

# Both are '?'


if left == '?' and right == '?':
count = (count * 26) % M

# One is '?' and the other is a character


elif left == '?' or right == '?':
# Do nothing, as only one choice matches the other character
continue

# Both are characters but not equal


elif left != right:
return 0 # No palindrome can be formed

# If the string length is odd, handle the middle character


if n % 2 == 1 and S[n // 2] == '?':
count = (count * 26) % M

return count

# Taking user input


M = int(input())
S = input()

# Calling the function with user input and printing the result
result = count_palindromic_strings(M, S)
print(result)

Remaining Questions are given below (Not Done due to income screenshots or improper visibility)
Independence Day Parade
Color Changing Box
Animal Chart
Knowledge Enhancement
The Distance
Alex Loves Chocolate
Finding String Weight – (A-z)
Mango Distribution
A Gardener is Tasked with Watering
Cryptographer
String Swap
Generated Numbers

You might also like