Sunday, 18 June 2023

Find the Kth Maximum and Minimum element from Array?


2 / 2

This is one of the most asked question from array in interviews. Find the "Kth" maximum and minimum element of an array in Java. This question is asked to check the logical skill and java knowledge of candidate. you can follow below steps to solve this problem:

  1. Sort the array in ascending order.
  2. The "Kth" minimum element will be at index K-1.
  3. The "Kth" maximum element will be at index array.length - K.

Here's an example code snippet that demonstrates this approach:

java
import java.util.Arrays;
public class KthMinMaxElement
public static void main(String[] args)
int[] array = {9, 5, 2, 7, 1, 8, 6, 3, 4};
// Sort the array in ascending order 
 Arrays.sort(array);
int k = 3;
// The value of k // Find the Kth minimum element
int kthMin = array[k - 1];
 System.out.println("Kth minimum element: " + kthMin);
// Find the Kth maximum element
int kthMax = array[array.length - k];
 System.out.println("Kth maximum element: " + kthMax);
 }
 }

In this example, the array is {9, 5, 2, 7, 1, 8, 6, 3, 4}. We want to find the 3rd minimum and maximum elements. The sorted array is {1, 2, 3, 4, 5, 6, 7, 8, 9}, so the 3rd minimum element is 3, and the 3rd maximum element is 7.

You can modify the code according to your specific requirements by providing a different array and value for k. 

Friday, 16 June 2023

Reverse Java Array with Two-Pointer Technique

 To reverse an array in Java with an optimized approach, you can use a two-pointer technique. Here's an example implementation:

java
public class ReverseArray
public static void reverse(int[] arr)
int left = 0
int right = arr.length - 1;
while (left < right) { 
// Swap elements at left and right indices int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; 
// Move the pointers towards the center 
 left++; right--; 
 } 
 } 
public static void main(String[] args)
int[] arr = {1, 2, 3, 4, 5}; 
 System.out.println("Original Array: " + Arrays.toString(arr)); reverse(arr); System.out.println("Reversed Array: " + Arrays.toString(arr)); 
 } 
}

In this example, the reverse method takes an array of integers (arr) as input. It initializes two pointers, left and right, pointing to the first and last elements of the array, respectively. It then iterates through the array, swapping the elements at the left and right indices using a temporary variable. After each swap, the left pointer is incremented and the right pointer is decremented, moving towards the center of the array. This process continues until the left pointer crosses the right pointer, resulting in a reversed array.

The example demonstrates the reversal of the array {1, 2, 3, 4, 5}. The output will be:

javascript
Original Array: [1, 2, 3, 4, 5
Reversed Array: [5, 4, 3, 2, 1]

Using the two-pointer technique ensures that each element in the array is swapped only once, resulting in an optimized approach for reversing the array.