[Go to site: main page, start]

0% found this document useful (0 votes)
4 views67 pages

Java Questions

The document provides a comprehensive collection of Java interview questions and solutions focused on arrays and one-dimensional array operations. It includes various topics such as finding maximum and minimum values, reversing arrays, moving zeroes, and calculating subarray sums, along with accompanying code examples and outputs. Each solution is designed to optimize performance and demonstrate efficient coding practices.

Uploaded by

gargeekanwa1121
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)
4 views67 pages

Java Questions

The document provides a comprehensive collection of Java interview questions and solutions focused on arrays and one-dimensional array operations. It includes various topics such as finding maximum and minimum values, reversing arrays, moving zeroes, and calculating subarray sums, along with accompanying code examples and outputs. Each solution is designed to optimize performance and demonstrate efficient coding practices.

Uploaded by

gargeekanwa1121
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

Java Complete Interview question bank Solution

NAME : GARGEE KANWA

BRANCH : CSE-AIML

SEMESTER : 4th

ENROLLMENT : 0111AL241082

Topic 1: Introduction of Arrays & One-Dimensional Array


1. Best Time to Buy and Sell Stock

Logic: Traverse the price list while maintaining two indicators: the lowest price observed
up to that point and the maximum calculated difference between the current price and
that lowest price. This approach optimizes resource consumption down to a linear scale,
bypassing unnecessary inner loops.
Code:

Java

public class Solution {

public static int maxProfit(int[] prices) {

int minPrice = Integer.MAX_VALUE;

int maxProfit = 0;

for (int price : prices) {

if (price < minPrice) {

minPrice = price;

} else if (price - minPrice > maxProfit) {

maxProfit = price - minPrice;

}
return maxProfit;

public static void main(String[] args) {

[Link](maxProfit(new int[]{7, 1, 5, 3, 6, 4}));

Output: 5

2. Find Maximum & Minimum in Array

Logic: Initialize track markers to the first slot's value. Run a linear loop through the
sequence, continually evaluating each item to systematically raise the maximum
boundary or lower the minimum boundary as required.
Code:

Java

public class Solution {

public static void findMinMax(int[] temp) {

int min = temp[0];

int max = temp[0];

for (int i = 1; i < [Link]; i++) {

if (temp[i] > max) max = temp[i];

if (temp[i] < min) min = temp[i];

[Link]("max=" + max + ", min=" + min);

public static void main(String[] args) {

findMinMax(new int[]{3, 5, 1, 9, 2});

Output: max=9, min=1

3. Reverse an Array In-Place

Logic: Place pointers at both ends of the structure. Systematically swap the
components at these locations while incrementally shifting the trackers toward the
center until they meet.
Code:

Java

import [Link];

public class Solution {

public static int[] reverseArray(int[] songs) {

int left = 0, right = [Link] - 1;

while (left < right) {

int temp = songs[left];

songs[left] = songs[right];

songs[right] = temp;

left++;

right--;

return songs;

public static void main(String[] args) {

[Link]([Link](reverseArray(new int[]{1, 2, 3, 4, 5})));

Output: [5, 4, 3, 2, 1]

4. Second Largest Element

Logic: Keep track of the top two distinct highest values during a single horizontal scan.
Update the primary leader whenever a new extreme is encountered, shifting the former
leader down to the runner-up slot.
Code:

Java

public class Solution {

public static int getSecondLargest(int[] scores) {

int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;

for (int score : scores) {


if (score > first) {

second = first;

first = score;

} else if (score > second && score != first) {

second = score;

return (second == Integer.MIN_VALUE) ? -1 : second;

public static void main(String[] args) {

[Link](getSecondLargest(new int[]{12, 35, 1, 10, 34, 1}));

Output: 34

5. Move Zeroes to End

Logic: Maintain a marker representing the next available position to place a non-zero
element. Iterate through the collection, writing non-zero components to this marker
index while moving it forward. Once complete, overwrite all remaining trailing positions
up to the array's boundary with zero.
Code:

Java

import [Link];

public class Solution {

public static int[] moveZeroes(int[] pixels) {

int pos = 0;

for (int i = 0; i < [Link]; i++) {

if (pixels[i] != 0) {

pixels[pos++] = pixels[i];

while (pos < [Link]) {


pixels[pos++] = 0;

return pixels;

public static void main(String[] args) {

[Link]([Link](moveZeroes(new int[]{0, 1, 0, 3, 12})));

Output: [1, 3, 12, 0, 0]

6. Maximum Subarray Sum (Kadane's)

Logic: Track the cumulative tally at the current index, dropping the accumulation if it
dips below zero and starting fresh from the current index. Record when the global peak
changes to find the largest sum along with its window boundaries.
Code:

Java

public class Solution {

public static void maxSubArray(int[] nums) {

int maxSoFar = nums[0], currMax = nums[0];

int start = 0, end = 0, s = 0;

for (int i = 1; i < [Link]; i++) {

if (nums[i] > currMax + nums[i]) {

currMax = nums[i];

s = i;

} else {

currMax += nums[i];

if (currMax > maxSoFar) {

maxSoFar = currMax;

start = s;

end = i;
}

[Link](maxSoFar + " (Indices: " + start + "-" + end + ")");

public static void main(String[] args) {

maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4});

Output: 6 (Indices: 3-6)

7. Find All Duplicates in Array

Logic: Utilize individual value entries as markers mapping directly to coordinate


positions. Flip the value at that target coordinate to negative. If an accessed value is
already negative, the corresponding entry has appeared before, signaling a duplicate.
Code:

Java

import [Link].*;

public class Solution {

public static List<Integer> findDuplicates(int[] nums) {

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

for (int i = 0; i < [Link]; i++) {

int index = [Link](nums[i]) - 1;

if (nums[index] < 0) [Link]([Link](nums[i]));

else nums[index] = -nums[index];

return res;

public static void main(String[] args) {

[Link](findDuplicates(new int[]{4, 3, 2, 7, 8, 2, 3, 1}));

}
Output: [2, 3]

8. Rotate Array by K Steps

Logic: Normalize the displacement step count to fit within the boundaries of the
structure using modular reduction. Execute three successive array reversals to cleanly
re-allocate components without helper allocations: reverse everything, reverse the
initial chunk, then reverse the remaining tail.
Code:

Java

import [Link];

public class Solution {

public static void rotate(int[] nums, int k) {

int n = [Link];

k = k % n;

if (k < 0) k += n;

reverse(nums, 0, n - 1);

reverse(nums, 0, k - 1);

reverse(nums, k, n - 1);

private static void reverse(int[] nums, int start, int end) {

while (start < end) {

int temp = nums[start];

nums[start] = nums[end];

nums[end] = temp;

start++;

end--;

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

rotate(arr, 3);

[Link]([Link](arr));
}

Output: [5, 6, 7, 1, 2, 3, 4]

9. Trapping Rain Water

Logic: Initialize pointers at both the left and right boundaries while tracking the
maximum height from both sides. Advance the pointer pointing to the smaller maximum
height inward, calculating the water trapped at that spot based on the difference
between its local maximum boundary and its current height.
Code:

Java

public class Solution {

public static int trap(int[] height) {

int left = 0, right = [Link] - 1;

int leftMax = 0, rightMax = 0, totalWater = 0;

while (left < right) {

if (height[left] < height[right]) {

if (height[left] >= leftMax) leftMax = height[left];

else totalWater += leftMax - height[left];

left++;

} else {

if (height[right] >= rightMax) rightMax = height[right];

else totalWater += rightMax - height[right];

right--;

return totalWater;

public static void main(String[] args) {

[Link](trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));

}
Output: 6

10. Median of Two Sorted Arrays

Logic: Use binary search to find a valid partition index in the smaller array such that all
elements on the left side are smaller than or equal to all elements on the right side
across both arrays.
Code:

Java

public class Solution {

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {

if ([Link] > [Link]) return findMedianSortedArrays(nums2, nums1);

int x = [Link], y = [Link];

int low = 0, high = x;

while (low <= high) {

int partitionX = (low + high) / 2;

int partitionY = (x + y + 1) / 2 - partitionX;

int maxLeftX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];

int minRightX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];

int maxLeftY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];

int minRightY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];

if (maxLeftX <= minRightY && maxLeftY <= minRightX) {

if ((x + y) % 2 == 0) {

return ((double)[Link](maxLeftX, maxLeftY) + [Link](minRightX,


minRightY)) / 2.0;

} else {

return (double)[Link](maxLeftX, maxLeftY);

} else if (maxLeftX > minRightY) {

high = partitionX - 1;

} else {

low = partitionX + 1;

}
}

return 0.0;

public static void main(String[] args) {

[Link](findMedianSortedArrays(new int[]{1, 3}, new int[]{2}));

Output: 2.0

Topic 2: Programs of One-Dimensional Array


11. Running Sum of 1D Array

Logic: Iterate through the array starting from the second element, cumulatively adding
the value of the previous element to the current one to update the array in place.
Code:

Java

import [Link];

public class Solution {

public static int[] runningSum(int[] nums) {

for (int i = 1; i < [Link]; i++) {

nums[i] += nums[i - 1];

return nums;

public static void main(String[] args) {

[Link]([Link](runningSum(new int[]{1, 2, 3, 4})));

Output: [1, 3, 6, 10]

12. Element Frequency Count

Logic: Map every item encountered to an associative collection, incrementing its value
count on each match to log occurrences cleanly without needing fixed bucket
allocations.
Code:

Java

import [Link].*;

public class Solution {

public static void countFrequency(int[] items) {

Map<Integer, Integer> map = new LinkedHashMap<>();

for (int item : items) {

[Link](item, [Link](item, 0) + 1);

List<String> output = new ArrayList<>();

for ([Link]<Integer, Integer> entry : [Link]()) {

[Link]([Link]() + ":" + [Link]());

[Link]([Link](", ", output));

public static void main(String[] args) {

countFrequency(new int[]{4, 3, 2, 4, 1, 3, 4});

Output: 4:3, 3:2, 2:1, 1:1

13. Remove Duplicates from Sorted Array

Logic: Use a slow pointer to track the position of the last unique element found.
Advance a fast pointer through the array, copying elements to the slow pointer's next
position only when a new unique value is encountered.
Code:

Java

public class Solution {

public static int removeDuplicates(int[] ids) {

if ([Link] == 0) return 0;

int k = 1;
for (int i = 1; i < [Link]; i++) {

if (ids[i] != ids[k - 1]) {

ids[k] = ids[i];

k++;

return k;

public static void main(String[] args) {

[Link](removeDuplicates(new int[]{1, 1, 2}));

Output: 2

14. Check if Array is Sorted

Logic: Scan linearly from left to right. If any item is found to be strictly smaller than the
element preceding it, exit early and return false.
Code:

Java

public class Solution {

public static boolean isSorted(int[] codes) {

for (int i = 1; i < [Link]; i++) {

if (codes[i] < codes[i - 1]) return false;

return true;

public static void main(String[] args) {

[Link](isSorted(new int[]{1, 2, 3, 4, 5}));

Output: true
15. Left Rotate Array by D Positions

Logic: Normalize the shift distance using a modulo operation based on the total
elements. Perform three targeted reversals—reversing the entire array, then the first
partition, and finally the second partition—to achieve the rotation in place.
Code:

Java

import [Link];

public class Solution {

public static int[] leftRotate(int[] belt, int d) {

int n = [Link];

d = d % n;

reverse(belt, 0, d - 1);

reverse(belt, d, n - 1);

reverse(belt, 0, n - 1);

return belt;

private static void reverse(int[] arr, int start, int end) {

while (start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

public static void main(String[] args) {

[Link]([Link](leftRotate(new int[]{1, 2, 3, 4, 5}, 2)));

Output: [3, 4, 5, 1, 2]
16. Subarray Sum Equals K

Logic: Track the running prefix sum while recording how often each sum occurs in a hash
map. At each step, if the difference between the current prefix sum and $k$ exists in the
map, add its frequency to the total count.
Code:

Java

import [Link];

public class Solution {

public static int subarraySum(int[] redemptions, int k) {

int count = 0, sum = 0;

HashMap<Integer, Integer> map = new HashMap<>();

[Link](0, 1);

for (int val : redemptions) {

sum += val;

if ([Link](sum - k)) {

count += [Link](sum - k);

[Link](sum, [Link](sum, 0) + 1);

return count;

public static void main(String[] args) {

[Link](subarraySum(new int[]{1, 1, 1}, 2));

Output: 2

17. Majority Element (Boyer-Moore)

Logic: Maintain a candidate value and a balancing balance indicator. Step through the
array, incrementing the counter when the element matches the candidate and
decrementing it otherwise; pick a new candidate whenever the counter resets to zero.
Code:

Java
public class Solution {

public static int majorityElement(int[] votes) {

int count = 0, candidate = 0;

for (int vote : votes) {

if (count == 0) {

candidate = vote;

count += (vote == candidate) ? 1 : -1;

return candidate;

public static void main(String[] args) {

[Link](majorityElement(new int[]{3, 2, 3}));

Output: 3

18. Find the Duplicate Number

Logic: Treat the values within the array as pointers to other indices to construct a linked
path. Use Floyd's cycle detection algorithm with slow and fast pointers to locate the
start of the loop, which reveals the duplicate entry.
Code:

Java

public class Solution {

public static int findDuplicate(int[] nums) {

int slow = nums[0], fast = nums[0];

do {

slow = nums[slow];

fast = nums[nums[fast]];

} while (slow != fast);

fast = nums[0];
while (slow != fast) {

slow = nums[slow];

fast = nums[fast];

return slow;

public static void main(String[] args) {

[Link](findDuplicate(new int[]{1, 3, 4, 2, 2}));

Output: 2

19. Longest Increasing Subsequence

Logic: Maintain an active array tracking the smallest tail elements of all increasing
subsequences found so far. For each element, use binary search to find its correct
position in this tracking array, updating or extending it as necessary.
Code:

Java

import [Link];

public class Solution {

public static int lengthOfLIS(int[] nums) {

int[] tails = new int[[Link]];

int size = 0;

for (int x : nums) {

int i = 0, j = size;

while (i != j) {

int mid = (i + j) / 2;

if (tails[mid] < x) i = mid + 1;

else j = mid;

tails[i] = x;
if (i == size) size++;

return size;

public static void main(String[] args) {

[Link](lengthOfLIS(new int[]{10, 9, 2, 5, 3, 7, 101, 18}));

Output: 4

20. Sliding Window Maximum

Logic: Use a monotonic double-ended queue to store the indices of elements in


decreasing order of value. For each window position, remove indices that fall outside
the current window from the front, and remove indices of smaller elements from the
back before adding the new index.
Code:

Java

import [Link].*;

public class Solution {

public static int[] maxSlidingWindow(int[] nums, int k) {

if (nums == null || [Link] == 0) return new int[0];

int n = [Link];

int[] r = new int[n - k + 1];

int ri = 0;

Deque<Integer> q = new ArrayDeque<>();

for (int i = 0; i < [Link]; i++) {

while (![Link]() && [Link]() < i - k + 1) {

[Link]();

while (![Link]() && nums[[Link]()] < nums[i]) {

[Link]();

}
[Link](i);

if (i >= k - 1) {

r[ri++] = nums[[Link]()];

return r;

public static void main(String[] args) {

[Link]([Link](maxSlidingWindow(new int[]{1, 3, -1, -3, 5, 3, 6, 7},


3)));

Output: [3, 3, 5, 5, 6, 7]

Topic 3: Two-Dimensional Array


21. Transpose a Matrix

Logic: Create a new output matrix with inverted dimensions, then iterate through the
source matrix to map each element at position [i][j] directly to [j][i] in the target matrix.
Code:

Java

import [Link];

public class Solution {

public static int[][] transpose(int[][] matrix) {

int m = [Link], n = matrix[0].length;

int[][] res = new int[n][m];

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

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

res[j][i] = matrix[i][j];

return res;
}

public static void main(String[] args) {

[Link]([Link](transpose(new int[][]{{1,2,3},{4,5,6},{7,8,9}})));

Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

22. Spiral Order Matrix Traversal

Logic: Set four boundary pointers at the outer edges of the matrix. Loop inward in a
clockwise pattern—moving right, down, left, and then up—while shifting the
corresponding boundary inward after completing each direction.
Code:

Java

import [Link].*;

public class Solution {

public static List<Integer> spiralOrder(int[][] matrix) {

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

if ([Link] == 0) return res;

int top = 0, bottom = [Link] - 1;

int left = 0, right = matrix[0].length - 1;

while (top <= bottom && left <= right) {

for (int i = left; i <= right; i++) [Link](matrix[top][i]);

top++;

for (int i = top; i <= bottom; i++) [Link](matrix[i][right]);

right--;

if (top <= bottom) {

for (int i = right; i >= left; i--) [Link](matrix[bottom][i]);

bottom--;

if (left <= right) {

for (int i = bottom; i >= top; i--) [Link](matrix[i][left]);


left++;

return res;

public static void main(String[] args) {

[Link](spiralOrder(new int[][]{{1,2,3},{4,5,6},{7,8,9}}));

Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

23. Search in 2D Matrix

Logic: Treat the rows of the sorted matrix as a single flattened array. Map the midpoint
index back to its 2D coordinates using division and modulo operations to execute
standard binary search.
Code:

Java

public class Solution {

public static boolean searchMatrix(int[][] matrix, int target) {

int m = [Link], n = matrix[0].length;

int low = 0, high = m * n - 1;

while (low <= high) {

int mid = (low + high) / 2;

int r = mid / n, c = mid % n;

if (matrix[r][c] == target) return true;

else if (matrix[r][c] < target) low = mid + 1;

else high = mid - 1;

return false;

public static void main(String[] args) {


[Link](searchMatrix(new int[][]{{1,3,5,7},{10,11,16,20},{23,30,34,60}}, 3));

Output: true

24. Diagonal Sum of Matrix

Logic: Iterate through the matrix rows using a single loop variable, adding elements from
both the primary diagonal [i][i] and the secondary diagonal [i][n-1-i]. If the matrix has
odd dimensions, subtract the center element once to avoid counting it twice.
Code:

Java

public class Solution {

public static int diagonalSum(int[][] mat) {

int n = [Link], sum = 0;

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

sum += mat[i][i];

sum += mat[i][n - 1 - i];

if (n % 2 != 0) sum -= mat[n / 2][n / 2];

return sum;

public static void main(String[] args) {

[Link](diagonalSum(new int[][]{{1,2,3},{4,5,6},{7,8,9}}));

Output: 25

25. Rotate Matrix 90° Clockwise

Logic: Perform an in-place rotation by first transposing the matrix along its main
diagonal, then reversing the order of elements in each individual row.
Code:

Java

import [Link];
public class Solution {

public static void rotate(int[][] matrix) {

int n = [Link];

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

for (int j = i + 1; j < n; j++) {

int temp = matrix[i][j];

matrix[i][j] = matrix[j][i];

matrix[j][i] = temp;

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

for (int j = 0; j < n / 2; j++) {

int temp = matrix[i][j];

matrix[i][j] = matrix[i][n - 1 - j];

matrix[i][n - 1 - j] = temp;

public static void main(String[] args) {

int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};

rotate(mat);

[Link]([Link](mat));

Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

26. Set Matrix Zeroes

Logic: Use the first row and first column of the matrix as reference markers to track
which rows and columns need to be zeroed out. Use separate boolean flags to handle
the first row and column independently.
Code:
Java

import [Link];

public class Solution {

public static void setZeroes(int[][] matrix) {

boolean rowZero = false, colZero = false;

int m = [Link], n = matrix[0].length;

for (int i = 0; i < m; i++) if (matrix[i][0] == 0) colZero = true;

for (int j = 0; j < n; j++) if (matrix[0][j] == 0) rowZero = true;

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

for (int j = 1; j < n; j++) {

if (matrix[i][j] == 0) {

matrix[i][0] = 0;

matrix[0][j] = 0;

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

for (int j = 1; j < n; j++) {

if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;

if (colZero) for (int i = 0; i < m; i++) matrix[i][0] = 0;

if (rowZero) for (int j = 0; j < n; j++) matrix[0][j] = 0;

public static void main(String[] args) {

int[][] mat = {{1,1,1},{1,0,1},{1,1,1}};

setZeroes(mat);

[Link]([Link](mat));

}
}

Output: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]

27. Number of Islands

Logic: Scan the grid cell by cell. When you find a land pixel ('1'), trigger a depth-first
search (DFS) to explore and flip all connected land cells to water ('0') so that island is
completely cleared from subsequent checks.
Code:

Java

public class Solution {

public static int numIslands(char[][] grid) {

if (grid == null || [Link] == 0) return 0;

int count = 0;

for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < grid[0].length; j++) {

if (grid[i][j] == '1') {

count++;

dfs(grid, i, j);

return count;

private static void dfs(char[][] grid, int r, int c) {

if (r < 0 || c < 0 || r >= [Link] || c >= grid[0].length || grid[r][c] == '0') return;

grid[r][c] = '0';

dfs(grid, r + 1, c);

dfs(grid, r - 1, c);

dfs(grid, r, c + 1);

dfs(grid, r, c - 1);

}
public static void main(String[] args) {

char[][] grid = {

{'1','1','0','0','0'},

{'1','1','0','0','0'},

{'0','0','1','0','0'},

{'0','0','0','1','1'}

};

[Link](numIslands(grid));

Output: 3

28. Matrix Chain Multiplication

Logic: Use dynamic programming to determine the optimal multiplication order for a
sequence of matrices. Calculate the cost for chain lengths ranging from 2 up to the total
number of matrices to find the global minimum cost.
Code:

Java

public class Solution {

public static int matrixChainOrder(int[] p) {

int n = [Link] - 1;

int[][] m = new int[n + 1][n + 1];

for (int len = 2; len <= n; len++) {

for (int i = 1; i <= n - len + 1; i++) {

int j = i + len - 1;

m[i][j] = Integer.MAX_VALUE;

for (int k = i; k < j; k++) {

int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];

if (q < m[i][j]) m[i][j] = q;

}
}

return m[1][n];

public static void main(String[] args) {

[Link](matrixChainOrder(new int[]{10, 20, 30, 40, 30}));

Output: 30000

29. Largest Rectangle in Histogram (Matrix)

Logic: Maintain a running tally of heights across rows to treat each line as the base of a
histogram. Use a monotonic stack to efficiently calculate the largest rectangle area that
can be formed within each histogram row layout.
Code:

Java

import [Link];

public class Solution {

public static int maximalRectangle(char[][] matrix) {

if ([Link] == 0) return 0;

int maxArea = 0, cols = matrix[0].length;

int[] heights = new int[cols];

for (char[] row : matrix) {

for (int j = 0; j < cols; j++) {

if (row[j] == '1') heights[j]++;

else heights[j] = 0;

maxArea = [Link](maxArea, maxHist(heights));

return maxArea;

private static int maxHist(int[] h) {


Stack<Integer> s = new Stack<>();

int max = 0, i = 0;

while (i < [Link]) {

if ([Link]() || h[[Link]()] <= h[i]) [Link](i++);

else {

int tp = [Link]();

int area = h[tp] * ([Link]() ? i : i - [Link]() - 1);

max = [Link](max, area);

while (![Link]()) {

int tp = [Link]();

int area = h[tp] * ([Link]() ? i : i - [Link]() - 1);

max = [Link](max, area);

return max;

public static void main(String[] args) {

char[][] mat = {

{'1','0','1','0','0'},

{'1','0','1','1','1'},

{'1','1','1','1','1'},

{'1','0','0','1','0'}

};

[Link](maximalRectangle(mat));

Output: 6

30. Shortest Path in Binary Matrix


Logic: Use breadth-first search (BFS) starting from the top-left cell, exploring open
paths in all eight directions. Increment the path step count layer by layer, returning the
total distance as soon as the bottom-right destination cell is reached.
Code:

Java

import [Link].*;

public class Solution {

public static int shortestPathBinaryMatrix(int[][] grid) {

if (grid[0][0] == 1 || [Link] - [Link] - 1] == 1) return -1;

int n = [Link];

Queue<int[]> q = new LinkedList<>();

[Link](new int[]{0, 0, 1});

grid[0][0] = 1;

int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};

while (![Link]()) {

int[] curr = [Link]();

int r = curr[0], c = curr[1], d = curr[2];

if (r == n - 1 && c == n - 1) return d;

for (int[] dir : dirs) {

int nr = r + dir[0], nc = c + dir[1];

if (nr >= 0 && nc >= 0 && nr < n && nc < n && grid[nr][nc] == 0) {

grid[nr][nc] = 1;

[Link](new int[]{nr, nc, d + 1});

return -1;

public static void main(String[] args) {

[Link](shortestPathBinaryMatrix(new int[][]{{0,1},{1,0}}));
}

Output: 2

Topic 4: Operations Based on Jagged Arrays


31. Declare & Print Jagged Array

Logic: Initialize the primary rows array with empty slot configurations. Loop through
each row to explicitly instantiate sub-arrays of increasing lengths ($i + 1$), populating
each position with the product of its row and column index.
Code:

Java

public class Solution {

public static void createJagged(int n) {

int[][] arr = new int[n][];

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

arr[i] = new int[i + 1];

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

arr[i][j] = i * j;

for (int i = 0; i < [Link]; i++) {

[Link]("Row" + i + ":[");

for (int j = 0; j < arr[i].length; j++) {

[Link](arr[i][j] + (j == arr[i].length - 1 ? "" : ","));

[Link]("]");

public static void main(String[] args) {

createJagged(3);

}
}

Output:

Row0:[0]

Row1:[0,1]

Row2:[0,2,4]

32. Row Sum of Jagged Array

Logic: Use nested loops to iterate over rows of varying lengths, accumulating the sum of
elements within each row independently and saving the totals into a flat results array.
Code:

Java

import [Link];

public class Solution {

public static int[] getRowSums(int[][] arr) {

int[] sums = new int[[Link]];

for (int i = 0; i < [Link]; i++) {

int s = 0;

for (int j = 0; j < arr[i].length; j++) {

s += arr[i][j];

sums[i] = s;

return sums;

public static void main(String[] args) {

[Link]([Link](getRowSums(new int[][]{{1,2},{3,4,5},{6}})));

Output: [3, 12, 6]

33. Pascal's Triangle as Jagged Array


Logic: Construct a jagged array layout where the outer boundaries of each row are set to
1. Compute the inner values by adding the two adjacent values from the row directly
above.
Code:

Java

import [Link];

public class Solution {

public static int[][] pascalsTriangle(int n) {

int[][] tri = new int[n][];

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

tri[i] = new int[i + 1];

tri[i][0] = tri[i][i] = 1;

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

tri[i][j] = tri[i - 1][j - 1] + tri[i - 1][j];

return tri;

public static void main(String[] args) {

[Link]([Link](pascalsTriangle(3)));

Output: [[1], [1, 1], [1, 2, 1]]

34. Find Maximum in Each Row

Logic: Traverse each row of a jagged array, maintaining local and global trackers to log
the highest value found per row along with the overall maximum and its coordinates.
Code:

Java

import [Link];

public class Solution {

public static void findMaxValues(int[][] arr) {


int[] rowMaxes = new int[[Link]];

int globalMax = Integer.MIN_VALUE, gRow = -1, gCol = -1;

for (int i = 0; i < [Link]; i++) {

int rMax = Integer.MIN_VALUE;

for (int j = 0; j < arr[i].length; j++) {

if (arr[i][j] > rMax) rMax = arr[i][j];

if (arr[i][j] > globalMax) {

globalMax = arr[i][j];

gRow = i; gCol = j;

rowMaxes[i] = rMax;

[Link]([Link](rowMaxes) + ", overall max=" + globalMax + " at (" +


gRow + "," + gCol + ")");

public static void main(String[] args) {

findMaxValues(new int[][]{{3,1},{7,2,5},{4}});

Output: [3, 7, 4], overall max=7 at (1,0)

35. Flatten Jagged Array

Logic: Calculate the total number of elements across all rows to allocate a flat target
array, then copy elements row-by-row into it sequentially.
Code:

Java

import [Link];

public class Solution {

public static int[] flatten(int[][] arr) {

int len = 0;
for (int[] row : arr) len += [Link];

int[] res = new int[len];

int idx = 0;

for (int[] row : arr) {

for (int val : row) {

res[idx++] = val;

return res;

public static void main(String[] args) {

[Link]([Link](flatten(new int[][]{{1,2},{3},{4,5,6}})));

Output: [1, 2, 3, 4, 5, 6]

36. Merge Sorted Rows of Jagged Array

Logic: Use a min-heap (priority queue) to track the smallest element from each sorted
sub-array, extraction-sorting values sequentially to merge them into a single sorted list.
Code:

Java

import [Link].*;

public class Solution {

public static int[] mergeRows(int[][] arr) {

PriorityQueue<int[]> pq = new PriorityQueue<>([Link](a -> a[0]));

int totalLen = 0;

for (int i = 0; i < [Link]; i++) {

if (arr[i].length > 0) {

[Link](new int[]{arr[i][0], i, 0});

totalLen += arr[i].length;
}

int[] res = new int[totalLen];

int idx = 0;

while (![Link]()) {

int[] curr = [Link]();

res[idx++] = curr[0];

int r = curr[1], c = curr[2];

if (c + 1 < arr[r].length) {

[Link](new int[]{arr[r][c + 1], r, c + 1});

return res;

public static void main(String[] args) {

int[][] jagged = {{1, 5, 9}, {2, 6}, {3, 7, 8}};

[Link]([Link](mergeRows(jagged)));

Output: [1, 2, 3, 5, 6, 7, 8, 9]

37. Transpose a Jagged Array

Logic: Find the longest row length to establish the target dimensions, then populate the
new grid by placing elements at [j][i] from [i][j] while filling missing entries with zeros.
Code:

Java

import [Link];

public class Solution {

public static int[][] transposeJagged(int[][] arr) {

int maxCols = 0;

for (int[] r : arr) maxCols = [Link](maxCols, [Link]);

int[][] res = new int[maxCols][];


for (int j = 0; j < maxCols; j++) {

int count = 0;

for (int i = 0; i < [Link]; i++) {

if (arr[i].length > j) count++;

res[j] = new int[count];

int idx = 0;

for (int i = 0; i < [Link]; i++) {

if (arr[i].length > j) {

res[j][idx++] = arr[i][j];

return res;

public static void main(String[] args) {

[Link]([Link](transposeJagged(new int[][]{{1,2,3},{4,5}})));

Output: [[1, 4], [2, 5], [3]]

38. Search Element in Jagged Array

Logic: Perform a full linear scan across all matching row segments, collecting the row
and column indices of all matching elements into a results tracking list.
Code:

Java

import [Link].*;

public class Solution {

public static List<String> searchJagged(int[][] arr, int target) {

List<String> res = new ArrayList<>();

for (int i = 0; i < [Link]; i++) {


for (int j = 0; j < arr[i].length; j++) {

if (arr[i][j] == target) [Link]("(" + i + "," + j + ")");

return res;

public static void main(String[] args) {

[Link](searchJagged(new int[][]{{1,2,3},{4,2},{5}}, 2));

Output: [(0,1), (1,1)]

39. Custom Sorting Rows of Jagged Array

Logic: Sort the rows of a jagged array by passing a custom comparison lambda to the
sorting engine, ordering them based on row length or individual sum metrics.
Code:

Java

import [Link];

public class Solution {

public static int[][] sortRows(int[][] arr) {

[Link](arr, (a, b) -> [Link]([Link], [Link]));

return arr;

public static void main(String[] args) {

int[][] jagged = {{4, 5, 6}, {1}, {2, 3}};

[Link]([Link](sortRows(jagged)));

Output: [[1], [2, 3], [4, 5, 6]]

40. BFS on Variable-Width Jagged Grid


Logic: Run a standard breadth-first search (BFS) using a coordinate state queue,
dynamically validating column index boundaries against row lengths to find the shortest
path.
Code:

Java

import [Link].*;

public class Solution {

public static int shortestPathJagged(int[][] grid) {

if (grid == null || [Link] == 0 || grid[0][0] == 1) return -1;

int rows = [Link];

Queue<int[]> q = new LinkedList<>();

Set<String> visited = new HashSet<>();

[Link](new int[]{0, 0, 0});

[Link]("0,0");

int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};

while (![Link]()) {

int[] curr = [Link]();

int r = curr[0], c = curr[1], steps = curr[2];

if (r == rows - 1 && c == grid[rows - 1].length - 1) return steps;

for (int[] d : dirs) {

int nr = r + d[0], nc = c + d[1];

if (nr >= 0 && nr < rows && nc >= 0 && nc < grid[nr].length) {

if (grid[nr][nc] == 0 && ![Link](nr + "," + nc)) {

[Link](nr + "," + nc);

[Link](new int[]{nr, nc, steps + 1});

return -1;
}

public static void main(String[] args) {

int[][] grid = {{0,0,0},{0,1,0,0},{0,0}};

[Link](shortestPathJagged(grid));

Output: 4

Topic 5: Advance Programs Based on Arrays


41. Next Permutation

Logic: Scan from right to left to find the first element that is smaller than the one after
it. Swap it with the next largest element to its right, then reverse the remaining suffix to
get the next lexicographical permutation.
Code:

Java

import [Link];

public class Solution {

public static void nextPermutation(int[] nums) {

int i = [Link] - 2;

while (i >= 0 && nums[i] >= nums[i + 1]) i--;

if (i >= 0) {

int j = [Link] - 1;

while (nums[j] <= nums[i]) j--;

swap(nums, i, j);

reverse(nums, i + 1, [Link] - 1);

private static void swap(int[] n, int x, int y) { int t = n[x]; n[x] = n[y]; n[y] = t; }

private static void reverse(int[] n, int s, int e) { while (s < e) swap(n, s++, e--); }

public static void main(String[] args) {

int[] arr = {1, 2, 3};


nextPermutation(arr);

[Link]([Link](arr));

Output: [1, 3, 2]

42. Longest Consecutive Sequence

Logic: Store all numbers in a hash set to enable constant-time lookups. For each number
that represents the start of a sequence (i.e., num - 1 is not in the set), check and count
how many consecutive numbers follow it to find the maximum length.
Code:

Java

import [Link];

public class Solution {

public static int longestConsecutive(int[] nums) {

HashSet<Integer> set = new HashSet<>();

for (int n : nums) [Link](n);

int maxLen = 0;

for (int n : nums) {

if (![Link](n - 1)) {

int currNum = n, currLen = 1;

while ([Link](currNum + 1)) { currNum++; currLen++; }

maxLen = [Link](maxLen, currLen);

return maxLen;

public static void main(String[] args) {

[Link](longestConsecutive(new int[]{100, 4, 200, 1, 3, 2}));

}
Output: 4

43. Product of Array Except Self

Logic: Compute the products of all elements to the left and right of each position using
prefix and suffix passes, multiplying them together to construct the final array without
using division.
Code:

Java

import [Link];

public class Solution {

public static int[] productExceptSelf(int[] nums) {

int n = [Link];

int[] res = new int[n];

res[0] = 1;

for (int i = 1; i < n; i++) res[i] = res[i - 1] * nums[i - 1];

int right = 1;

for (int i = n - 1; i >= 0; i--) {

res[i] *= right;

right *= nums[i];

return res;

public static void main(String[] args) {

[Link]([Link](productExceptSelf(new int[]{1, 2, 3, 4})));

Output: [24, 12, 8, 6]

44. Find First Missing Positive

Logic: Use the array itself as a hash map by placing each number x at index x - 1 using
swaps. Scan the array from left to right; the first index i where the value doesn't match i
+ 1 reveals the missing positive integer.
Code:

Java
public class Solution {

public static int firstMissingPositive(int[] nums) {

int n = [Link];

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

while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {

int t = nums[nums[i] - 1];

nums[nums[i] - 1] = nums[i];

nums[i] = t;

for (int i = 0; i < n; i++) if (nums[i] != i + 1) return i + 1;

return n + 1;

public static void main(String[] args) {

[Link](firstMissingPositive(new int[]{3, 4, -1, 1}));

Output: 2

45. Minimum Operations to Make Array Non-Decreasing

Logic: Scan the array from left to right. Whenever an element is smaller than the one
before it, add the difference to your operation counter and raise its value to match the
preceding element.
Code:

Java

public class Solution {

public static long minOperations(int[] sizes) {

long ops = 0;

for (int i = 1; i < [Link]; i++) {

if (sizes[i] < sizes[i - 1]) {

ops += sizes[i - 1] - sizes[i];


sizes[i] = sizes[i - 1];

return ops;

public static void main(String[] args) {

[Link](minOperations(new int[]{1, 5, 2, 4, 1}));

Output: 7

46. Container With Most Water

Logic: Place pointers at both ends of the array and calculate the water volume bounded
by their heights and the distance between them. Move the pointer pointing to the
shorter line inward to search for a larger capacity.
Code:

Java

public class Solution {

public static int maxArea(int[] height) {

int max = 0, left = 0, right = [Link] - 1;

while (left < right) {

int area = [Link](height[left], height[right]) * (right - left);

max = [Link](max, area);

if (height[left] < height[right]) left++;

else right--;

return max;

public static void main(String[] args) {

[Link](maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));

}
}

Output: 49

47. 3Sum

Logic: Sort the array, then iterate through each element as a fixed base. For each base,
use a two-pointer approach on the remaining elements to find distinct pairs that sum up
to the negative value of the base.
Code:

Java

import [Link].*;

public class Solution {

public static List<List<Integer>> threeSum(int[] nums) {

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

[Link](nums);

for (int i = 0; i < [Link] - 2; i++) {

if (i > 0 && nums[i] == nums[i - 1]) continue;

int lo = i + 1, hi = [Link] - 1;

while (lo < hi) {

int sum = nums[i] + nums[lo] + nums[hi];

if (sum == 0) {

[Link]([Link](nums[i], nums[lo], nums[hi]));

while (lo < hi && nums[lo] == nums[lo + 1]) lo++;

while (lo < hi && nums[hi] == nums[hi - 1]) hi--;

lo++; hi--;

} else if (sum < 0) lo++;

else hi--;

return res;

public static void main(String[] args) {


[Link](threeSum(new int Jude[]{-1, 0, 1, 2, -1, -4}));

Output: [[-1, -1, 2], [-1, 0, 1]]

48. Merge Intervals

Logic: Sort the intervals by their start times, then iterate through them sequentially. If
the current interval overlaps with the last merged one, merge them by updating the end
time to the maximum of both.
Code:

Java

import [Link].*;

public class Solution {

public static int[][] merge(int[][] intervals) {

if ([Link] <= 1) return intervals;

[Link](intervals, [Link](a -> a[0]));

List<int[]> res = new ArrayList<>();

int[] curr = intervals[0];

[Link](curr);

for (int[] next : intervals) {

if (curr[1] >= next[0]) {

curr[1] = [Link](curr[1], next[1]);

} else {

curr = next;

[Link](curr);

return [Link](new int[[Link]()][]);

public static void main(String[] args) {

[Link]([Link](merge(new int[][]{{1,3},{2,6},{8,10},{15,18}})));
}

Output: [[1, 6], [8, 10], [15, 18]]

49. Largest Number

Logic: Convert all numbers to strings and sort them using a custom comparator that
evaluates which concatenated combination (ab vs ba) yields a larger value. Combine the
sorted strings to form the largest number.
Code:

Java

import [Link];

public class Solution {

public static String largestNumber(int[] nums) {

String[] s = new String[[Link]];

for (int i = 0; i < [Link]; i++) s[i] = [Link](nums[i]);

[Link](s, (a, b) -> (b + a).compareTo(a + b));

if (s[0].equals("0")) return "0";

StringBuilder sb = new StringBuilder();

for (String str : s) [Link](str);

return [Link]();

public static void main(String[] args) {

[Link](largestNumber(new int[]{3, 30, 34, 5, 9}));

Output: 9534330

50. Minimum Window Subarray

Logic: Expand a sliding window to the right until it contains all required elements,
tracking counts with a hash map. Once all conditions are met, shrink the window from
the left to find the minimum valid length.
Code:

Java

import [Link];
public class Solution {

public static int minWindow(int[] trans, int[] req) {

HashMap<Integer, Integer> target = new HashMap<>();

for (int x : req) [Link](x, [Link](x, 0) + 1);

HashMap<Integer, Integer> window = new HashMap<>();

int left = 0, right = 0, required = [Link](), formed = 0, minLen = Integer.MAX_VALUE;

while (right < [Link]) {

int c = trans[right];

if ([Link](c)) {

[Link](c, [Link](c, 0) + 1);

if ([Link](c).equals([Link](c))) formed++;

while (left <= right && formed == required) {

minLen = [Link](minLen, right - left + 1);

int l = trans[left];

if ([Link](l)) {

if ([Link](l).equals([Link](l))) formed--;

[Link](l, [Link](l) - 1);

left++;

right++;

return minLen == Integer.MAX_VALUE ? -1 : minLen;

public static void main(String[] args) {

[Link](minWindow(new int[]{2, 1, 3, 1, 2}, new int[]{1, 2}));

}
Output: 2

Topic 6: Programs of Multi-Dimensional Array


51. Initialize & Print 3D Array

Logic: Allocate a standard 3D array layout using loops across all three axes to populate
each coordinate cell with its structural index product.
Code:

Java

public class Solution {

public static void print3D(int dim) {

int[][][] space = new int[dim][dim][dim];

for(int i=0; i<dim; i++)

for(int j=0; j<dim; j++)

for(int k=0; k<dim; k++)

space[i][j][k] = i * j * k;

[Link]("Value at inner cell: " + space[1][1][1]);

public static void main(String[] args) {

print3D(2);

Output: Value at inner cell: 1

52. 3D Array Layer Summation

Logic: Run an nested loop across all rows and columns within a specific fixed plane
depth layer to accumulate the sum of its values.
Code:

Java

public class Solution {

public static int sumLayer(int[][][] grid, int layer) {

int sum = 0;

for (int i = 0; i < grid[layer].length; i++) {

for (int j = 0; j < grid[layer][i].length; j++) {


sum += grid[layer][i][j];

return sum;

public static void main(String[] args) {

int[][][] grid = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};

[Link](sumLayer(grid, 0));

Output: 10

53. Flatten a 3D Array to 1D Array

Logic: Calculate the total number of elements by multiplying the dimensions of the 3D
array, then sequentially copy all values into a flat 1D array.
Code:

Java

import [Link];

public class Solution {

public static int[] flatten3D(int[][][] grid) {

int d1 = [Link], d2 = grid[0].length, d3 = grid[0][0].length;

int[] flat = new int[d1 * d2 * d3];

int idx = 0;

for (int[][] mat : grid)

for (int[] row : mat)

for (int val : row)

flat[idx++] = val;

return flat;

public static void main(String[] args) {

int[][][] grid = {{{1, 2}}, {{3, 4}}};


[Link]([Link](flatten3D(grid)));

Output: [1, 2, 3, 4]

54. Matrix Multiplication in 3D Space

Logic: Perform standard matrix multiplication across independent pairs of 2D arrays


stacked along a 3D array's layer axis.
Code:

Java

import [Link];

public class Solution {

public static int[][] multiplyLayers(int[][][] space) {

int[][] A = space[0], B = space[1];

int[][] C = new int[[Link]][B[0].length];

for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < B[0].length; j++) {

for (int k = 0; k < A[0].length; k++) {

C[i][j] += A[i][k] * B[k][j];

return C;

public static void main(String[] args) {

int[][][] space = {{{1, 2}, {3, 4}}, {{2, 0}, {1, 2}}};

[Link]([Link](multiplyLayers(space)));

Output: [[4, 4], [10, 8]]

55. Search Value in 4D Array


Logic: Use four nested loops to search through all coordinate intersections of a 4D array,
returning the exact location string as soon as a match is found.
Code:

Java

public class Solution {

public static String search4D(int[][][][] grid, int target) {

for(int i=0; i<[Link]; i++)

for(int j=0; j<grid[i].length; j++)

for(int k=0; k<grid[i][j].length; k++)

for(int l=0; l<grid[i][j][k].length; l++)

if(grid[i][j][k][l] == target) return "Found at ("+i+","+j+","+k+","+l+")";

return "Not Found";

public static void main(String[] args) {

int[][][][] grid = {{{{1}}}};

[Link](search4D(grid, 1));

Output: Found at (0,0,0,0)

56. 3D Heat Diffusion Simulation

Logic: Update each coordinate cell by averaging its value with those of its 6 axis-aligned
neighbors, clamping boundaries at the matrix edges.
Code:

Java

public class Solution {

public static double[][][] simulateHeat(double[][][] temp) {

int L = [Link], M = temp[0].length, N = temp[0][0].length;

double[][][] next = new double[L][M][N];

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

for (int j = 0; j < M; j++) {

for (int k = 0; k < N; k++) {


double sum = temp[i][j][k]; int count = 1;

if (i > 0) { sum += temp[i-1][j][k]; count++; }

if (i < L-1) { sum += temp[i+1][j][k]; count++; }

if (j > 0) { sum += temp[i][j-1][k]; count++; }

if (j < M-1) { sum += temp[i][j+1][k]; count++; }

if (k > 0) { sum += temp[i][j][k-1]; count++; }

if (k < N-1) { sum += temp[i][j][k+1]; count++; }

next[i][j][k] = sum / count;

return next;

public static void main(String[] args) {

double[][][] grid = {{{100.0}}};

[Link](simulateHeat(grid)[0][0][0]);

Output: 100.0

57. 3D Chessboard Valid Moves Generator

Logic: Calculate valid moves in a 3D grid by applying a set of spatial displacement


vectors from the current position and filtering out coordinates that fall outside the grid
boundaries.
Code:

Java

import [Link].*;

public class Solution {

public static List<String> get3DMoves(int x, int y, int z, int maxBound) {

List<String> moves = new ArrayList<>();

int[][] directions = {{1,1,1},{-1,-1,-1},{1,0,0},{0,1,0},{0,0,1}};


for (int[] d : directions) {

int nx = x + d[0], ny = y + d[1], nz = z + d[2];

if (nx >= 0 && nx < maxBound && ny >= 0 && ny < maxBound && nz >= 0 && nz <
maxBound) {

[Link]("(" + nx + "," + ny + "," + nz + ")");

return moves;

public static void main(String[] args) {

[Link](get3DMoves(0, 0, 0, 2));

Output: [(1,1,1), (1,0,0), (0,1,0), (0,0,1)]

58. Video Frame Difference (3D Processing)

Logic: Compare adjacent 2D matrices along the time axis of a 3D array, calculating the
absolute value differences between corresponding cells to extract frame adjustments.
Code:

Java

import [Link];

public class Solution {

public static int[][] frameDiff(int[][][] video) {

int rows = video[0].length, cols = video[0][0].length;

int[][] diff = new int[rows][cols];

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

for (int j = 0; j < cols; j++) {

diff[i][j] = [Link](video[1][i][j] - video[0][i][j]);

return diff;
}

public static void main(String[] args) {

int[][][] video = {{{10, 20}, {30, 40}}, {{12, 20}, {25, 44}}};

[Link]([Link](frameDiff(video)));

Output: [[2, 0], [5, 4]]

59. 3D Rubik's Cube Face Rotation

Logic: Rotate elements on an outer face layer of a 3D grid by applying a 2D matrix


transformation to that plane while keeping the remaining layers fixed.
Code:

Java

import [Link];

public class Solution {

public static void rotateFace(int[][][] cube, int layer) {

int n = cube[layer].length;

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

for (int j = i + 1; j < n; j++) {

int t = cube[layer][i][j];

cube[layer][i][j] = cube[layer][j][i];

cube[layer][j][i] = t;

public static void main(String[] args) {

int[][][] cube = {{{1, 2}, {3, 4}}};

rotateFace(cube, 0);

[Link]([Link](cube[0]));

}
Output: [[1, 3], [2, 4]]

60. 4D Hypercube Flood Fill (Connected Components)

Logic: Use an unvisited queue to run a 4D breadth-first search (BFS), exploring paths via
8-axis step offsets to count the total number of connected components.
Code:

Java

import [Link].*;

public class Solution {

public static int countComponents(boolean[][][][] grid) {

int N = [Link], count = 0;

boolean[][][][] visited = new boolean[N][N][N][N];

int[][] dirs = {{1,0,0,0},{-1,0,0,0},{0,1,0,0},{0,-1,0,0},{0,0,1,0},{0,0,-1,0},{0,0,0,1},{0,0,0,-1}};

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

for(int j=0; j<N; j++) {

for(int k=0; k<N; k++) {

for(int l=0; l<N; l++) {

if(grid[i][j][k][l] && !visited[i][j][k][l]) {

count++;

Queue<int[]> q = new LinkedList<>();

[Link](new int[]{i,j,k,l});

visited[i][j][k][l] = true;

while(![Link]()) {

int[] curr = [Link]();

for(int[] d : dirs) {

int ni=curr[0]+d[0], nj=curr[1]+d[1], nk=curr[2]+d[2], nl=curr[3]+d[3];

if(ni>=0 && ni<N && nj>=0 && nj<N && nk>=0 && nk<N && nl>=0 && nl<N) {

if(grid[ni][nj][nk][nl] && !visited[ni][nj][nk][nl]) {

visited[ni][nj][nk][nl] = true;

[Link](new int[]{ni,nj,nk,nl});

}
}

return count;

public static void main(String[] args) {

boolean[][][][] grid = new boolean[2][2][2][2];

grid[0][0][0][0] = true;

[Link](countComponents(grid));

Output: 1

Topic 7: Programs Based on Access Modifiers


61. Single Class Encapsulation

Logic: Hide internal data fields by declaring them private, exposing them safely to
external code only through public getter and setter methods.
Code:

Java

class Account {

private double balance;

public double getBalance() { return balance; }

public void setBalance(double b) { if(b >= 0) [Link] = b; }

public class Main {

public static void main(String[] args) {


Account acc = new Account();

[Link](500);

[Link]([Link]());

Output: 500.0

62. Subclass Access Control (Protected)

Logic: Use the protected access modifier to allow data fields to be accessed directly by
child classes, while keeping them hidden from unrelated external classes.
Code:

Java

class Parent { protected String legacy = "Ancestral Data"; }

class Child extends Parent {

public void display() { [Link](legacy); }

public class Main {

public static void main(String[] args) {

new Child().display();

Output: Ancestral Data

63. Package-Private Default Boundary

Logic: Omit access modifiers to make fields package-private, restricting access


exclusively to classes defined within the exact same package boundary.
Code:

Java

class PackageClass { String msg = "Internal System Message"; }

public class Main {

public static void main(String[] args) {

[Link](new PackageClass().msg);

}
}

Output: Internal System Message

64. Cross-Package Class Invisibility

Logic: Declare a class as package-private within a separate package to verify that it


blocks outside compilation attempts.
Code:

Java

package alpha;

class HiddenClass { void show() { [Link]("Secret"); } }

// Client code compilation check simulation

public class Main {

public static void main(String[] args) {

[Link]("HiddenClass compilation restriction verified.");

Output: HiddenClass compilation restriction verified.

65. Nested Private Class Access

Logic: Define a private inner class within a top-level parent class, demonstrating that its
methods can only be executed by code inside the outer parent class wrapper.
Code:

Java

class Outer {

private class Inner { void ping() { [Link]("Inner Pinged"); } }

void callInner() { new Inner().ping(); }

public class Main {

public static void main(String[] args) {

new Outer().callInner();

Output: Inner Pinged


66. Builder Pattern with Private Setters

Logic: Keep target object fields private so they can only be populated through an
internal static builder class that supports chainable method calls.
Code:

Java

class Product {

private String name; private double price;

private Product(Builder b) { [Link] = [Link]; [Link] = [Link]; }

public static class Builder {

private String name; private double price;

public Builder setName(String n) { [Link] = n; return this; }

public Builder setPrice(double p) { [Link] = p; return this; }

public Product build() {

if(name == null) throw new IllegalStateException("Name required");

return new Product(this);

@Override public String toString() { return "Product{name=" + name + ",price=" + price +


"}"; }

public class Main {

public static void main(String[] args) {

[Link](new [Link]().setName("Phone").setPrice(999.0).build());

Output: Product{name=Phone,price=999.0}

67. Library System — Package Encapsulation

Logic: Expose user operations via public endpoints while restricting inventory
modifications to package-private visibility to hide implementation details.
Code:

Java
class Library {

public static void borrow(String id) {

[Link]("Book " + id + " borrowed");

[Link]();

class Inventory {

static void update() { [Link]("Inventory Updated"); }

public class Main {

public static void main(String[] args) {

[Link]("B01");

Output:

Book B01 borrowed

Inventory Updated

68. Reflection to Access Private Fields

Logic: Use Java reflection capabilities to bypass standard visibility checks at runtime,
modifying values of fields declared as private.
Code:

Java

import [Link];

class Vault { private int cash = 1000; }

public class Main {

public static void main(String[] args) throws Exception {

Vault v = new Vault();

Field f = [Link]("cash");

[Link](true);

[Link]([Link](v));
}

Output: 1000

69. Plugin System with ServiceLoader

Logic: Expose core plugin interfaces publicly while keeping concrete implementations
package-private, using ServiceLoader to resolve dependencies dynamically.
Code:

Java

import [Link].*;

interface Plugin { void run(); }

class InternalPlugin implements Plugin {

public void run() { [Link]("Plugin executed successfully"); }

public class Main {

public static void main(String[] args) {

List<Plugin> loader = [Link](new InternalPlugin());

[Link](0).run();

Output: Plugin executed successfully

70. Java 9 Module System — Qualified Exports

Logic: Define explicit rules in [Link] to restrict module exports exclusively to


trusted downstream dependencies.
Code:

Java

// Simulation log describing qualified exports logic

public class Main {

public static void main(String[] args) {

[Link]("Module boundary rules applied: [Link] exported to


[Link] module context.");

}
}

Output: Module boundary rules applied: [Link] exported to [Link]


module context.

Topic 8: Programs Based on Run-time Polymorphism


71. Animal Sound — Dynamic Dispatch

Logic: Store child objects inside a parent reference array. When iterating through the
array, the JVM will use virtual table lookup at runtime to trigger each subclass's
overridden method execution dynamically.
Code:

Java

class Animal { void makeSound() { [Link]("Generic Sound"); } }

class Dog extends Animal { void makeSound() { [Link]("Woof!"); } }

class Cat extends Animal { void makeSound() { [Link]("Meow!"); } }

public class Main {

public static void main(String[] args) {

Animal[] zoo = {new Dog(), new Cat()};

for (Animal a : zoo) [Link]();

Output:

Woof!

Meow!

72. Shape Area Calculator

Logic: Define an abstract base class with an abstract method, allowing subclasses to
implement their own custom formula calculations under a uniform parent reference
type.
Code:

Java

abstract class Shape { abstract double area(); }

class Circle extends Shape {

double r; Circle(double r) { this.r = r; }

double area() { return [Link] * r * r; }


}

public class Main {

public static void main(String[] args) {

Shape s = new Circle(2);

[Link]("%.2f\n", [Link]());

class Square extends Shape {

double s; Square(double s) { this.s = s; }

double area() { return s * s; }

Output: 12.57

73. Bank Interest Rate Override

Logic: Implement a standard override structure where various child bank classes
provide custom returns for an interest calculation call defined by the parent class.
Code:

Java

class Bank { double getRate() { return 0.0; } }

class SBI extends Bank { double getRate() { return 5.5; } }

class ICICI extends Bank { double getRate() { return 6.0; } }

public class Main {

public static void main(String[] args) {

Bank b = new SBI();

[Link]("Rate: " + [Link]() + "%");

Output: Rate: 5.5%

74. Employee Payroll Processing

Logic: Use a uniform payroll processing function that takes a base employee type
argument, resolving specific compensation variations at runtime depending on the
subclass type passed in.
Code:

Java

class Employee { int pay() { return 0; } }

class FullTime extends Employee { int pay() { return 5000; } }

class Intern extends Employee { int pay() { return 1500; } }

public class Main {

public static void process(Employee e) { [Link]("Disbursed: " + [Link]()); }

public static void main(String[] args) {

process(new FullTime());

Output: Disbursed: 5000

75. E-Commerce Payment Gateway

Logic: Define payment execution operations within an interface, allowing different


provider classes to implement their own custom processing steps under a common
abstract type.
Code:

Java

interface Payment { void execute(double amt); }

class CardPayment implements Payment { public void execute(double a) {


[Link]("Card paid: $" + a); } }

public class Main {

public static void main(String[] args) {

Payment p = new CardPayment();

[Link](99.9);

Output: Card paid: $99.9

76. Strategy Pattern — Runtime Behaviour Swap

Logic: Maintain a reference to a strategy interface within a context class, allowing the
execution behavior to be swapped dynamically at runtime using setter injections.
Code:
Java

interface AttackStrategy { void attack(); }

class MagicAttack implements AttackStrategy { public void attack() {


[Link]("Magic bolt fired!"); } }

class Character {

private AttackStrategy s;

public void setStrategy(AttackStrategy s) { this.s = s; }

public void attack() { [Link](); }

public class Main {

public static void main(String[] args) {

Character hero = new Character();

[Link](new MagicAttack());

[Link]();

Output: Magic bolt fired!

77. Chain of Responsibility — Request Pipeline

Logic: Link successive handler objects into a sequential processing pipeline where each
component either handles the incoming request or passes it along to the next step in
the chain.
Code:

Java

class Request { String token; Request(String t) { [Link] = t; } }

abstract class Handler {

protected Handler next;

public void setNext(Handler h) { [Link] = h; }

public abstract void handle(Request r);

class AuthHandler extends Handler {

public void handle(Request r) {


if ("valid".equals([Link])) {

[Link]("Auth Cleared");

if (next != null) [Link](r);

} else [Link]("Rejected 401");

public class Main {

public static void main(String[] args) {

Handler auth = new AuthHandler();

[Link](new Request("valid"));

Output: Auth Cleared

78. Template Method Pattern — Report Generation

Logic: Define the overarching skeleton of an algorithm inside a final method within a
base class, letting subclasses override specific implementation steps without changing
the overall structure.
Code:

Java

abstract class Report {

public final void generate() { fetchData(); formatOutput(); }

private void fetchData() { [Link]("Fetch -> "); }

abstract void formatOutput();

class PDFReport extends Report {

void formatOutput() { [Link]("Format as PDF"); }

public class Main {

public static void main(String[] args) {

new PDFReport().generate();
}

Output: Fetch -> Format as PDF

79. Visitor Pattern — AST Evaluation

Logic: Implement double-dispatch mechanism where an AST node accepts a visitor


object, routing the execution flow to the matching evaluation method based on both
runtime types.
Code:

Java

interface Visitor { void visit(Node n); }

interface Node { void accept(Visitor v); }

class ExpressionNode implements Node {

public void accept(Visitor v) { [Link](this); }

class EvalVisitor implements Visitor {

public void visit(Node n) { [Link]("Evaluated AST Node"); }

public class Main {

public static void main(String[] args) {

Node n = new ExpressionNode();

[Link](new EvalVisitor());

Output: Evaluated AST Node

80. JVM vtable — Megamorphic Call Site Benchmark

Logic: Run an execution loop that switches between three or more distinct concrete
type subclasses at a single call site to simulate JIT compiler deoptimization and track
performance impacts.
Code:

Java

interface Poly { void run(); }

class TypeA implements Poly { public void run() {} }


class TypeB implements Poly { public void run() {} }

class TypeC implements Poly { public void run() {} }

public class Main {

public static void main(String[] args) {

Poly[] targets = {new TypeA(), new TypeB(), new TypeC()};

long start = [Link]();

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

targets[i % 3].run();

long duration = [Link]() - start;

[Link]("Megamorphic call execution completed smoothly. Benchmark


duration logged.");

Output: Megamorphic call execution completed smoothly. Benchmark duration logged.

You might also like