0% found this document useful (0 votes)
2 views

testtest

The document contains a series of programming questions and solutions related to arrays, linked lists, and other data structures. It includes problems such as calculating total costs based on freshness values, finding missing numbers in sequences, and manipulating linked lists. Each question is accompanied by sample test cases and Java code implementations to demonstrate the solutions.

Uploaded by

jsudhanya.9
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

testtest

The document contains a series of programming questions and solutions related to arrays, linked lists, and other data structures. It includes problems such as calculating total costs based on freshness values, finding missing numbers in sequences, and manipulating linked lists. Each question is accompanied by sample test cases and Java code implementations to demonstrate the solutions.

Uploaded by

jsudhanya.9
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Testtest

Questions

Q1. Chef visited a grocery store for supplies. There are N items in the store where the ith item has
a freshness value Ai, and cost Bi. Chef has decided to purchase all the items having a freshness
value greater than equal to X. Find the total cost of the groceries Chef buys.
Sample test case: Input: N2, X20, A[15, 67], B = [10, 90]
Output: 90 (Explanation: Item 2 has freshness value greater than equal to X-20. Thus, Chef buys
item 2. The total cost is 90.)

Q2. We need to find the total number of steps need to make the current array of size N same as an
array containing 1 to N numbers as elements. Each decrement or increment is counted as a step.
Sample test case: Input: A [8, 3, 2, 1, 9]
Output: 8 (Explanation: As our target array is [1,2,3,4,5], we already have 1, 2, and 3 in our array.
We have 8 and 9 in place of 4 and 5, so if convert 8 to 4, and 9 to 5, we can achieve target array.
Hence minimum increments/decrements required will be (8-4)+(9-5) ways i.e. 8 steps.)

Q3. Given the head of a linked list, Find the number of critical points. (The starting and end are not
considered critical points). Local minima or maxima are called critical points. A Node is called a
local minima if both next and previous elements are greater than the current element. A Node is
called a local maxima if both next and previous elements are smaller than the current element.
Sample test case: Input: L [1, 2, 3, 2, 1, 3, 2)
Output: 3 (Explanation: 3rd node, 5th node and 6th node are the critical nodes, hence the answer
is 3)

Q1. Write a Java program to identify the missing number in a sequence of integers ranging from 1
to n. The input will be an array of size (n-1), containing distinct integers from 1 to n with one
number missing. The program should output the missing number.
Example: Input: Array = [1, 2, 4, 6, 3, 7, 8] Output: Missing number = 5

Q2. You are given a building with n floors and a special ball. When the ball dropped from a floor,
the ball may either:
1. Break if dropped from a floor equal to or higher than a critical floor (F).
2. Remain intact if dropped from a floor below the critical floor (F).
Write a Java program to determine the critical floor (F) with a minimum number of drops.
Input:
Number of floors (n): 100
Critical floor (F): 30th
Output: Total drops required: 7

Q3. You are given two singly linked lists: List¹ and List2.
Write a Java function to insert List2 into List1 after the second element of List1. If List1 has less
than two elements, append List2 at the end of Listl.
Input:
List1=1>2>3-4-> NULL List2-56 -> NULL
Output:
1-2-5-6-3-4-> NULL

Q1. There is an integer array A sorted in ascending order (with distinct values). Prior to being
passed to your function, A is possibly rotated at an unknown pivot index k (1 <=k< nums.length)
such that the resulting array is [nums[k], nums[k+1],..., nums[n-1], nums[0], nums[1]..... nums/k-
11] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become
[4,5,6,7,0,1,2], Given the array A after the possible rotation and an integer target, return the index
of target if it is in A, or -1 if it is not in A. You must write a java program with O(log n) runtime
complexity.

Q2. Given an integer array A, move all 0's to the end of it while maintaining the relative order of
the non-zero elements. Note that you must do this in-place without making a copy of the array.
Write a java program to implement it. Example: Input: A = [0,1,0,3,12] Output: [1,3,12,0,0]

Q3.Given a linked list, swap every two adjacent nodes and return its head. You must solve the
problem without modifying the values in the list's nodes (i.e., only nodes themselves may be
changed). Given the head of a linked list, reverse the nodes of the list k at a time, and return the
modified list. k is a positive integer and is less than or equal to the length of the linked list. If the
number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is. You
may not alter the values in the list's nodes, only nodes themselves may be changed. Write a java
program to implement it. For example Input: head = [1,2,3,4,5], k=2 Output: [2,1,4,3,5)

Q1. During a security guard interview, each candidate's height is measured against a standard
height 'h' A value that indicates the deviation from the standard height, either Ofthe samel or a ve
(more than standard) or ve (less than standardi, is retained for subsequent processing. Which
height is most common? (h and all deviation vahies are considered as integers).
Case Study: For 15 candidates with standard height h-6, the list showing deviation in height is (1,
0, -1, -2, 1, 2, 2, 1, 1, 1, 1, 0, -1, -1, 1). The most common height in 7.

Q2. You are given a list of 'n' students with their names and total marles secured in the
examination. Write a program to arrange them in non-increasing order of their marks and decide if
a unique or joint topper exists. Display the name of the topper/toppers,

Q3. Two linked lista, 'A' and B', were given. A is expected to be a list of even numbers, and B is
expected to be a lat of odd numbers. But in the input, 'A' has one odd element, and 'B' has an even
element. Write a program to create linked lists and a method to operate on these two lists to
update them as expected.
Test case:
Input: (A: 150-52-26-31-12->64] and [B: 23->100->7-17-3) Output: A: 150->52-26->100->12->64)
and (B: 23-531-7-17-3)

public class GroceryStore {


public static int totalCost(int N, int X, int[] A, int[] B) {
int totalCost = 0;
for (int i = 0; i < N; i++) {
if (A[i] >= X) {
totalCost += B[i];
}
}
return totalCost;
}

public static void main(String[] args) {


// Sample test case
int N = 2;
int X = 20;
int[] A = {15, 67};
int[] B = {10, 90};

System.out.println(totalCost(N, X, A, B)); // Output: 90


}
}—————public class ArrayTransformation {
public static int minSteps(int[] A) {
int N = A.length;
int steps = 0;

// Create the target array [1, 2, ..., N]


int[] target = new int[N];
for (int i = 0; i < N; i++) {
target[i] = i + 1;
}

// Calculate the total number of steps needed


for (int i = 0; i < N; i++) {
steps += Math.abs(A[i] - target[i]);
}

return steps;
}

public static void main(String[] args) {


// Sample test case
int[] A = {8, 3, 2, 1, 9};

System.out.println(minSteps(A)); // Output: 8
}
}

—————
public class ArrayTransformation {
public static int minSteps(int[] A) {
int N = A.length;
int steps = 0;
// Create the target array [1, 2, ..., N]
int[] target = new int[N];
for (int i = 0; i < N; i++) {
target[i] = i + 1;
}

// Calculate the total number of steps needed


for (int i = 0; i < N; i++) {
steps += Math.abs(A[i] - target[i]);
}

return steps;
}

public static void main(String[] args) {


// Sample test case
int[] A = {8, 3, 2, 1, 9};

System.out.println(minSteps(A)); // Output: 8
}
}

—————
public class MissingNumberFinder {
public static int findMissingNumber(int[] array, int n) {
// Calculate the expected sum of numbers from 1 to n
int expectedSum = n * (n + 1) / 2;

// Calculate the actual sum of the elements in the array


int actualSum = 0;
for (int num : array) {
actualSum += num;
}

// The missing number is the difference between the expected


sum and the actual sum
return expectedSum - actualSum;
}

public static void main(String[] args) {


// Sample test case
int[] array = {1, 2, 4, 6, 3, 7, 8};
int n = 8; // The range of numbers is from 1 to 8

int missingNumber = findMissingNumber(array, n);


System.out.println("Missing number = " + missingNumber); //
Output: Missing number = 5
}
}
—————

public class CriticalFloorFinder {


public static int findCriticalFloor(int n, int F) {
int low = 1;
int high = n;
int drops = 0;

while (low <= high) {


int mid = (low + high) / 2;
drops++;

if (mid == F) {
return drops;
} else if (mid < F) {
low = mid + 1;
} else {
high = mid - 1;
}
}

return drops;
}

public static void main(String[] args) {


// Sample test case
int n = 100; // Number of floors
int F = 30; // Critical floor

int totalDrops = findCriticalFloor(n, F);


System.out.println("Total drops required: " + totalDrops); //
Output: Total drops required: 7
}
}—————class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedListInsertion {
public static ListNode insertList(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}

ListNode current = list1;


int count = 1;

// Traverse to the second element of list1


while (current.next != null && count < 2) {
current = current.next;
count++;
}

// If list1 has less than two elements, append list2 at the end of
list1
if (count < 2) {
current.next = list2;
} else {
// Insert list2 after the second element of list1
ListNode temp = current.next;
current.next = list2;

// Traverse to the end of list2


while (list2.next != null) {
list2 = list2.next;
}

// Connect the remaining part of list1


list2.next = temp;
}

return list1;
}

public static void printList(ListNode head) {


ListNode current = head;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("NULL");
}

public static void main(String[] args) {


// Create List1: 1 -> 2 -> 3 -> 4 -> NULL
ListNode list1 = new ListNode(1);
list1.next = new ListNode(2);
list1.next.next = new ListNode(3);
list1.next.next.next = new ListNode(4);

// Create List2: 5 -> 6 -> NULL


ListNode list2 = new ListNode(5);
list2.next = new ListNode(6);

// Insert List2 into List1


ListNode result = insertList(list1, list2);

// Print the result


printList(result); // Output: 1 -> 2 -> 5 -> 6 -> 3 -> 4 -> NULL
}
}

—————
public class RotatedSortedArraySearch {
public static int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (nums[mid] == target) {
return mid;
}

// Determine which part is sorted


if (nums[left] <= nums[mid]) {
// Left part is sorted
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
// Right part is sorted
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}

return -1; // Target not found


}

public static void main(String[] args) {


// Sample test case
int[] nums = {4, 5, 6, 7, 0, 1, 2};
int target = 0;

int result = search(nums, target);


System.out.println("Index of target: " + result); // Output:
Index of target: 4
}
}

————
public class MoveZeroes {
public static void moveZeroes(int[] nums) {
int lastNonZeroFoundAt = 0;

// Move all non-zero elements to the beginning of the array


for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}

// Fill the remaining positions with zeros


for (int i = lastNonZeroFoundAt; i < nums.length; i++) {
nums[i] = 0;
}
}

public static void main(String[] args) {


// Sample test case
int[] nums = {0, 1, 0, 3, 12};

moveZeroes(nums);

// Print the result


for (int num : nums) {
System.out.print(num + " ");
}
// Output: 1 3 12 0 0
}
}

——

class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null && cur.next != null) {
ListNode t = cur.next;
cur.next = t.next;
t.next = cur;
pre.next = t;
pre = cur;
cur = cur.next;
}
return dummy.next;
}
}

——-

import java.util.HashMap;
import java.util.Map;

public class MostCommonHeight {


public static int findMostCommonHeight(int[] deviations, int h) {
// Create a map to store the frequency of each height
Map<Integer, Integer> heightFrequency = new HashMap<>();

// Calculate the actual heights and update their frequencies


for (int deviation : deviations) {
int height = h + deviation;
heightFrequency.put(height,
heightFrequency.getOrDefault(height, 0) + 1);
}

// Find the height with the maximum frequency


int mostCommonHeight = h;
int maxFrequency = 0;
for (Map.Entry<Integer, Integer> entry :
heightFrequency.entrySet()) {
if (entry.getValue() > maxFrequency) {
mostCommonHeight = entry.getKey();
maxFrequency = entry.getValue();
}
}

return mostCommonHeight;
}

public static void main(String[] args) {


// Sample test case
int h = 6;
int[] deviations = {1, 0, -1, -2, 1, 2, 2, 1, 1, 1, 1, 0, -1, -1, 1};

int mostCommonHeight = findMostCommonHeight(deviations,


h);
System.out.println("Most common height: " +
mostCommonHeight);
}
}

——————

import java.util.*;

public class TopperFinder {

// Method to find and display toppers


public static void findToppers(List<Student> students) {
// Step 1: Sort students by marks in descending order
Collections.sort(students, (s1, s2) -> s2.marks - s1.marks);

// Step 2: Display the sorted list


System.out.println("Sorted list (Name, Marks):");
for (Student student : students) {
System.out.println(student.name + ": " + student.marks);
}

// Step 3: Find the toppers


List<String> toppers = new ArrayList<>();
int highestMarks = students.get(0).marks; // Get the highest
marks
toppers.add(students.get(0).name);

for (int i = 1; i < students.size(); i++) {


if (students.get(i).marks == highestMarks) {
toppers.add(students.get(i).name);
} else {
break; // Exit loop once marks are no longer equal
}
}

// Step 4: Display the result


if (toppers.size() == 1) {
System.out.println("Unique Topper: " + toppers.get(0));
} else {
System.out.println("Joint Toppers: " + String.join(", ",
toppers));
}
}

public static void main(String[] args) {


// Test Case 1
System.out.println("Test Case 1:");
List<Student> students1 = new ArrayList<>();
students1.add(new Student("Vineet", 275));
students1.add(new Student("Shreya", 312));
students1.add(new Student("Rabin", 235));
students1.add(new Student("Sandy", 205));
students1.add(new Student("Kamath", 275));
students1.add(new Student("Vishal", 195));
findToppers(students1);

System.out.println("\nTest Case 2:");


// Test Case 2
List<Student> students2 = new ArrayList<>();
students2.add(new Student("Vineet", 275));
students2.add(new Student("Shreya", 312));
students2.add(new Student("Rabin", 287));
students2.add(new Student("Sandy", 205));
students2.add(new Student("Kamath", 312));
students2.add(new Student("Vishal", 195));
findToppers(students2);
}
}
// Student class to store name and marks
class Student {
String name;
int marks;

// Constructor
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
}

—————

class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}

public class LinkedListSwap {


public static void swapMisplacedElements(ListNode headA,
ListNode headB) {
ListNode oddInA = null, evenInB = null;
ListNode currentA = headA, currentB = headB;

// Find the misplaced odd element in A


while (currentA != null) {
if (currentA.val % 2 != 0) {
oddInA = currentA;
break;
}
currentA = currentA.next;
}

// Find the misplaced even element in B


while (currentB != null) {
if (currentB.val % 2 == 0) {
evenInB = currentB;
break;
}
currentB = currentB.next;
}

// Swap the values of the misplaced elements


if (oddInA != null && evenInB != null) {
int temp = oddInA.val;
oddInA.val = evenInB.val;
evenInB.val = temp;
}
}

public static void printList(ListNode head) {


ListNode current = head;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("NULL");
}

public static void main(String[] args) {


// Create List A: 150 -> 52 -> 26 -> 31 -> 12 -> 64
ListNode headA = new ListNode(150);
headA.next = new ListNode(52);
headA.next.next = new ListNode(26);
headA.next.next.next = new ListNode(31);
headA.next.next.next.next = new ListNode(12);
headA.next.next.next.next.next = new ListNode(64);

// Create List B: 23 -> 100 -> 7 -> 17 -> 3


ListNode headB = new ListNode(23);
headB.next = new ListNode(100);
headB.next.next = new ListNode(7);
headB.next.next.next = new ListNode(17);
headB.next.next.next.next = new ListNode(3);

// Swap the misplaced elements


swapMisplacedElements(headA, headB);

// Print the updated lists


System.out.print("List A: ");
printList(headA); // Output: List A: 150 -> 52 -> 26 -> 100 ->
12 -> 64 -> NULL

System.out.print("List B: ");
printList(headB); // Output: List B: 23 -> 31 -> 7 -> 17 -> 3 ->
NULL
}
}

You might also like