You are on page 1of 15

//1-bitwise and

// Function to count the number of unordered pairs of elements in arr such that
their bitwise AND is a power of 2
#include <stdio.h>

// Function to count the number of unordered pairs of elements in arr such that
their bitwise AND is a power of 2
int bitwiseAnd(int arr_count,int* arr)
{
int no_bwand_pwr2=0;
int i=0,j=0;
for(i=0;i<arr_count;i++)
{
for(j=0;j<arr_count-i-1;j++)
{
int bwand_value = arr[i]&arr[j+i+1];
if(bwand_value >0)
{
if((bwand_value &(bwand_value-1))==0)
{
no_bwand_pwr2+=1;
}
}
}
}
return no_bwand_pwr2;
}
int main() {
// Sample Case 1
int arr1[] = {10,7,2,8,3};
int arr_count1 = 5;
printf("Sample Output 1: %ld\n", bitwiseAnd(arr_count1, arr1));

return 0;
}

/
***********************************************************************************
*********************/
//2-equalizing array
#include <stdio.h>
#include <stdlib.h> // For qsort function
#include <limits.h> // For INT_MAX constant

// Function to compare two integers for qsort

#define MAX_INT 200000


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

int mino(int arr_count, int* arr, int threshold, int divider)


{
int dp[MAX_INT][2] = {0};
int minO = MAX_INT;
qsort(arr,arr_count,sizeof(int),des);

for(int i=0;i<arr_count;i++)
{
int steps = 0;
while(1)
{
int element_value = arr[i];
dp[element_value][0]+=1;
dp[element_value][1]+=steps;

if(dp[element_value][0] >= threshold)


{
minO = (minO <= dp[element_value][1])? minO :
dp[element_value][1];
}
if(element_value==0)
{
break;
}
arr[i] /= divider;
steps += 1;
}
}
return minO;
}

int main() {
// Sample Input 1
int arr1[] = {64, 30, 25, 33};
int arr_count1 = 4;
int threshold1 = 2;
int d1 = 2;
printf("Sample Output 1: %d\n", mino(arr_count1, arr1, threshold1, d1));

// Sample Input 2
int arr2[] = {1, 2, 3, 4 ,5};
int arr_count2 = 5;
int threshold2 = 3;
int d2 = 2;
printf("Sample Output 2: %d\n", mino(arr_count2, arr2, threshold2, d2));

return 0;
}

/
***********************************************************************************
*********************/
//3- file renaming

#include <stdio.h>
#include <string.h>

#define MOD 1000000007


long temp_arr[1000000]; // Array to store temporary values during dynamic
programming
long occ_arr[1000000]; // Array to store occurrences at each step

// Function to calculate the number of ways to create a new file name by removing
characters
int renameFile(char* newName, char* oldName) {
long new_length = strlen(newName);
long old_length = strlen(oldName);

// Initialize the temporary array with all elements set to 1


for (long z = 0; z < old_length + 1; z++) {
temp_arr[z] = 1;
}

// Iterate over each character in the new file name


for (long i = 1; i < new_length + 1; i++) {
// Initialize the occurrence array with all elements set to 0 for each
character in the new name
for (long z = 0; z < old_length + 1; z++) {
occ_arr[z] = 0;
}

// Iterate over each character in the old file name


for (long j = i; j < old_length + 1; j++) {
// Update the occurrence array for the current character position,
considering the case when the current character in the new name is not matched with
the current character in the old name
occ_arr[j] = occ_arr[j - 1];

// If the current characters in both names are equal, update the


occurrence array
if (newName[i - 1] == oldName[j - 1])
occ_arr[j] += temp_arr[j - 1];
}

// Update the temporary array with the values from the occurrence array
for (long z = 0; z < old_length + 1; z++) {
temp_arr[z] = occ_arr[z];
}
}

// Return the final result modulo MOD


return occ_arr[old_length] % MOD;
}

int main() {
// Test Case
char newName[] = "aba";
char oldName[] = "ababa";

// Get the result from the function and print it


int result = renameFile(newName, oldName);
printf("Number of ways to create the new file name: %d\n", result);

return 0;
}
/
***********************************************************************************
*********************/
//4-hotel construction

#include <stdio.h>

#define MAX_CITIES_CNT (50)

// Function to initialize distances between cities recursively


void initDistance(int distance[MAX_CITIES_CNT][MAX_CITIES_CNT], int src, int des,
int val, int citiesCnt, char isThereRoad[MAX_CITIES_CNT][MAX_CITIES_CNT]) {
// Set the distance value between src city and des city
distance[src][des] = val;

// Iterate through possible next destinations


for (int nextDes = 0; nextDes < citiesCnt; nextDes++) {
// Check if there is a road to the next destination and the distance is
uninitialized
if (isThereRoad[des][nextDes] && distance[src][nextDes] == -1) {
// Recursively initialize distances
initDistance(distance, src, nextDes, val + 1, citiesCnt, isThereRoad);
}
}
}

// Function to calculate the number of ways to build exactly 3 hotels with equal
distances
int numberOfWays(int roads_rows, int roads_columns, int** roads) {
int citiesCnt = roads_rows + 1;

char isThereRoad[MAX_CITIES_CNT][MAX_CITIES_CNT] = {0};

// Marking the roads between cities


for (int i = 0; i < roads_rows; i++) {
int city1 = roads[i][0] - 1;
int city2 = roads[i][1] - 1;

// Mark the bidirectional road connections


isThereRoad[city1][city2] = 1;
isThereRoad[city2][city1] = 1;
}

int distance[MAX_CITIES_CNT][MAX_CITIES_CNT];

// Set all distances to -1 (uninitialized)


for (int src = 0; src < citiesCnt; src++) {
for (int des = 0; des < citiesCnt; des++) {
distance[src][des] = -1;
}
}

// Initialize distances
for (int src = 0; src < citiesCnt; src++) {
// Distance from src city to itself = 0
initDistance(distance, src, src, 0, citiesCnt, isThereRoad);
}

// Count the number of ways to build exactly 3 hotels with equal distances
int cnt = 0;

for (int city1 = 0; city1 < citiesCnt; city1++) {


for (int city2 = city1 + 1; city2 < citiesCnt; city2++) {
for (int city3 = city2 + 1; city3 < citiesCnt; city3++) {
// Check if distances between all pairs of selected cities are
equal
if (distance[city1][city2] == distance[city1][city3] &&
distance[city1][city2] == distance[city2][city3])
cnt++;
}
}
}

return cnt;
}

int main() {
// Test Case
int roads_rows = 4;
int roads_columns = 2;
int roads_arr[][2] = {{1, 2}, {1, 3}, {1, 4}, {1, 5}};

int* roads[roads_rows];
for (int i = 0; i < roads_rows; i++) {
roads[i] = roads_arr[i];
}

int result = numberOfWays(roads_rows, roads_columns, roads);


printf("Number of ways to build exactly 3 hotels: %d\n", result);

return 0;
}

/
***********************************************************************************
*********************/
//5-largest area

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX(a, b) ((a) > (b) ? (a) : (b))

// Function to compare two integers for qsort


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

// Global variables to store maximum horizontal and vertical sizes


long maxH, maxV, boundry;

// Function to calculate the maximum area after adding a boundary


long maxArea(int w, int h, int* horizontalCuts, int horizontalCutsSize, int*
verticalCuts, int verticalCutsSize) {
if (boundry == 0) {
// Calculate the maximum horizontal size
maxH = MAX(horizontalCuts[0], h - horizontalCuts[horizontalCutsSize - 1]);

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


maxH = MAX(maxH, horizontalCuts[i] - horizontalCuts[i - 1]);
}
} else if (boundry == 1) {
// Calculate the maximum vertical size
maxV = MAX(verticalCuts[0], w - verticalCuts[verticalCutsSize - 1]);

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


maxV = MAX(maxV, verticalCuts[i] - verticalCuts[i - 1]);
}
}

// Return the maximum area after adding the boundary


return maxH * maxV;
}

// Function to get the maximum areas after adding each boundary


long* getMaxArea(int w, int h, int isVertical_count, bool* isVertical, int
distance_count, int* distance, int* result_count) {
maxH = h;
maxV = w;

*result_count = isVertical_count;

// Allocate memory for the result array


long* result = (long*)malloc(isVertical_count * sizeof(long));

// Boundry counters
int horizontalCutsSize = 0;
int verticalCutsSize = 0;

// Arrays to store horizontal and vertical cuts


int* horizontalCuts = (int*)malloc(isVertical_count * sizeof(int));
int* verticalCuts = (int*)malloc(isVertical_count * sizeof(int));

// Iterate through each boundary


for (int i = 0; i < isVertical_count; i++) {
// Horizontal Boundary
if (isVertical[i] == 0) {
boundry = 0;
horizontalCuts[horizontalCutsSize] = distance[i];
horizontalCutsSize++;
qsort(horizontalCuts, horizontalCutsSize, sizeof(int), cmp);
}
// Vertical Boundary
else if (isVertical[i] == 1) {
boundry = 1;
verticalCuts[verticalCutsSize] = distance[i];
verticalCutsSize++;
qsort(verticalCuts, verticalCutsSize, sizeof(int), cmp);
}

// Calculate the maximum area after adding the current boundary


result[i] = maxArea(w, h, horizontalCuts, horizontalCutsSize, verticalCuts,
verticalCutsSize);
}
// Free allocated memory for cuts arrays
free(horizontalCuts);
free(verticalCuts);

// Return the result array


return result;
}

int main() {
// Test Case
int w = 4;
int h = 4;
int isVertical_count = 2;
bool isVertical[] = {0, 1};
int distance_count = 2;
int distance[] = {3, 1};
int result_count;

// Get the maximum areas after adding each boundary


long* result = getMaxArea(w, h, isVertical_count, isVertical, distance_count,
distance, &result_count);

// Print the result array


printf("Result: [");
for (int i = 0; i < result_count; i++) {
printf("%ld", result[i]);
if (i < result_count - 1) {
printf(", ");
}
}
printf("]\n");

// Free allocated memory for the result array


free(result);

return 0;
}

/
***********************************************************************************
*********************/
//6-maximizing element
#include <stdio.h>

// Function to find the maximum value at index k in the array


int maxElement(int n, int maxSum, int k)
{
// Base case: If there is only one element in the array, return maxSum
if (n == 1) {
return maxSum;
}

// Initialization
int right = k; // Right pointer starting at index k
int left = k; // Left pointer starting at index k
int count = 1; // Counter for the number of steps taken
int limitRight = n - 1; // Maximum valid index in the array
// Explore elements on both sides until the sum exceeds maxSum or no more
elements to explore
while (n <= maxSum && (left > 0 || right < limitRight)) {
// Increment n by the difference between right and left plus 1
n = n + (right - left + 1);

// Decrement left if it is greater than 0


if (left > 0) {
left--;
}

// Increment right if it is less than limitRight


if (right < limitRight) {
right++;
}

// Increment the step count


count++;
}

// If n is still less than maxSum, adjust count by adding the remaining


difference divided by the range plus 1
if (n < maxSum) {
count += (maxSum - n) / (right - left + 1) + 1;
}

// Return the final result (count - 1)


return count - 1;
}

int main() {
// Sample Input 1
int n1 = 3, maxSum1 = 7, k1 = 1;
printf("Sample Output 1: %d\n", maxElement(n1, maxSum1, k1));

// Sample Input 2
int n2 = 4, maxSum2 = 6, k2 = 2;
printf("Sample Output 2: %d\n", maxElement(n2, maxSum2, k2));

return 0;
}

/
***********************************************************************************
*********************/

//7-maximum subarray value


#include <stdio.h>

// Macros for maximum and minimum of two values


#define max(a,b) ((a) > (b) ? (a) : (b))
#define min(a,b) ((a) < (b) ? (a) : (b))

// Function to find the maximum subarray value among its subarrays


long maxSubarrayValue(int n, int* arr)
{
// Variable to store the maximum subarray value
long MAX = 0;
// Negate odd indexed elements in the array
for(int i = 1; i < n; i += 2)
{
arr[i] = 0 - arr[i];
}

// Variables to track maximum and minimum values during iteration


long maxSoFar = arr[0];
long currMax = arr[0];
long currMin = arr[0];
long minSoFar = arr[0];

// Iterate through the array starting from the second element


for (int i = 1; i < n; i++)
{
// Calculate the maximum subarray sum using Kadane's algorithm
currMax = max(arr[i], currMax + arr[i]);
maxSoFar = max(maxSoFar, currMax);

// Update the minimum subarray sum


if (currMin > 0)
currMin = arr[i];
else
currMin += arr[i];

// Update the minimum subarray sum so far


minSoFar = min(minSoFar, currMin);
}

// Calculate the maximum subarray value and square it


MAX = abs(maxSoFar) > abs(minSoFar) ? abs(maxSoFar) : abs(minSoFar);

return MAX * MAX;


}

// Function declaration
long maxSubarrayValue(int n, int* arr);

int main() {
// Test Case 1
int arr1[] = {-1, -4, 2};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
long result1 = maxSubarrayValue(n1, arr1);
printf("Test Case 1: %ld\n", result1);

// Test Case 2
int arr2[] = {2, -1, -4, 5};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
long result2 = maxSubarrayValue(n2, arr2);
printf("Test Case 2: %ld\n", result2);

return 0;
}

/
***********************************************************************************
*********************/
//8-nice teams

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Function to compare integers for qsort


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

// Function to calculate the maximum number of pairs


int maxPairs(int skillLevel_count, int* skillLevel, int minDiff) {
// Sort the skill levels in ascending order
qsort(skillLevel, skillLevel_count, sizeof(int), cmpfunc);

int l = 0;
int r = skillLevel_count / 2 + 1;

// Binary search to find the maximum number of pairs


while (r - l > 1) {
int m = (l + r) / 2;
bool good = true;

// Check if pairs can be formed with the minimum difference


for (int i = 0; i < m; i++)
good &= (skillLevel[skillLevel_count - m + i] - skillLevel[i] >=
minDiff);

if (good)
l = m;
else
r = m;
}

return l; // Return the maximum number of pairs


}

int main() {
// Test Case
int skillLevel[] = {1, 2, 3, 4, 5, 6};
int skillLevel_count = sizeof(skillLevel) / sizeof(skillLevel[0]);
int minDiff = 4;

// Call the function to get the result


int result = maxPairs(skillLevel_count, skillLevel, minDiff);

// Print the result


printf("Maximum number of pairs: %d\n", result);

return 0;
}

/
***********************************************************************************
*********************/
//9. Sorted Sums

#include <stdio.h>

// Function to swap two elements


void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// Function to calculate the sorted sum modulo (10^9 + 7)


int sortedSum(int a_count, int* a) {
long long ans = 0, M = 1000000007; // Use long long to prevent overflow, M is
modulo constant

// Iterate through the array and sort it using insertion sort


for (int i = 0; i < a_count; i++) {
int j = i;
// Move elements to their correct positions
while (j > 0 && a[j - 1] > a[j]) {
swap(&a[j], &a[j - 1]);
j--;
}

// Calculate the sorted sum for the current state of the array
for (int k = 0; k <= i; k++) {
ans = (ans + a[k] * 1LL * (k + 1)) % M; // Multiply with position (k +
1) and accumulate
}
ans %= M; // Take modulo to prevent overflow
}

return ans;
}

int main() {
// Sample Input 1
int a1[] = {3, 9, 5, 8};
int a_count1 = 4;
printf("Sample Output 1: %d\n", sortedSum(a_count1, a1));

// Sample Input 2
int a2[] = {5, 9};
int a_count2 = 2;
printf("Sample Output 2: %d\n", sortedSum(a_count2, a2));

return 0;
}

/
***********************************************************************************
*********************/
//10-nice teams
#include <stdio.h>

// Function to determine the maximum number of pairs that can be made from the
given supply of weights
int taskOfPairing(int freq_size, int* freq) {
int pairsCnt = 0; // Counter to track the number of pairs formed
int prevRemainder = 0; // Variable to store the remainder from the previous
iteration

// Iterate through the frequency array


for (int i = 0; i < freq_size; i++) {
// If there are no dumbbells of the current weight, reset the remainder and
continue to the next iteration
if (freq[i] == 0) {
prevRemainder = 0;
continue;
}

// Add the previous remainder to the current frequency


freq[i] += prevRemainder;

// Update the pairs count based on the number of pairs formed with the
current frequency
pairsCnt += freq[i] / 2;

// Update the previous remainder for the next iteration


prevRemainder = freq[i] % 2;
}

// Return the total number of pairs formed


return pairsCnt;
}

int main() {
// Test Case
int freq_size = 4; // Number of different weights
int freq[] = {2, 4, 3, 1}; // Frequency array representing the number of
dumbbells for each weight

// Get the result from the function


int result = taskOfPairing(freq_size, freq);

// Print the result


printf("Maximum number of pairs: %d\n", result);

return 0;
}

/
***********************************************************************************
*********************/
//11-user friendly password system
#include <stdio.h>
#include <stdlib.h>

#define P (131)
#define MOD (1000000007)

// Function to set the password and calculate its hash


int setPassword(char* password) {
long res = 0;
// Calculate the hash using the given formula
for (int i = 0; password[i]; i++) {
res *= P;
res %= MOD;
res += password[i];
res %= MOD;
}

return res;
}

// Function to authorize based on the correct hash and input hash


int authorize(long correctHash, long inputHash) {
// If the input hash matches the correct hash, return 1 (authorization success)
if (correctHash == inputHash)
return 1;

correctHash *= P;
correctHash %= MOD;

// Try adding digits


for (int i = '0'; i <= '9'; i++) {
if ((correctHash + i) % MOD == inputHash)
return 1;
}

// Try adding lower characters


for (int i = 'a'; i <= 'z'; i++) {
if ((correctHash + i) % MOD == inputHash)
return 1;
}

// Try adding upper characters


for (int i = 'A'; i <= 'Z'; i++) {
if ((correctHash + i) % MOD == inputHash)
return 1;
}

// If no match is found, return 0 (authorization failure)


return 0;
}

// Function to process events and perform authorization


int *authEvents(int events_rows, int events_columns, char ***events, int
*result_count) {
// Initialize the result array to store the authorization outcomes
int *res = malloc(events_rows * sizeof(int));
int resIdx = 0; // Index to track the current position in the result array
int currHash; // Variable to store the current password hash

// Process each event


for (int i = 0; i < events_rows; i++) {
switch (events[i][0][0]) {
case 's':
// If the event is to set the password, calculate its hash
currHash = setPassword(events[i][1]);
break;

case 'a':
// If the event is to authorize, perform authorization and store
the result
res[resIdx] = authorize(currHash, atoi(events[i][1]));
resIdx++;
break;
}
}

// Update the result count and return the result array


*result_count = resIdx;
return res;
}

int main() {
// Test Case
char ***events;
int result_count;

// Set the events array based on the given test case


int events_rows = 4;
int events_columns = 2;
char *setPasswordEvent[] = {"setPassword", "000A"};
char *authorizeEvent1[] = {"authorize", "108738450"};
char *authorizeEvent2[] = {"authorize", "108738449"};
char *authorizeEvent3[] = {"authorize", "244736787"};

events = (char ***)malloc(events_rows * sizeof(char **));


for (int i = 0; i < events_rows; i++) {
events[i] = (char **)malloc(events_columns * sizeof(char *));
}

events[0] = setPasswordEvent;
events[1] = authorizeEvent1;
events[2] = authorizeEvent2;
events[3] = authorizeEvent3;

// Call the authEvents function to perform authorization


int *result = authEvents(events_rows, events_columns, events, &result_count);

// Print the results


for (int i = 0; i < result_count; i++) {
printf("%d\n", result[i]);
}

// Free allocated memory


free(result);
for (int i = 0; i < events_rows; i++) {
free(events[i]);
}
free(events);

return 0;
}

/
***********************************************************************************
*********************/

You might also like