0% found this document useful (0 votes)
117 views27 pages

TCS CodeVita Actual Questions Answers

Uploaded by

parv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views27 pages

TCS CodeVita Actual Questions Answers

Uploaded by

parv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

TCS CodeVita Actual

Questions & Answers

1. BestBubble

TCS CodeVita Actual Questions & Answers 1


Python

def mac(arr, temp_arr, left, right):


if left == right:
return 0

mid = (left + right) // 2


inv_c = 0

inv_c += mac(arr, temp_arr, left, mid)


inv_c += mac(arr, temp_arr, mid + 1, right)

inv_c += merge(arr, temp_arr, left, mid, right)

return inv_c

def merge(arr, temp_arr, left, mid, right):


i = left
j = mid + 1
k = left
inv_c = 0

while i <= mid and j <= right:


if arr[i] <= arr[j]:

TCS CodeVita Actual Questions & Answers 2


temp_arr[k] = arr[i]
i += 1
else:
temp_arr[k] = arr[j]
inv_c += (mid - i + 1)
j += 1
k += 1

while i <= mid:


temp_arr[k] = arr[i]
i += 1
k += 1

while j <= right:


temp_arr[k] = arr[j]
j += 1
k += 1

for i in range(left, right + 1):


arr[i] = temp_arr[i]

return inv_c

def count_swaps(arr, asc=True):


n = len(arr)
temp_arr = [0] * n

if asc:
return mac(arr, temp_arr, 0, n - 1)
else:
arr = arr[::-1]
return mac(arr, temp_arr, 0, n - 1)

n = int(input())

TCS CodeVita Actual Questions & Answers 3


arr = list(map(int, input().split()))

asc_swaps = count_swaps(arr.copy(), asc=True)


desc_swaps = count_swaps(arr.copy(), asc=False)

print(min(asc_swaps, desc_swaps), end="")

Java

import java.util.Scanner;

public class Main {

static int mac(int[] arr, int[] temp_arr, int left, int ri


if (left == right)
return 0;

int mid = (left + right) / 2;


int inv_c = 0;

inv_c += mac(arr, temp_arr, left, mid);


inv_c += mac(arr, temp_arr, mid + 1, right);
inv_c += merge(arr, temp_arr, left, mid, right);

return inv_c;
}

static int merge(int[] arr, int[] temp_arr, int left, int


int i = left;
int j = mid + 1;
int k = left;
int inv_c = 0;

while (i <= mid && j <= right) {


if (arr[i] <= arr[j]) {
temp_arr[k] = arr[i];
i++;

TCS CodeVita Actual Questions & Answers 4


} else {
temp_arr[k] = arr[j];
inv_c += (mid - i + 1);
j++;
}
k++;
}

while (i <= mid) {


temp_arr[k] = arr[i];
i++;
k++;
}

while (j <= right) {


temp_arr[k] = arr[j];
j++;
k++;
}

for (i = left; i <= right; i++) {


arr[i] = temp_arr[i];
}

return inv_c;
}

static int count_swaps(int[] arr, boolean asc) {


int n = arr.length;
int[] temp_arr = new int[n];

if (asc) {
return mac(arr, temp_arr, 0, n - 1);
} else {
reverseArray(arr);
return mac(arr, temp_arr, 0, n - 1);
}
}

TCS CodeVita Actual Questions & Answers 5


static void reverseArray(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];

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


arr[i] = sc.nextInt();
}

int asc_swaps = count_swaps(arr.clone(), true);


int desc_swaps = count_swaps(arr.clone(), false);

System.out.print(Math.min(asc_swaps, desc_swaps));
sc.close();
}
}

2. GoodString

TCS CodeVita Actual Questions & Answers 6


TCS CodeVita Actual Questions & Answers 7
Python

import sys
import bisect

def main():
input_lines = sys.stdin.read().split('\n')
if len(input_lines) < 2:
good_string = input_lines[0].strip()
student_name = ''
else:
good_string = input_lines[0].strip()
student_name = input_lines[1].strip()

good_characters = set(good_string)
sorted_ascii_values = sorted(set(ord(c) for c in good_stri

if not good_string:
print(0)
sys.exit()
previous_ascii = ord(good_string[0])

total_distance = 0

TCS CodeVita Actual Questions & Answers 8


for char in student_name:
if char in good_characters:
previous_ascii = ord(char)
continue

target_ascii = ord(char)
position = bisect.bisect_left(sorted_ascii_values, ta

if position == 0:
selected_ascii = sorted_ascii_values[0]
distance = abs(target_ascii - selected_ascii)
elif position == len(sorted_ascii_values):
selected_ascii = sorted_ascii_values[-1]
distance = abs(target_ascii - selected_ascii)
else:
left_ascii = sorted_ascii_values[position - 1]
right_ascii = sorted_ascii_values[position]
left_distance = abs(left_ascii - target_ascii)
right_distance = abs(right_ascii - target_ascii)

if left_distance < right_distance:


selected_ascii = left_ascii
distance = left_distance
elif right_distance < left_distance:
selected_ascii = right_ascii
distance = right_distance
else:
if abs(previous_ascii - left_ascii) < abs(prev
selected_ascii = left_ascii
else:
selected_ascii = right_ascii
distance = abs(previous_ascii - selected_ascii

total_distance += distance
previous_ascii = selected_ascii

print(total_distance, end='')

TCS CodeVita Actual Questions & Answers 9


if __name__ == "__main__":
main()

Java

import java.util.*;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
List<String> inputLines = new ArrayList<>();

while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (!line.isEmpty()) {
inputLines.add(line);
}
}

String goodString = inputLines.size() > 0 ? inputLine


String studentName = inputLines.size() > 1 ? inputLine

Set<Character> goodCharacters = new HashSet<>();


List<Integer> sortedAsciiValues = new ArrayList<>();

for (char c : goodString.toCharArray()) {


goodCharacters.add(c);
sortedAsciiValues.add((int) c);
}

Collections.sort(sortedAsciiValues);

if (goodString.isEmpty()) {
System.out.print(0);
return;
}

TCS CodeVita Actual Questions & Answers 10


int previousAscii = (int) goodString.charAt(0);
int totalDistance = 0;

for (char c : studentName.toCharArray()) {


if (goodCharacters.contains(c)) {
previousAscii = (int) c;
continue;
}

int targetAscii = (int) c;


int position = Collections.binarySearch(sortedAsci
if (position < 0) {
position = -(position + 1);
}

int selectedAscii, distance;


if (position == 0) {
selectedAscii = sortedAsciiValues.get(0);
distance = Math.abs(targetAscii - selectedAsci
} else if (position == sortedAsciiValues.size())
selectedAscii = sortedAsciiValues.get(sortedA
distance = Math.abs(targetAscii - selectedAsci
} else {
int leftAscii = sortedAsciiValues.get(positio
int rightAscii = sortedAsciiValues.get(positio
int leftDistance = Math.abs(leftAscii - targe
int rightDistance = Math.abs(rightAscii - targ

if (leftDistance < rightDistance) {


selectedAscii = leftAscii;
distance = leftDistance;
} else if (rightDistance < leftDistance) {
selectedAscii = rightAscii;
distance = rightDistance;
} else {
if (Math.abs(previousAscii - leftAscii) <
selectedAscii = leftAscii;
} else {

TCS CodeVita Actual Questions & Answers 11


selectedAscii = rightAscii;
}
distance = Math.abs(previousAscii - selec
}
}

totalDistance += distance;
previousAscii = selectedAscii;
}

System.out.print(totalDistance);
}
}

3. Orchard

TCS CodeVita Actual Questions & Answers 12


Python

def count_valid_combinations(trees):
n = len(trees)
count = 0

count_M_before = 0
count_L_before = 0

TCS CodeVita Actual Questions & Answers 13


for i in range(n):
if trees[i] == 'M':

count += count_L_before * (count_L_before - 1) //


count_M_before += 1
elif trees[i] == 'L':

count += count_M_before * (count_M_before - 1) //


count_L_before += 1

count_M_after = 0
count_L_after = 0

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


if trees[i] == 'M':
count += count_L_after * (count_L_after - 1) // 2
count_M_after += 1
elif trees[i] == 'L':
count += count_M_after * (count_M_after - 1) // 2
count_L_after += 1

return count

def find_winner(row_ashok, row_anand):

if not all(c in 'ML' for c in row_ashok) or not all(c in


return "Invalid input"

count_ashok = count_valid_combinations(row_ashok)
count_anand = count_valid_combinations(row_anand)

if count_ashok > count_anand:

TCS CodeVita Actual Questions & Answers 14


return "Ashok"
elif count_anand > count_ashok:
return "Anand"
else:
return "Draw"

ashok_row = input().strip()
anand_row = input().strip()

print(find_winner(ashok_row, anand_row), end = '')

Java

import java.util.Scanner;

public class Main {

public static int countValidCombinations(String trees) {


int n = trees.length();
int count = 0;
int countMBefore = 0;
int countLBefore = 0;

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


if (trees.charAt(i) == 'M') {
count += countLBefore * (countLBefore - 1) / 2
countMBefore++;
} else if (trees.charAt(i) == 'L') {
count += countMBefore * (countMBefore - 1) / 2
countLBefore++;
}
}

int countMAfter = 0;
int countLAfter = 0;

TCS CodeVita Actual Questions & Answers 15


for (int i = n - 1; i >= 0; i--) {
if (trees.charAt(i) == 'M') {
count += countLAfter * (countLAfter - 1) / 2;
countMAfter++;
} else if (trees.charAt(i) == 'L') {
count += countMAfter * (countMAfter - 1) / 2;
countLAfter++;
}
}

return count;
}

public static String findWinner(String rowAshok, String ro


if (!rowAshok.matches("[ML]+") || !rowAnand.matches("
return "Invalid input";
}

int countAshok = countValidCombinations(rowAshok);


int countAnand = countValidCombinations(rowAnand);

if (countAshok > countAnand) {


return "Ashok";
} else if (countAnand > countAshok) {
return "Anand";
} else {
return "Draw";
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
String ashokRow = sc.nextLine().trim();
String anandRow = sc.nextLine().trim();
System.out.print(findWinner(ashokRow, anandRow));
sc.close();
}
}

TCS CodeVita Actual Questions & Answers 16


4. VIPCafe

TCS CodeVita Actual Questions & Answers 17


Python

def VipCafe(arr, pos):


in_index = -1
max_val = -1
n = len(arr)

for i in range(n):
if max_val < arr[i]:
in_index = i
max_val = arr[i]

if in_index == pos:
return 0

arr[in_index] = -1

for i in range(in_index):
if arr[i] > 0:
arr[i] += 1

return 1 + VipCafe(arr, pos)

if __name__ == "__main__":

TCS CodeVita Actual Questions & Answers 18


n = int(input())
arr = list(map(int, input().split()))
k = int(input()) - 1
print(1 + VipCafe(arr, k))

Java

import java.util.*;

public class Main {

public static int VipCafe(List<Integer> arr, int pos) {


int in = -1;
int max = -1;
int n = arr.size();
for (int i = 0; i < n; i++) {
if (max < arr.get(i)) {
in = i;
max = arr.get(i);
}
}
if (in == pos) return 0;
arr.set(in, -1);

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


if (arr.get(i) > 0) arr.set(i, arr.get(i) + 1);
}

return 1 + VipCafe(arr, pos);


}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr.add(sc.nextInt());
}

TCS CodeVita Actual Questions & Answers 19


int k = sc.nextInt();
k--;
System.out.print(1 + VipCafe(arr, k));
sc.close();
}
}

5. WeaponBoxes

TCS CodeVita Actual Questions & Answers 20


Python

import math
from collections import deque

def is_triangle(x):

TCS CodeVita Actual Questions & Answers 21


n = (-1 + math.sqrt(1 + 8 * x)) / 2.0
return n.is_integer()

def calculate_labor_cost(weights, N, K):


queue = deque(weights)
cons_unshifted = 0
curr_max = None
shifted = []

while cons_unshifted < K:

cycle = [queue.popleft() for _ in range(min(N, len(que

while len(cycle) > 1:


a = cycle.pop(0)
b = cycle.pop(0)
if a < b:
shifted.append(a)
queue.append(a)
cycle.insert(0, b)
else:
shifted.append(b)
queue.append(b)
cycle.insert(0, a)

last_box = cycle[0]

if curr_max == last_box:
cons_unshifted += 1
else:
cons_unshifted = 1
curr_max = last_box

TCS CodeVita Actual Questions & Answers 22


queue.appendleft(last_box)

labor_cost = sum(w for w in shifted if not is_triangle(w)


return labor_cost

if __name__ == "__main__":
weights = list(map(int, input().split()))
N, K = map(int, input().split())
result = calculate_labor_cost(weights, N, K)
print(result, end = '')

Java

import java.util.*;
import java.lang.Math;

public class Main {

public static boolean isTriangle(int x) {


double n = (-1 + Math.sqrt(1 + 8 * x)) / 2.0;
return n == (int) n;
}

public static int calculateLaborCost(List<Integer> weight


Deque<Integer> queue = new ArrayDeque<>(weights);
int consUnshifted = 0;
Integer currMax = null;
List<Integer> shifted = new ArrayList<>();

while (consUnshifted < K) {


List<Integer> cycle = new ArrayList<>();
for (int i = 0; i < Math.min(N, queue.size()); i++
cycle.add(queue.pollFirst());
}

while (cycle.size() > 1) {

TCS CodeVita Actual Questions & Answers 23


int a = cycle.remove(0);
int b = cycle.remove(0);
if (a < b) {
shifted.add(a);
queue.addLast(a);
cycle.add(0, b);
} else {
shifted.add(b);
queue.addLast(b);
cycle.add(0, a);
}
}

int lastBox = cycle.get(0);

if (currMax != null && currMax.equals(lastBox)) {


consUnshifted++;
} else {
consUnshifted = 1;
currMax = lastBox;
}

queue.addFirst(lastBox);
}

int laborCost = 0;
for (int w : shifted) {
if (!isTriangle(w)) {
laborCost += w;
}
}
return laborCost;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
List<Integer> weights = new ArrayList<>();
while (sc.hasNextInt()) {

TCS CodeVita Actual Questions & Answers 24


weights.add(sc.nextInt());
}
int N = weights.remove(weights.size() - 2);
int K = weights.remove(weights.size() - 1);

int result = calculateLaborCost(weights, N, K);


System.out.print(result);
sc.close();
}
}

6. ZeroCount

TCS CodeVita Actual Questions & Answers 25


Python

first, sec = map(int, input().split())

if sec == 0:
print(first)
else:
ans = first - sec
result = ans // (sec + 1)
if ans % (sec + 1) != 0:
result += 1
print((result), end = '')

Java

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int first = sc.nextInt();
int sec = sc.nextInt();

if (sec == 0) {
System.out.print(first);

TCS CodeVita Actual Questions & Answers 26


} else {
int ans = first - sec;
int result = ans / (sec + 1);
if (ans % (sec + 1) != 0) {
result += 1;
}
System.out.print(result);
}
sc.close();
}
}

TCS CodeVita Actual Questions & Answers 27

You might also like