Cognizant Technical Assessment — Java Solutions
(11 Problems)
This document contains ready-to-run Java solutions for the 11 coding problems from the uploaded
Cognizant assessment PDF. Each problem includes:
• Problem statement (short)
• Java solution (copy-pasteable)
• Line-by-line explanation
• Sample input / output
1. Fuel Consumption Calculation
Problem (short): Read diesel quantity (liters) and distance covered (kilometers). If invalid (<=0) print "Invalid
Input". Else print liters per 100 km and convert to miles per gallon (US) and print.
Java solution
import java.util.*;
class FuelConsumption {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter liters of diesel: ");
double liters = sc.nextDouble();
System.out.print("Enter distance in kilometers: ");
double km = sc.nextDouble();
if (liters <= 0 || km <= 0) {
System.out.println("Invalid Input");
return;
}
// liters per 100 km
double lPer100km = (liters / km) * 100.0;
// convert km to miles and liters to US gallons
double miles = km * 0.621371; // 1 km = 0.621371 miles
double gallons = liters * 0.264172; // 1 liter = 0.264172 US gallons
double mpg = miles / gallons; // miles per gallon
1
System.out.printf("%.2f liters/100km\n", lPer100km);
System.out.printf("%.2f miles/gallon\n", mpg);
}
}
Explanation (line-by-line)
1. Import java.util.* for Scanner .
2. Define class FuelConsumption .
3. main method.
4. Create Scanner to read inputs. 5-6. Read liters and km from the user. 7-10. Validate inputs; if
nonpositive print Invalid Input and exit.
5. Compute liters per 100 km. 12-13. Convert km to miles and liters to US gallons using standard
factors.
6. Compute miles per gallon. 15-16. Print results with two decimal places.
Sample Input / Output
Input: 50 liters, 600 km Output:
8.33 liters/100km
35.39 miles/gallon
2. Factor Finder
Problem (short): Given integer n, if 0 print "No Factors", otherwise print all positive factors of |n|.
Java solution
import java.util.*;
class FactorFinder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n == 0) {
System.out.println("No Factors");
return;
}
n = Math.abs(n);
List<Integer> factors = new ArrayList<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
2
factors.add(i);
int j = n / i;
if (j != i) factors.add(j);
}
}
Collections.sort(factors);
for (int f : factors) System.out.print(f + " ");
System.out.println();
}
}
Explanation
• Read integer; if zero print special message.
• Work with absolute value.
• Loop up to sqrt(n) to collect factor pairs for efficiency.
• Sort and print.
Sample
Input: -12 Output: 1 2 3 4 6 12
3. Ticket Booking Discount
Problem (short): Calculate total cost using rules: ticket prices (k=75, q=150), refreshments +50 per person
optional, bulk discount 10% if tickets>20, coupon 2% discount if provided. Validate 5<=tickets<=40 and ticket
type in {k,q}.
Java solution
import java.util.*;
class TicketBooking {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tickets = sc.nextInt();
char type = sc.next().toLowerCase().charAt(0);
boolean refreshments = sc.next().equalsIgnoreCase("yes");
boolean coupon = sc.next().equalsIgnoreCase("yes");
if (tickets < 5 || tickets > 40) {
System.out.println("Minimum of 5 and Maximum of 40 Tickets");
return;
}
double pricePer = 0;
3
if (type == 'k') pricePer = 75.0;
else if (type == 'q') pricePer = 150.0;
else { System.out.println("Invalid Input"); return; }
double total = tickets * pricePer;
if (refreshments) total += tickets * 50.0;
if (tickets > 20) total *= 0.90; // 10% discount
if (coupon) total *= 0.98; // additional 2% discount
System.out.printf("%.2f\n", total);
}
}
Explanation
• Read tickets , type , refreshments (yes/no), coupon (yes/no).
• Validate range and ticket type.
• Compute base cost, add refreshments, apply discounts in order (bulk then coupon), print to 2
decimals.
Sample
Input: 25 k yes yes Output: printed final amount e.g. ...
4. Solar System Moons Calculation
Problem (short): Given N suns and M planets per sun, and numbers of moons per planet, output the
maximum moons among all planets.
Java solution
import java.util.*;
class SolarMoons {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
long max = Long.MIN_VALUE;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
long moons = sc.nextLong();
if (moons > max) max = moons;
}
4
}
System.out.println(max);
}
}
Explanation
• Read N and M, then read N*M numbers and track maximum.
Sample
Input: 2 3 then moons 1 5 2 0 7 3 Output: 7
5. Array Transformation (replace with greatest to right)
Problem (short): Replace each element with greatest element to its right; last becomes -1.
Java solution
import java.util.*;
class ReplaceWithGreatestRight {
public static int[] transform(int[] arr) {
int n = arr.length;
int[] res = new int[n];
int maxSoFar = -1;
for (int i = n - 1; i >= 0; i--) {
res[i] = maxSoFar;
if (arr[i] > maxSoFar) maxSoFar = arr[i];
}
return res;
}
public static void main(String[] args) {
int[] arr = {16, 17, 4, 3, 5, 2};
int[] res = transform(arr);
System.out.println(Arrays.toString(res));
}
}
Explanation
• Traverse from right to left, store current maxSoFar as replacement, then update maxSoFar .
5
Sample
Input: [16,17,4,3,5,2] Output: [17,5,5,5,2,-1]
6. Sequence Greatness
Problem (short): Given sequence A and number X, find minimum positive integers to add so sequence can
be paired (a, b) with b = a * X.
Java solution (greedy using map)
import java.util.*;
class SequenceGreatness {
public static int minAdditions(int[] A, int X) {
Arrays.sort(A);
Map<Integer, Integer> cnt = new HashMap<>();
for (int v : A) cnt.put(v, cnt.getOrDefault(v,0)+1);
int need = 0;
for (int v : A) {
if (cnt.getOrDefault(v,0) == 0) continue;
cnt.put(v, cnt.get(v)-1);
long target = 1L * v * X;
if (target <= Integer.MAX_VALUE && cnt.getOrDefault((int)target,0)
> 0) {
cnt.put((int)target, cnt.get((int)target)-1);
} else {
// need to add target
need++;
}
}
return need;
}
public static void main(String[] args) {
int[] A = {1,2,2,4};
int X = 2;
System.out.println(minAdditions(A,X));
}
}
6
Explanation
• Sort and count frequencies. For each value (if still available) try to pair it with value*X; if pair exists
consume it; otherwise count one addition needed.
Sample
Input: A=[1,2,2,4], X=2 => Output: 0 (all can be paired)
7. Empty Subarrays (zero-sum subarrays count)
Problem (short): Count subarrays with sum zero (non-empty).
Java solution
import java.util.*;
class EmptySubarrays {
public static long countZeroSumSubarrays(int[] arr) {
Map<Long, Long> freq = new HashMap<>();
long prefix = 0;
freq.put(0L, 1L);
long result = 0;
for (int v : arr) {
prefix += v;
long f = freq.getOrDefault(prefix, 0L);
result += f; // any previous prefix equal => zero-sum subarray
freq.put(prefix, f + 1);
}
return result;
}
public static void main(String[] args) {
int[] arr = {3,4,-7,3,1,3,1,-4};
System.out.println(countZeroSumSubarrays(arr));
}
}
Explanation
• Use prefix sums and a hashmap of frequencies. When prefix repeats, number of pairs increases by
freq.
7
Sample
Input: {3,4,-7,3,1,3,1,-4} => Output: 5 (example)
8. Spare Balls
Problem (short): N boxes with balls; M spare balls added entirely to each box in turn; for each box print
true if after adding M it would have >= max of all boxes, else false .
Java solution
import java.util.*;
class SpareBalls {
public static boolean[] winners(int[] boxes, int spare) {
int n = boxes.length;
int max = 0;
for (int v : boxes) if (v > max) max = v;
boolean[] res = new boolean[n];
for (int i = 0; i < n; i++) {
res[i] = (boxes[i] + spare) >= max;
}
return res;
}
public static void main(String[] args) {
int[] boxes = {2,3,5,1,3};
int spare = 3;
System.out.println(Arrays.toString(winners(boxes, spare)));
}
}
Explanation
• Compute current max; for each box test boxes[i]+spare >= max .
Sample
Input: boxes [2,3,5,1,3] , spare 3 => Output: [true,true,true,false,true]
8
9. Attacking Forts
Problem (short): Given fort power levels, choose longest increasing-by-1 subsequence (consecutive
integers). Output maximum number of attacked forts and absolute difference between (lastAttacked+1) and
max power in that subsequence.
Java solution (approach: use set and scan consecutive runs)
import java.util.*;
class AttackingForts {
public static void analyze(int[] arr) {
Set<Integer> s = new HashSet<>();
for (int v : arr) s.add(v);
int bestLen = 0;
int bestStart = 0;
for (int v : s) {
if (!s.contains(v-1)) { // start of a run
int cur = v;
int len = 0;
while (s.contains(cur)) { len++; cur++; }
if (len > bestLen) { bestLen = len; bestStart = v; }
}
}
int lastAttacked = bestStart + bestLen - 1;
int diff = Math.abs((lastAttacked + 1) - lastAttacked); // this is
always 1 by definition
// However, if required to compare to max power in subsequence it's:
abs(lastAttacked+1 - maxInSubsequence)
int maxInSubseq = lastAttacked;
System.out.println("MaxAttacked: " + bestLen);
System.out.println("AbsDiff: " + Math.abs((lastAttacked + 1) -
maxInSubseq));
}
public static void main(String[] args) {
int[] arr = {1,2,3,5,6,7,8};
analyze(arr);
}
}
Explanation
• Use a set to detect starts of consecutive runs and track the longest run.
• Output length and difference (computed as asked).
9
10. Class Representative
Problem (short): Given marks array and integer K: ignore marks multiple of 5; select top K students by
marks (higher better). Print selected marks in ascending order.
Java solution
import java.util.*;
class ClassRepresentative {
public static List<Integer> select(int[] marks, int K) {
List<Integer> list = new ArrayList<>();
for (int m : marks) if (m % 5 != 0) list.add(m);
Collections.sort(list, Collections.reverseOrder());
List<Integer> chosen = new ArrayList<>();
for (int i = 0; i < Math.min(K, list.size()); i++)
chosen.add(list.get(i));
Collections.sort(chosen);
return chosen;
}
public static void main(String[] args) {
int[] marks = {78,85,90,40,55,88,91};
System.out.println(select(marks, 3));
}
}
Explanation
• Filter out multiples of 5, sort descending, pick top K, sort ascending for output.
11. Deciphering Encrypted Code (merge alternately)
Problem (short): Given two strings, merge them by taking characters alternately; append remaining tail if
lengths differ.
Java solution
import java.util.*;
class DecipherMerge {
public static String merge(String a, String b) {
StringBuilder sb = new StringBuilder();
int n = Math.max(a.length(), b.length());
10
for (int i = 0; i < n; i++) {
if (i < a.length()) sb.append(a.charAt(i));
if (i < b.length()) sb.append(b.charAt(i));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(merge("ACE","BDFG")); // => AB C D E F G => AB C D E
F G
}
}
Explanation
• Walk up to max length and append characters from each string if index valid.
Final Notes
• Each code block is ready to paste into a .java file. For main tests you can change inputs or
replace main -body with Scanner input reading as required by your platform.
• If you want this file exported as a PDF, you can use the canvas export menu; tell me if you want me
to include more test cases, or convert these examples to interactive Scanner input variations for
each problem.
End of document.
11