0% found this document useful (0 votes)
3 views83 pages

Java Complete Scenario Question Bank

The document is a comprehensive Java interview question bank that includes 80 questions across 8 topics, categorized by difficulty level (easy, moderate, very hard). Each topic covers various aspects of arrays and object-oriented programming, with practical coding exercises relevant for MNC screenings and hackathons. The document provides problem statements, examples, constraints, and hints for solving each question.

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)
3 views83 pages

Java Complete Scenario Question Bank

The document is a comprehensive Java interview question bank that includes 80 questions across 8 topics, categorized by difficulty level (easy, moderate, very hard). Each topic covers various aspects of arrays and object-oriented programming, with practical coding exercises relevant for MNC screenings and hackathons. The document provides problem statements, examples, constraints, and hints for solving each question.

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

Scenario-Based · LeetCode & HackerRank Style · All 8 Topics · 80 Questions

5 EASY per topic 3 MODERATE per topic 2 VERY HARD per topic

T1: Introduction of Arrays & One-Dimensional Array T2: Programs of One-Dimensional Array

T3: Two-Dimensional Array T4: Operations Based on Jagged Arrays

T5: Advance Programs Based on Arrays T6: Programs of Multi-Dimensional Array

T7: Programs Based on Access Modifiers T8: Programs Based on Run-time Polymorphism
Table of Contents
Topic 1: Introduction of Arrays & One-Dimensional Array
Covers array declaration, traversal, searching and basic manipulation.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard

Topic 2: Programs of One-Dimensional Array


Practical 1-D array coding exercises from MNC screening and hackathon rounds.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard

Topic 3: Two-Dimensional Array


Matrix operations, grid traversal and 2-D DP — core FAANG interview topics.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard

Topic 4: Operations Based on Jagged Arrays


Ragged (variable-length row) arrays — Java-specific feature tested in core OOP rounds.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard

Topic 5: Advance Programs Based on Arrays


High-difficulty algorithms tested in FAANG SDE-2 and product-company competitive rounds.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard

Topic 6: Programs of Multi-Dimensional Array


3-D and higher-dimensional arrays — tested at Qualcomm, NVIDIA, and scientific computing roles.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard

Topic 7: Programs Based on Access Modifiers


Java encapsulation (public/private/protected/default) — core OOP round at every MNC.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard

Topic 8: Programs Based on Run-time Polymorphism


Method overriding, dynamic dispatch and design patterns — tested at FAANG and product MNCs.
■ 5 Easy ■ 3 Moderate ■ 2 Very Hard
TOPIC 1 Introduction of Arrays & One-Dimensional Array
Covers array declaration, traversal, searching and basic manipulation.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 Best Time to Buy and Sell Stock EASY


1
■ Amazon Source: LeetCode #121

PROBLEM STATEMENT

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and a different day in the future to sell it.

Return the maximum profit you can achieve. If you cannot achieve any profit, return 0.

EXAMPLES

Example 1:

Input: prices = [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (price=1) and sell on day 5 (price=6), profit = 6-1 = 5.

Example 2:

Input: prices = [7,6,4,3,1]

Output: 0

Explanation: No transaction is done and the max profit = 0.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• 0 <= prices[i] <= 10^4

Array Greedy Single Pass

■ Track minimum price seen so far; max profit = max(profit, price - minPrice). O(n) time O(1) space.
Hint:
Q0 Find Maximum & Minimum in Array EASY
2
■ TCS Source: HackerRank – Arrays

PROBLEM STATEMENT

A factory sensor logs temperature readings every second into an array temp[].

Without using any built-in sort or library method, find the maximum and minimum temperature recorded in a single
traversal.

Return both values.

EXAMPLES

Example 1:

Input: temp = [3,5,1,9,2]

Output: max=9, min=1

Explanation: Single pass with two variables.

Example 2:

Input: temp = [7]

Output: max=7, min=7

Explanation: Only one element.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• -10^4 <= temp[i] <= 10^4

Array Traversal Two Variables

■ Initialize max=temp[0], min=temp[0]. Loop once updating both. O(n) time, O(1) space.
Hint:
Q0 Reverse an Array In-Place EASY
3
■ Infosys Source: HackerRank – Arrays

PROBLEM STATEMENT

A music playlist is stored as an array songs[] of song IDs.

The user clicks 'Reverse Playlist'. Reverse the array in-place without using any extra array.

Return the reversed array.

EXAMPLES

Example 1:

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

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

Explanation: Two-pointer swap from both ends.

Example 2:

Input: [1,2]

Output: [2,1]

Explanation: Swap first and last.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• 0 <= songs[i] <= 10^9

Array Two Pointers In-place

■ Two pointers: left=0, right=n-1. Swap and move inward until they meet. O(n) time, O(1) space.
Hint:
Q0 Second Largest Element EASY
4
■ Wipro Source: GeeksForGeeks

PROBLEM STATEMENT

An HR system stores employee performance scores in array scores[].

Find the second highest score without sorting the array.

Handle duplicates correctly — if all scores are equal, return -1.

EXAMPLES

Example 1:

Input: [12,35,1,10,34,1]

Output: 34

Explanation: 35 is largest, 34 is second largest.

Example 2:

Input: [10,10,10]

Output: -1

Explanation: All elements equal — no second largest.

CONSTRAINTS

• 2 <= [Link] <= 10^5

• 1 <= scores[i] <= 10^6

Array Single Pass Edge Cases

■ One pass: track first and second max. Update second when new value > second but <= first.
Hint:
Q0 Move Zeroes to End EASY
5
■ Cognizant Source: LeetCode #283

PROBLEM STATEMENT

A photo editing app stores pixel intensities in array pixels[].

Zero-value pixels represent empty slots and must be shifted to the end during compression.

Non-zero pixels must maintain their relative order. Do it in-place.

EXAMPLES

Example 1:

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

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

Explanation: Non-zero order preserved; zeroes at end.

Example 2:

Input: [0]

Output: [0]

Explanation: Single zero — unchanged.

CONSTRAINTS

• 1 <= [Link] <= 10^4

• -2^31 <= pixels[i] <= 2^31-1

Array Two Pointers In-place

■ Slow pointer 'pos' for next non-zero write position. After loop, fill pos..n-1 with 0. O(n).
Hint:

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Maximum Subarray Sum (Kadane's) MODERATE
6
■ Goldman Sachs Source: LeetCode #53

PROBLEM STATEMENT

A financial analyst receives daily profit/loss figures as array nums[].

Find the contiguous subarray with the largest sum. Also return its start and end indices.

The naive O(n^2) approach will TLE on large datasets.

EXAMPLES

Example 1:

Input: [-2,1,-3,4,-1,2,1,-5,4]

Output: 6

Explanation: Subarray [4,-1,2,1] gives sum 6. Indices 3-6.

Example 2:

Input: [5,4,-1,7,8]

Output: 23

Explanation: Entire array. Indices 0-4.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• -10^4 <= nums[i] <= 10^4

Array DP Kadane's Algorithm

■ Kadane's: curr = max(nums[i], curr+nums[i]). Track start/end indices when curr resets or global max updates. O(n).
Hint:
Q0 Find All Duplicates in Array MODERATE
7
■ Adobe Source: LeetCode #442

PROBLEM STATEMENT

A university database stores student IDs (1 to n) in an array of size n.

Due to a system glitch, some IDs appear twice. Find all duplicates.

Solve in O(n) time and O(1) extra space — no HashMap allowed.

EXAMPLES

Example 1:

Input: [4,3,2,7,8,2,3,1]

Output: [2,3]

Explanation: 2 and 3 each appear twice.

Example 2:

Input: [1,1,2]

Output: [1]

Explanation: 1 appears twice.

CONSTRAINTS

• n == [Link]

• 1 <= n <= 10^5

• 1 <= nums[i] <= n

Array Index Marking O(1) Space

■ For each nums[i], negate nums[abs(nums[i])-1]. If already negative, it's a duplicate. O(n) time O(1) space.
Hint:
Q0 Rotate Array by K Steps MODERATE
8
■ Accenture Source: LeetCode #189

PROBLEM STATEMENT

A scheduling system rotates tasks in a circular queue represented as array tasks[].

Rotate the array to the right by k steps in-place.

Handle k > n and negative k. Optimize to O(1) space.

EXAMPLES

Example 1:

Input: [1,2,3,4,5,6,7], k=3

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

Explanation: Rotate right by 3.

Example 2:

Input: [-1,-100,3,99], k=2

Output: [3,99,-1,-100]

Explanation: Rotate right by 2.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• -2^31 <= nums[i] <= 2^31-1

• 0 <= k <= 10^5

Array Reversal Trick In-place

■ k = k % n. Reverse entire array, reverse first k, reverse remaining n-k. Three reversals = O(n), O(1) space.
Hint:

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Trapping Rain Water VERY HARD
9
■ Google Source: LeetCode #42

PROBLEM STATEMENT

Google's urban flooding simulator models a city skyline as elevation map height[].

After heavy rainfall, water gets trapped between taller buildings.

Compute the total volume of water trapped. O(n) time, O(1) space required — brute force will TLE.

EXAMPLES

Example 1:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]

Output: 6

Explanation: 6 units trapped between the elevation bars.

Example 2:

Input: [4,2,0,3,2,5]

Output: 9

Explanation: 9 units of water trapped in the valleys.

CONSTRAINTS

• n == [Link]

• 1 <= n <= 2*10^4

• 0 <= height[i] <= 10^5

Array Two Pointers FAANG Classic Hard

■ Two pointers: leftMax, rightMax. Process smaller-max side: water[i] = max - height[i]. Move pointer inward. O(n)
Hint: O(1).
Q1 Median of Two Sorted Arrays VERY HARD
0
■ Netflix Source: LeetCode #4

PROBLEM STATEMENT

Netflix partitions user-rating scores into two independently sorted arrays across two data centres.

The recommendation engine needs the exact median of combined scores in under 1ms for 10^6 elements.

Merging first is O(m+n) — too slow. Achieve O(log min(m,n)).

EXAMPLES

Example 1:

Input: nums1=[1,3], nums2=[2]

Output: 2.00000

Explanation: Merged=[1,2,3], median=2.

Example 2:

Input: nums1=[1,2], nums2=[3,4]

Output: 2.50000

Explanation: Merged=[1,2,3,4], median=(2+3)/2=2.5.

CONSTRAINTS

• 0 <= m,n <= 1000

• 0 <= m+n <= 2000

• -10^6 <= nums[i] <= 10^6

Array Binary Search Divide & Conquer Hard

■ Binary search on smaller array. Partition both so left-halves equal right-halves. Invariant: maxLeft1<=minRight2 and
Hint: maxLeft2<=minRight1.
TOPIC 2 Programs of One-Dimensional Array
Practical 1-D array coding exercises from MNC screening and hackathon rounds.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 Running Sum of 1D Array EASY


1
■ Google Source: LeetCode #1480

PROBLEM STATEMENT

A server logs daily new user signups in array nums[].

Return the running sum array where result[i] is the total signups from day 0 through day i.

This live total powers a marketing dashboard.

EXAMPLES

Example 1:

Input: [1,2,3,4]

Output: [1,3,6,10]

Explanation: Each element becomes cumulative sum.

Example 2:

Input: [1,1,1,1,1]

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

Explanation: Uniform additions.

CONSTRAINTS

• 1 <= [Link] <= 1000

• -10^6 <= nums[i] <= 10^6

Array Prefix Sum In-place

■ In-place: nums[i] += nums[i-1] starting from index 1. O(n) time, O(1) extra space.
Hint:
Q0 Element Frequency Count EASY
2
■ Infosys Source: HackerRank

PROBLEM STATEMENT

A retail system stores item category codes in array items[].

Count the frequency of each unique item code and print 'code: count' pairs.

Handle negative values and large ranges without a fixed-size bucket array.

EXAMPLES

Example 1:

Input: [4,3,2,4,1,3,4]

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

Explanation: 4 appears 3 times, etc.

Example 2:

Input: [1]

Output: 1:1

Explanation: Single element.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• -10^4 <= items[i] <= 10^4

Array HashMap Frequency

■ Use HashMap. Iterate once: [Link](key,1,Integer::sum). O(n) time, O(k) space (k=unique).
Hint:
Q0 Remove Duplicates from Sorted Array EASY
3
■ Wipro Source: LeetCode #26

PROBLEM STATEMENT

An HR portal stores sorted employee IDs in array ids[].

Duplicate entries exist due to migration bugs. Remove duplicates in-place so each ID appears once.

Return the new length k. Only the first k elements matter.

EXAMPLES

Example 1:

Input: [1,1,2]

Output: 2

Explanation: After removal: [1,2,_]

Example 2:

Input: [0,0,1,1,1,2,2,3,3,4]

Output: 5

Explanation: After removal: [0,1,2,3,4,...]

CONSTRAINTS

• 1 <= [Link] <= 3*10^4

• ids is sorted in non-decreasing order

Array Two Pointers Sorted Array

■ Two pointers: slow 'k' and fast 'i'. Copy nums[i] to nums[k] only when nums[i] != nums[k-1]. O(n) O(1).
Hint:
Q0 Check if Array is Sorted EASY
4
■ TCS Source: Classic

PROBLEM STATEMENT

A logistics system verifies that delivery priority codes are in non-decreasing order before dispatch.

Given array codes[], return true if it is sorted in non-decreasing order, false otherwise.

Do not use any sort method.

EXAMPLES

Example 1:

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

Output: true

Explanation: Already sorted.

Example 2:

Input: [1,3,2,4]

Output: false

Explanation: 3 > 2 breaks order at index 2.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• -10^4 <= codes[i] <= 10^4

Array Linear Scan Early Exit

■ Single loop: if codes[i] < codes[i-1] return false immediately. O(n) time.
Hint:
Q0 Left Rotate Array by D Positions EASY
5
■ Cognizant Source: HackerRank

PROBLEM STATEMENT

A conveyor belt simulation rotates items left by D positions every cycle.

Given array belt[] and integer d, return the array after left rotation by d positions.

Handle d >= n gracefully.

EXAMPLES

Example 1:

Input: [1,2,3,4,5], d=2

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

Explanation: First 2 elements move to end.

Example 2:

Input: [1,2,3], d=4

Output: [2,3,1]

Explanation: 4 % 3 = 1 effective rotation.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• 1 <= d <= 10^9

Array Reversal Trick Modular Arithmetic

■ d = d % n. Reverse entire array, reverse first n-d, reverse last d. Three reversals O(n) O(1).
Hint:

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Subarray Sum Equals K MODERATE
6
■ Flipkart Source: LeetCode #560

PROBLEM STATEMENT

Flipkart tracks daily coupon redemptions per store in array redemptions[].

Find the total count of contiguous subarrays whose sum equals exactly k.

The array may contain negative values (refunds/reversals).

EXAMPLES

Example 1:

Input: [1,1,1], k=2

Output: 2

Explanation: Subarrays [1,1] at 0-1 and 1-2.

Example 2:

Input: [1,2,3], k=3

Output: 2

Explanation: [3] at index 2 and [1,2] at 0-1.

CONSTRAINTS

• 1 <= [Link] <= 2*10^4

• -1000 <= nums[i] <= 1000

• -10^7 <= k <= 10^7

Array Prefix Sum HashMap

■ Prefix sum + HashMap: if [Link](prefixSum - k) count += [Link](that). O(n).


Hint:
Q0 Majority Element (Boyer-Moore) MODERATE
7
■ Amazon Source: LeetCode #169

PROBLEM STATEMENT

An election system stores votes as candidate IDs in array votes[].

A candidate wins if they receive more than n/2 votes.

Find the winning candidate. Guarantee: a majority always exists.

Solve without extra space.

EXAMPLES

Example 1:

Input: [3,2,3]

Output: 3

Explanation: 3 appears 2 out of 3 times.

Example 2:

Input: [2,2,1,1,1,2,2]

Output: 2

Explanation: 2 appears 4 out of 7 times.

CONSTRAINTS

• n == [Link]

• 1 <= n <= 5*10^4

• -10^9 <= votes[i] <= 10^9

• Majority element always exists

Array Boyer-Moore Voting O(1) Space

■ Boyer-Moore Voting: candidate + count. If count==0 pick new candidate. Increment/decrement on match/mismatch.
Hint: O(n) O(1).
Q0 Find the Duplicate Number MODERATE
8
■ Microsoft Source: LeetCode #287

PROBLEM STATEMENT

A hospital system stores patient admission IDs (1 to n) in array of size n+1.

A data entry error caused exactly one ID to be entered twice.

Find the duplicate without modifying the array and using O(1) extra space.

EXAMPLES

Example 1:

Input: [1,3,4,2,2]

Output: 2

Explanation: 2 appears twice.

Example 2:

Input: [3,1,3,4,2]

Output: 3

Explanation: 3 appears twice.

CONSTRAINTS

• 1 <= n <= 10^5

• [Link] == n+1

• 1 <= nums[i] <= n

• Only one integer repeated

Array Floyd's Algorithm Two Pointers Hard Logic

■ Floyd's Cycle Detection: treat values as next pointers. Find cycle entry = duplicate. O(n) O(1).
Hint:

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Longest Increasing Subsequence VERY HARD
9
■ Netflix Source: LeetCode #300

PROBLEM STATEMENT

Netflix ranks content by engagement score over time in array scores[].

Find the length of the longest subsequence where scores are strictly increasing.

This identifies periods of consistent audience growth.

O(n^2) DP will TLE — achieve O(n log n).

EXAMPLES

Example 1:

Input: [10,9,2,5,3,7,101,18]

Output: 4

Explanation: LIS = [2,3,7,101], length 4.

Example 2:

Input: [0,1,0,3,2,3]

Output: 4

Explanation: LIS = [0,1,2,3] or [0,1,3,3...], length 4.

CONSTRAINTS

• 1 <= [Link] <= 2500

• -10^4 <= nums[i] <= 10^4

Array Binary Search Patience Sorting Hard

■ Patience sorting: maintain tails[] array. Binary search insertion point for each element. O(n log n) time O(n) space.
Hint:
Q1 Sliding Window Maximum VERY HARD
0
■ Uber Source: LeetCode #239

PROBLEM STATEMENT

Uber's surge pricing engine monitors fare estimates in a sliding window of k consecutive minutes.

For each window position, report the maximum estimate — used to trigger surge alerts.

Data streams at 10M entries/sec; solution must be O(n).

EXAMPLES

Example 1:

Input: [1,3,-1,-3,5,3,6,7], k=3

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

Explanation: Max of each window of size 3.

Example 2:

Input: [1], k=1

Output: [1]

Explanation: Single element window.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• -10^4 <= nums[i] <= 10^4

• 1 <= k <= [Link]

Array Monotonic Deque Sliding Window Hard

■ Monotonic Deque (ArrayDeque): maintain decreasing deque of indices. Pop front if out of window; pop back if
Hint: smaller than new. O(n).
TOPIC 3 Two-Dimensional Array
Matrix operations, grid traversal and 2-D DP — core FAANG interview topics.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 Transpose a Matrix EASY


1
■ Samsung Source: LeetCode #867

PROBLEM STATEMENT

Samsung's image processing pipeline stores pixel grids as matrices.

Transposing a matrix is required before applying filters.

Given an M×N matrix, return its transpose where transpose[i][j] = matrix[j][i].

EXAMPLES

Example 1:

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

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

Explanation: Rows become columns.

Example 2:

Input: [[1,2],[3,4]]

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

Explanation: 2×2 transpose.

CONSTRAINTS

• m == [Link]

• n == matrix[i].length

• 1 <= m,n <= 1000

• 1 <= matrix[i][j] <= 10^9

Matrix Array Nested Loops

■ Create result[n][m]. Set result[j][i] = matrix[i][j]. O(m*n) time and space.


Hint:
Q0 Spiral Order Matrix Traversal EASY
2
■ TCS Source: LeetCode #54

PROBLEM STATEMENT

A warehouse management system prints shelf inventory in spiral order (clockwise from top-left) for audit reports.

Given M×N matrix grid, return all elements in spiral order.

EXAMPLES

Example 1:

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

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

Explanation: Clockwise spiral.

Example 2:

Input: [[1,2],[3,4]]

Output: [1,2,4,3]

Explanation: Clockwise spiral on 2×2.

CONSTRAINTS

• m == [Link]

• n == matrix[i].length

• 1 <= m,n <= 10

• −100 <= matrix[i][j] <= 100

Matrix Simulation Boundary Pointers

■ Four boundary pointers: top, bottom, left, right. Traverse right→down→left→up, shrink boundaries. O(m*n).
Hint:
Q0 Search in 2D Matrix EASY
3
■ Capgemini Source: LeetCode #74

PROBLEM STATEMENT

A sorted product catalog stores items in an M×N matrix where each row is sorted and the first element of each row is
greater than the last element of the previous row.

Given target price, return true if it exists.

EXAMPLES

Example 1:

Input: matrix=[[1,3,5,7],[10,11,16,20],[23,30,34,60]], target=3

Output: true

Explanation: 3 is at row 0, col 1.

Example 2:

Input: matrix=[[1,3,5,7],[10,11,16,20],[23,30,34,60]], target=13

Output: false

Explanation: 13 not found.

CONSTRAINTS

• m == [Link]

• n == matrix[i].length

• 1 <= m,n <= 100

• −10^4 <= matrix[i][j],target <= 10^4

Matrix Binary Search Flattened Index

■ Treat as flattened sorted array. mid = mid/n row, mid%n col. Standard binary search. O(log m*n).
Hint:
Q0 Diagonal Sum of Matrix EASY
4
■ Wipro Source: LeetCode #1572

PROBLEM STATEMENT

A game board stores scores at each cell in an N×N matrix.

Calculate the sum of all elements on the primary diagonal and secondary diagonal.

For odd N, the centre element must be counted only once.

EXAMPLES

Example 1:

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

Output: 25

Explanation: Primary: 1+5+9=15. Secondary: 3+5+7=15. Centre 5 counted once: 25.

Example 2:

Input: [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]

Output: 8

Explanation: 4+4 diagonals, no overlap for even N.

CONSTRAINTS

• n == [Link] == mat[i].length

• 1 <= n <= 100

• −100 <= mat[i][j] <= 100

Matrix Diagonal Math

■ Loop i 0 to n-1: add mat[i][i] + mat[i][n-1-i]. If n is odd subtract mat[n/2][n/2] once. O(n).
Hint:
Q0 Rotate Matrix 90° Clockwise EASY
5
■ Adobe Source: LeetCode #48

PROBLEM STATEMENT

An image editor must rotate photos 90 degrees clockwise.

Given an N×N pixel matrix, rotate it clockwise in-place without allocating another matrix.

EXAMPLES

Example 1:

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

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

Explanation: Clockwise 90° rotation.

Example 2:

Input: [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]

Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Explanation: 4×4 rotation.

CONSTRAINTS

• n == [Link] == matrix[i].length

• 1 <= n <= 20

• −1000 <= matrix[i][j] <= 1000

Matrix In-place Transpose+Reverse

■ Step 1: Transpose (swap matrix[i][j] with matrix[j][i] for j>i). Step 2: Reverse each row. O(n^2) O(1).
Hint:

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Set Matrix Zeroes MODERATE
6
■ Amazon Source: LeetCode #73

PROBLEM STATEMENT

Amazon's inventory matrix tracks stock levels. If any cell is 0 (out of stock), the entire row and column must be zeroed
out to flag all related items.

Solve in O(1) extra space — no marker matrix allowed.

EXAMPLES

Example 1:

Input: [[1,1,1],[1,0,1],[1,1,1]]

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

Explanation: Row 1 and col 1 zeroed.

Example 2:

Input: [[0,1,2,0],[3,4,5,2],[1,3,1,5]]

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

Explanation: Two zero cells affect rows/cols.

CONSTRAINTS

• m == [Link]

• n == matrix[0].length

• 1 <= m,n <= 200

• −2^31 <= matrix[i][j] <= 2^31−1

Matrix In-place Sentinel Technique

■ Use first row and first col as sentinel markers. Handle (0,0) overlap with a boolean flag. Two passes. O(m*n) O(1).
Hint:
Q0 Flood Fill MODERATE
7
■ Microsoft Source: LeetCode #733

PROBLEM STATEMENT

A paint-bucket tool in Microsoft Paint fills connected pixels of the same colour.

Given image matrix, starting cell (sr,sc) and new colour, perform flood fill (4-directional).

All connected pixels with the original colour become the new colour.

EXAMPLES

Example 1:

Input: image=[[1,1,1],[1,1,0],[1,0,1]], sr=1,sc=1, color=2

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

Explanation: Connected 1s replaced with 2.

Example 2:

Input: [[0,0,0],[0,0,0]], sr=0,sc=0, color=0

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

Explanation: Same color — no change.

CONSTRAINTS

• m == [Link]

• n == image[i].length

• 1 <= m,n <= 50

• 0 <= image[i][j],color <= 65535

Matrix DFS BFS Flood Fill

■ DFS or BFS from (sr,sc). Replace original colour. Skip if already new colour to avoid infinite loop. O(m*n).
Hint:
Q0 Number of Islands MODERATE
8
■ Uber Source: LeetCode #200

PROBLEM STATEMENT

Uber's geospatial engine analyses a binary map where '1'=land and '0'=water.

Count the number of islands. An island is surrounded by water and formed by connecting adjacent land cells
(4-directional).

EXAMPLES

Example 1:

Input: [[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]

Output: 1

Explanation: All land connected = 1 island.

Example 2:

Input: [[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]

Output: 3

Explanation: Three separate islands.

CONSTRAINTS

• m == [Link]

• n == grid[i].length

• 1 <= m,n <= 300

• grid[i][j] is '0' or '1'

Matrix DFS Connected Components

■ DFS: when you find '1', increment count, then DFS to mark all connected '1's as visited ('0'). O(m*n).
Hint:

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Largest Rectangle in Histogram (Matrix) VERY HARD
9
■ Microsoft Source: LeetCode #85

PROBLEM STATEMENT

Microsoft Excel's formula engine detects the largest all-1 region in a binary dependency matrix to optimise batch
recalculation.

Given a binary matrix, find the area of the largest rectangle containing only 1s.

EXAMPLES

Example 1:

Input: [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]

Output: 6

Explanation: Maximal rectangle has area 6.

Example 2:

Input: [[0]]

Output: 0

Explanation: No 1s.

Example 3:

Input: [[1]]

Output: 1

Explanation: Single cell.

CONSTRAINTS

• rows == [Link]

• cols == matrix[0].length

• 1 <= rows,cols <= 200

• matrix[i][j] is '0' or '1'

Matrix Monotonic Stack Histogram DP Hard

■ Build histogram heights row by row. Apply Largest Rectangle in Histogram (monotonic stack) for each row. O(m*n).
Hint:
Q1 Shortest Path in Binary Matrix VERY HARD
0
■ Google Source: LeetCode #1091

PROBLEM STATEMENT

Google Maps models a city grid where 0=clear road and 1=blocked.

Find the length of the shortest clear path from top-left (0,0) to bottom-right (n-1,n-1) moving in 8 directions.

Return −1 if no path exists.

EXAMPLES

Example 1:

Input: [[0,1],[1,0]]

Output: 2

Explanation: Path: (0,0)→(1,1), length 2.

Example 2:

Input: [[0,0,0],[1,1,0],[1,1,0]]

Output: 4

Explanation: Length 4 path exists via diagonal.

CONSTRAINTS

• n == [Link] == grid[i].length

• 1 <= n <= 100

• grid[i][j] is 0 or 1

Matrix BFS Shortest Path Hard

■ BFS from (0,0). Level = distance. 8-directional. Mark visited by setting grid[i][j]=1. O(n^2).
Hint:
TOPIC 4 Operations Based on Jagged Arrays
Ragged (variable-length row) arrays — Java-specific feature tested in core OOP rounds.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 Declare & Print Jagged Array EASY


1
■ Infosys Source: Core Java

PROBLEM STATEMENT

A school scheduler stores class sessions per grade: Grade 1 has 1 session, Grade 2 has 2 sessions, etc.

Declare a jagged array where row i has (i+1) columns. Fill each cell with row*col product and print the structure.

EXAMPLES

Example 1:

Input: n=3

Output: Row0:[0] Row1:[0,1] Row2:[0,2,4]

Explanation: i*j fill for 3 rows.

Example 2:

Input: n=1

Output: Row0:[0]

Explanation: Single row.

CONSTRAINTS

• 1 <= n <= 10

Jagged Array Declaration Nested Loops

■ int[][] arr = new int[n][]; then arr[i] = new int[i+1]; Triple nested logic for fill. O(n^2).
Hint:
Q0 Row Sum of Jagged Array EASY
2
■ TCS Source: Core Java

PROBLEM STATEMENT

A departmental budget system stores varying-length monthly expenses per team in a jagged array.

Compute the sum of each row and return a 1-D array of row sums.

EXAMPLES

Example 1:

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

Output: [3,12,6]

Explanation: Row sums: 1+2=3, 3+4+5=12, 6=6.

Example 2:

Input: [[10,20],[5]]

Output: [30,5]

Explanation: Two rows.

CONSTRAINTS

• 1 <= rows <= 100

• 0 <= elements <= 1000

Jagged Array Row Sum Traversal

■ Outer loop over rows, inner over arr[i].length. sum += arr[i][j]. Store in result[]. O(total elements).
Hint:
Q0 Pascal's Triangle as Jagged Array EASY
3
■ Wipro Source: LeetCode #118

PROBLEM STATEMENT

A mathematics tutoring app generates Pascal's Triangle for visualisation.

Store rows 0 to n as a jagged array where each row has (rowNum+1) elements.

Each cell = sum of two cells directly above it.

EXAMPLES

Example 1:

Input: n=4

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

Explanation: Classic Pascal's triangle.

Example 2:

Input: n=1

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

Explanation: First two rows.

CONSTRAINTS

• 0 <= n <= 30

Jagged Array Pascal's Triangle DP

■ tri[i][0]=tri[i][i]=1. tri[i][j] = tri[i-1][j-1] + tri[i-1][j] for 0 < j < i. O(n^2) time/space.


Hint:
Q0 Find Maximum in Each Row EASY
4
■ Cognizant Source: Classic

PROBLEM STATEMENT

A warehouse stores varying counts of product weights per shelf (row) in a jagged array.

For each shelf, find the maximum weight. Return as a 1-D array.

Also report the overall maximum and its (row, col) position.

EXAMPLES

Example 1:

Input: [[3,1],[7,2,5],[4]]

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

Explanation: Each row maximum found.

Example 2:

Input: [[10,20,30]]

Output: [30], overall=30 at (0,2)

Explanation: Single row.

CONSTRAINTS

• 1 <= rows <= 100

• 1 <= elements per row <= 100

• 0 <= values <= 10^6

Jagged Array Max Finding Tracking

■ Nested loops. rowMax = Integer.MIN_VALUE. Track globalMax and position. O(total elements).
Hint:
Q0 Flatten Jagged Array EASY
5
■ Accenture Source: Core Java

PROBLEM STATEMENT

A data pipeline receives a jagged int[][] and must flatten it into a single 1-D array before sending to a downstream API.

Flatten row-by-row maintaining order. Return the 1-D array.

EXAMPLES

Example 1:

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

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

Explanation: All rows concatenated.

Example 2:

Input: [[10],[20,30]]

Output: [10,20,30]

Explanation: Two rows flattened.

CONSTRAINTS

• 1 <= rows <= 100

• 1 <= elements per row <= 100

• Values fit in int

Jagged Array Flatten Array Copy

■ Compute totalLen = sum of arr[i].length. Allocate result[totalLen]. Copy with index pointer. O(total elements).
Hint:

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Merge Sorted Rows of Jagged Array MODERATE
6
■ HCL Source: Classic

PROBLEM STATEMENT

A logistics system has deliveries per route stored as sorted sub-arrays in a jagged array.

Merge corresponding rows of two jagged arrays A and B so that C[i] is the merged sorted version of A[i] and B[i].

EXAMPLES

Example 1:

Input: A=[[1,3],[2]], B=[[2,4],[1,5]]

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

Explanation: Row-wise sorted merge.

Example 2:

Input: A=[[1]], B=[[2]]

Output: C=[[1,2]]

Explanation: Single-element rows.

CONSTRAINTS

• Same number of rows in A and B

• Rows are sorted

• 1 <= elements <= 10^4

Jagged Array Two Pointers Merge

■ For each row i: two-pointer merge of A[i] and B[i] into C[i] of size A[i].length+B[i].length. O(total).
Hint:
Q0 Transpose a Jagged Array MODERATE
7
■ Mphasis Source: Advanced Java

PROBLEM STATEMENT

A data analytics tool needs to pivot a report: if input[i][j]=x then output[j][i]=x.

Transpose the jagged array. Rows have different lengths — determine correct output dimensions.

Missing cells should be treated as 0.

EXAMPLES

Example 1:

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

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

Explanation: Column 2 only has one element; 0-padded.

Example 2:

Input: [[1],[2,3]]

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

Explanation: Row lengths differ.

CONSTRAINTS

• 1 <= rows <= 50

• Variable column lengths

• Values fit in int

Jagged Array Transpose Edge Cases

■ maxCols = max(arr[i].length). out[j].length = count of rows where arr[i].length > j. Fill with 0 default. O(total).
Hint:
Q0 Search Element in Jagged Array MODERATE
8
■ L&T; Infotech Source: Classic

PROBLEM STATEMENT

A hospital record system stores patient IDs in a jagged array (variable patients per ward).

Given target patient ID, search across all wards and return all (row, col) positions where the ID appears.

EXAMPLES

Example 1:

Input: arr=[[1,2,3],[4,2],[5]], target=2

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

Explanation: Found in two positions.

Example 2:

Input: arr=[[10],[20,30]], target=5

Output: []

Explanation: Not found.

CONSTRAINTS

• 1 <= rows <= 100

• 1 <= elements per row <= 100

• IDs are integers

Jagged Array Linear Search Multi-Position

■ Nested loop over all (i,j). Check arr[i][j] == target, add (i,j) to result list. O(total elements).
Hint:

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Sparse Matrix Multiplication (CSR) VERY HARD
9
■ IBM Research Source: LeetCode #311

PROBLEM STATEMENT

IBM's quantum chemistry simulator multiplies sparse matrices where 99.9% of cells are zero.

Store matrices A and B in CSR format (jagged arrays of non-zero values and column indices).

Compute C=A×B minimising zero multiplications.

EXAMPLES

Example 1:

Input: A=[[1,0,0],[-1,0,3]], B=[[7,0,0],[0,0,0],[0,0,1]]

Output: [[7,0,0],[-7,0,3]]

Explanation: Only non-zero products computed.

Example 2:

Input: A=[[0]], B=[[0]]

Output: [[0]]

Explanation: All zeros.

CONSTRAINTS

• m == [Link]

• k == A[0].length == [Link]

• n == B[0].length

• 1 <= m,k,n <= 200

Jagged Array Sparse Matrix CSR Format Hard

■ For each row i of A, for each non-zero A[i][k], iterate non-zero entries in row k of B. Skip zeros. O(nnz_A *
Hint: nnz_B_per_row).
Q1 BFS on Variable-Width Jagged Grid VERY HARD
0
■ EA Games Source: Competitive

PROBLEM STATEMENT

A game map is stored as a jagged array where each row has a different width (variable terrain).

Find the shortest path from (0,0) to the last element of the last row using BFS.

Validate column bounds per row during neighbour expansion.

EXAMPLES

Example 1:

Input: grid=[[0,0,0],[0,1,0,0],[0,0]]

Output: 4

Explanation: Shortest path length 4 avoiding walls(1).

Example 2:

Input: grid=[[0]]

Output: 0

Explanation: Already at destination.

CONSTRAINTS

• 1 <= rows <= 50

• 1 <= cols per row <= 50

• 0=free, 1=blocked

Jagged Array BFS Shortest Path Hard

■ BFS with queue of (row,col). For each neighbour check: valid row, col < grid[nr].length, not blocked. O(total cells).
Hint:
TOPIC 5 Advance Programs Based on Arrays
High-difficulty algorithms tested in FAANG SDE-2 and product-company competitive rounds.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 Find Pivot Index EASY


1
■ TCS Source: LeetCode #724

PROBLEM STATEMENT

A balancing robot stores weight sensors as array nums[]. The pivot index is where the total weight on its left equals
total weight on its right.

Return the leftmost pivot index. If none, return −1.

EXAMPLES

Example 1:

Input: [1,7,3,6,5,6]

Output: 3

Explanation: Left sum=1+7+3=11, Right sum=5+6=11.

Example 2:

Input: [1,2,3]

Output: −1

Explanation: No pivot exists.

Example 3:

Input: [2,1,-1]

Output: 0

Explanation: Left sum=0, Right sum=1-1=0.

CONSTRAINTS

• 1 <= [Link] <= 10^4

• -1000 <= nums[i] <= 1000

Array Prefix Sum Single Pass

■ totalSum precomputed. At each i: if leftSum == totalSum - leftSum - nums[i] return i. Else leftSum += nums[i]. O(n).
Hint:
Q0 Can Place Flowers EASY
2
■ Accenture Source: LeetCode #605

PROBLEM STATEMENT

A garden layout system checks if n new flowers can be planted in a flowerbed array without violating the
no-adjacent-flowers rule.

1=planted, 0=empty. Return true if n flowers can be placed.

EXAMPLES

Example 1:

Input: [1,0,0,0,1], n=1

Output: true

Explanation: Plant at index 2.

Example 2:

Input: [1,0,0,0,1], n=2

Output: false

Explanation: Cannot place 2 without adjacency conflict.

CONSTRAINTS

• 1 <= [Link] <= 2*10^4

• 0 <= n <= [Link]

• No two adjacent 1s initially

Array Greedy In-place Check

■ Greedy: if flowerbed[i]==0 and neighbours are 0 (or boundary), plant and decrement n. O(n).
Hint:
Q0 Arithmetic Array Validation EASY
3
■ Infosys Source: LeetCode #1502

PROBLEM STATEMENT

A music composer checks if a sequence of notes forms an arithmetic progression (constant difference between
consecutive notes).

Given shuffled array notes[], determine if it can be rearranged to form an AP.

EXAMPLES

Example 1:

Input: [3,5,1]

Output: true

Explanation: Sort → [1,3,5], difference = 2.

Example 2:

Input: [1,2,4]

Output: false

Explanation: Sort → [1,2,4], differences 1 and 2 differ.

CONSTRAINTS

• 2 <= [Link] <= 1000

• -10^6 <= nums[i] <= 10^6

Array Sorting Arithmetic Progression

■ Sort the array. Compute diff = nums[1]-nums[0]. Check all consecutive differences equal diff. O(n log n).
Hint:
Q0 Maximum Average Subarray I EASY
4
■ Wipro Source: LeetCode #643

PROBLEM STATEMENT

A fitness tracker computes the maximum average heart rate over any k consecutive minutes.

Given array heartRate[] and integer k, return the maximum average value of any subarray of length k.

EXAMPLES

Example 1:

Input: [1,12,-5,-6,50,3], k=4

Output: 12.75

Explanation: Subarray [12,-5,-6,50] avg=51/4=12.75.

Example 2:

Input: [5], k=1

Output: 5.00

Explanation: Single element.

CONSTRAINTS

• n == [Link]

• 1 <= k <= n <= 10^5

• -10^4 <= nums[i] <= 10^4

Array Sliding Window Fixed Size

■ Sliding window of size k. Compute first window sum, then slide: add right, remove left. Track maxSum. O(n).
Hint:
Q0 Minimum Operations to Make Array Non-Decreasing EASY
5
■ Cognizant Source: HackerRank

PROBLEM STATEMENT

A factory conveyor adjusts product sizes to ensure non-decreasing order. In one operation you can increase any
element by 1.

Given array sizes[], return the minimum number of operations to make it non-decreasing.

EXAMPLES

Example 1:

Input: [1,5,2,4,1]

Output: 7

Explanation: Adjust index 2 from 2→5 (+3) and index 4 from 1→4 (+3), +1 adjust=7.

Example 2:

Input: [1,2,3]

Output: 0

Explanation: Already non-decreasing.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• 0 <= sizes[i] <= 10^9

Array Greedy Running Max

■ Scan left to right. If sizes[i] < sizes[i-1], ops += sizes[i-1] - sizes[i], set sizes[i] = sizes[i-1]. O(n).
Hint:

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Product of Array Except Self MODERATE
6
■ Microsoft Source: LeetCode #238

PROBLEM STATEMENT

A recommendation engine computes feature importance: for each item, the product of all other item scores.

Given array nums[], return array answer where answer[i] = product of all nums except nums[i].

No division allowed. O(n) time, O(1) extra space.

EXAMPLES

Example 1:

Input: [1,2,3,4]

Output: [24,12,8,6]

Explanation: 24=2*3*4, 12=1*3*4, 8=1*2*4, 6=1*2*3.

Example 2:

Input: [-1,1,0,-3,3]

Output: [0,0,9,0,0]

Explanation: Zero causes most products to be 0.

CONSTRAINTS

• 2 <= [Link] <= 10^5

• -30 <= nums[i] <= 30

• Product fits in 32-bit integer

Array Prefix Product O(1) Space Trick

■ Left-pass: result[i] = product of all left of i. Right-pass: multiply result[i] by suffix product. O(n) O(1).
Hint:
Q0 Jump Game II (Min Jumps) MODERATE
7
■ Oracle Source: LeetCode #45

PROBLEM STATEMENT

A game character must reach the last platform. Array jump[] stores max jump length from each platform.

Find the minimum number of jumps to reach the last platform.

Prove your greedy is optimal.

EXAMPLES

Example 1:

Input: [2,3,1,1,4]

Output: 2

Explanation: Jump from 0→1 (3 steps range) → last.

Example 2:

Input: [2,3,0,1,4]

Output: 2

Explanation: Jump 0→1→last.

CONSTRAINTS

• 1 <= [Link] <= 10^4

• 0 <= nums[i] <= 1000

• Guaranteed to reach last index

Array Greedy Jump Game

■ Track curEnd (current jump boundary) and farthest reachable. When i==curEnd: jumps++, curEnd=farthest. O(n).
Hint:
Q0 Next Greater Element MODERATE
8
■ Zomato Source: LeetCode #496

PROBLEM STATEMENT

Zomato's menu dynamically highlights the next dish with a higher rating after each dish.

For each element in nums1 (subset of nums2), find the next greater element in nums2 to its right.

Return −1 if none exists.

EXAMPLES

Example 1:

Input: nums1=[4,1,2], nums2=[1,3,4,2]

Output: [-1,3,-1]

Explanation: 4: none>4 to right; 1: 3>1; 2: none.

Example 2:

Input: nums1=[2,4], nums2=[1,2,3,4]

Output: [3,-1]

Explanation: Next greater of 2 is 3; 4 has none.

CONSTRAINTS

• 1 <= [Link] <= [Link] <= 1000

• 0 <= nums1[i],nums2[i] <= 10^4

• All values unique

Array Monotonic Stack HashMap

■ Monotonic decreasing stack over nums2. Pop when current > stack top; that element's NGE is current. Store in
Hint: HashMap. O(n).

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Count Inversions in Array VERY HARD
9
■ Jane Street Source: CodeChef INVCNT

PROBLEM STATEMENT

Jane Street's arbitrage detector counts inversions in price arrays: pairs (i,j) where iarr[j], signalling mispricing.

Count total inversions in O(n log n) — O(n^2) brute force is too slow for 10^5 element arrays.

EXAMPLES

Example 1:

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

Output: 3

Explanation: Pairs: (2,1),(4,1),(4,3) = 3 inversions.

Example 2:

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

Output: 10

Explanation: Fully reversed: n*(n-1)/2 = 10 inversions.

CONSTRAINTS

• 1 <= n <= 10^5

• 1 <= arr[i] <= 10^9

Array Merge Sort Inversion Count Hard

■ Modified merge sort: during merge, when right element placed before remaining left elements, add (mid-leftPtr+1) to
Hint: count. O(n log n).
Q1 Minimum Window Subarray VERY HARD
0
■ Paytm Source: LeetCode #76 variant

PROBLEM STATEMENT

Paytm's fraud team tracks transaction codes. Given an array transactions[] and a pattern array required[], find the
smallest contiguous subarray of transactions that contains all required codes at least once.

Return length of that window.

EXAMPLES

Example 1:

Input: trans=[2,1,3,1,2], req=[1,2]

Output: 2

Explanation: Window [1,2] at end has length 2.

Example 2:

Input: trans=[1,2,3], req=[4]

Output: −1

Explanation: Required code not present.

CONSTRAINTS

• 1 <= [Link] <= 10^5

• 1 <= [Link] <= [Link]

• Values are positive integers

Array Sliding Window HashMap Hard

■ Sliding window + HashMap of required counts. Expand right until satisfied, shrink left to minimise. O(n).
Hint:
TOPIC 6 Programs of Multi-Dimensional Array
3-D and higher-dimensional arrays — tested at Qualcomm, NVIDIA, and scientific computing roles.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 3D Array Declaration & Print EASY


1
■ L&T; Source: Core Java

PROBLEM STATEMENT

A 3-D game engine stores voxel data in a 3-D grid of size L×M×N.

Declare a 3-D integer array, fill each cell with i+j+k, and print layer by layer (each 2-D slice on separate block).

EXAMPLES

Example 1:

Input: L=2,M=2,N=2

Output: Layer 0: [[0,1],[1,2]], Layer 1: [[1,2],[2,3]]

Explanation: i+j+k fill for 2×2×2.

Example 2:

Input: L=1,M=1,N=1

Output: Layer 0: [[0]]

Explanation: Single voxel.

CONSTRAINTS

• 1 <= L,M,N <= 10

3D Array Nested Loops Declaration

■ int[][][] arr = new int[L][M][N]; Triple nested loops for fill and print. O(L*M*N).
Hint:
Q0 Sum of Two 3D Tensors EASY
2
■ IBM Source: Core Java

PROBLEM STATEMENT

A scientific simulation must add two identically shaped 3-D data tensors A and B element-wise.

Given A and B of shape L×M×N, compute C = A + B and return C.

EXAMPLES

Example 1:

Input: A=[[[1,2]]], B=[[[3,4]]]

Output: C=[[[4,6]]]

Explanation: Element-wise addition.

Example 2:

Input: A=[[[0]]], B=[[[5]]]

Output: C=[[[5]]]

Explanation: Single element add.

CONSTRAINTS

• Same shape L×M×N

• 1 <= L,M,N <= 20

• Values fit in int

3D Array Element-wise Addition

■ Triple nested loops: C[i][j][k] = A[i][j][k] + B[i][j][k]. O(L*M*N) time and space.
Hint:
Q0 Average Intensity Per Frame (3D Video) EASY
3
■ Adobe Source: Core Java

PROBLEM STATEMENT

Adobe Premiere stores a video as int[frames][rows][cols] where each value is a pixel intensity.

Compute and return the average pixel intensity per frame as a double[] array.

EXAMPLES

Example 1:

Input: video[2][2][2] = {{{1,3},{5,7}},{{2,4},{6,8}}}

Output: [4.0, 5.0]

Explanation: Frame 0 avg=(1+3+5+7)/4=4, Frame 1 avg=(2+4+6+8)/4=5.

Example 2:

Input: video[1][1][1]={{{9}}}

Output: [9.0]

Explanation: Single pixel frame.

CONSTRAINTS

• 1 <= frames,rows,cols <= 50

• 0 <= intensity <= 255

3D Array Average Frame Processing

■ For each frame, sum all pixels, divide by rows*cols. O(frames*rows*cols).


Hint:
Q0 Count Non-Zero Elements in 3D Array EASY
4
■ Qualcomm Source: Core Java

PROBLEM STATEMENT

Qualcomm's signal processor stores 3-D sensor readings where zero means no signal.

Count the number of non-zero elements across the entire 3-D array and return their (i,j,k) positions.

EXAMPLES

Example 1:

Input: [[[1,0],[0,2]],[[3,0],[0,0]]]

Output: Count=3, positions: (0,0,0),(0,1,1),(1,0,0)

Explanation: Three non-zero entries.

Example 2:

Input: [[[0]]]

Output: Count=0, positions:[]

Explanation: All zero.

CONSTRAINTS

• 1 <= L,M,N <= 20

• Values fit in int

3D Array Counting Position Tracking

■ Triple nested loop. If arr[i][j][k] != 0, increment count and record position. O(L*M*N).
Hint:
Q0 Max Element in 3D Array EASY
5
■ Samsung Source: Core Java

PROBLEM STATEMENT

Samsung's 3-D LIDAR sensor outputs depth readings as a 3-D integer array.

Find the maximum depth reading and its (layer, row, col) position without flattening the array.

EXAMPLES

Example 1:

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

Output: max=9 at (0,0,1)

Explanation: 9 is the global max.

Example 2:

Input: [[[42]]]

Output: max=42 at (0,0,0)

Explanation: Single element.

CONSTRAINTS

• 1 <= L,M,N <= 30

• Values fit in int

3D Array Max Finding Position

■ Track globalMax = Integer.MIN_VALUE and position. Triple nested loop update. O(L*M*N).
Hint:

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 3D Heat Diffusion Simulation MODERATE
6
■ NVIDIA Source: Scientific Computing

PROBLEM STATEMENT

NVIDIA's physics engine simulates heat diffusion in a 3-D grid.

In one step each cell becomes the average of itself and its 6 axis-aligned neighbours (handle boundaries with
clamping).

Return the updated grid.

EXAMPLES

Example 1:

Input: 3×3×3 uniform temp 100

Output: After 1 step: boundary cells slightly lower due to fewer neighbours.

Explanation: Average of available neighbours.

Example 2:

Input: 1×1×1 grid [50]

Output: [50]

Explanation: No neighbours — unchanged.

CONSTRAINTS

• 1 <= L,M,N <= 20

• 0 <= temp[i][j][k] <= 1000

3D Array Simulation Boundary Handling

■ Use copy array for new values. For each cell, average self + existing neighbours only. O(L*M*N).
Hint:
Q0 3D Prefix Sum for Volume Queries MODERATE
7
■ Intel Source: Competitive Programming

PROBLEM STATEMENT

Intel's volume rendering engine answers Q sub-cuboid sum queries on a 3-D dataset.

Preprocess a 3-D prefix sum so each query [x1,y1,z1] to [x2,y2,z2] answers in O(1).

EXAMPLES

Example 1:

Input: 4×4×4 grid, query(0,0,0,1,1,1)

Output: Sum of 2×2×2 sub-cube at origin.

Explanation: 8-corner inclusion-exclusion.

Example 2:

Input: 1×1×1 grid, query(0,0,0,0,0,0)

Output: Value at (0,0,0)

Explanation: Single cell.

CONSTRAINTS

• 1 <= L,M,N <= 50

• 0 <= values <= 100

• 1 <= Q <= 10^5

3D Array Prefix Sum Inclusion-Exclusion Moderate-Hard

■ pre[i][j][k] = val + pre[i-1][j][k] + pre[i][j-1][k] + pre[i][j][k-1] - (3 double-counts) + (3 triple-counts) - pre[i-1][j-1][k-1].


Hint: O(L*M*N) build, O(1) query.
Q0 3D BFS — Shortest Path in Obstacle Grid MODERATE
8
■ Amazon Robotics Source: LeetCode variant

PROBLEM STATEMENT

Amazon's warehouse robot navigates a 3-D grid (0=free, 1=obstacle) and must find the shortest path from (0,0,0) to
(L-1,M-1,N-1) moving in 6 cardinal directions.

Return path length or −1 if unreachable.

EXAMPLES

Example 1:

Input: 2×2×2 grid all zeros

Output: 3

Explanation: Diagonal path len 3: (0,0,0)→(1,0,0)→(1,1,0)→(1,1,1).

Example 2:

Input: 1×1×1 grid [0]

Output: 0

Explanation: Already at destination.

CONSTRAINTS

• 1 <= L,M,N <= 20

• grid[i][j][k] is 0 or 1

• Start and end always 0

3D Array BFS Shortest Path

■ BFS with queue of int[3]. 6 direction vectors {±1,0,0},{0,±1,0},{0,0,±1}. Visited 3-D boolean. O(L*M*N).
Hint:

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Matrix Chain Multiplication (3D Slices) VERY HARD
9
■ Google Brain Source: CLRS Classic

PROBLEM STATEMENT

A deep learning pipeline multiplies a chain of weight matrices stored as 2-D slices of a 3-D array matrices[n][rows][cols].

Find the optimal parenthesisation that minimises scalar multiplications using interval DP.

Return minimum cost and the split sequence.

EXAMPLES

Example 1:

Input: dims=[10,30,5,60]

Output: 4500

Explanation: Optimal: (A*(B*C)) costs 30*5*60 + 10*30*60 = 9000+... — best split gives 4500.

Example 2:

Input: dims=[40,20,30]

Output: 24000

Explanation: Only one split: 40*20*30=24000.

CONSTRAINTS

• 2 <= [Link] <= 15

• 1 <= dims[i] <= 100

3D Array Interval DP MCM Hard

■ dp[i][j] = min cost to multiply matrices i through j. dp[i][j] = min over k of dp[i][k]+dp[k+1][j]+dims[i-1]*dims[k]*dims[j].
Hint: O(n^3).
Q1 4D Hypercube Flood Fill (Connected Components) VERY HARD
0
■ Research Source: Competitive

PROBLEM STATEMENT

A hyperdimensional data structure stores a 4-D boolean grid representing activated neural pathways.

Count the number of connected components using BFS with 8-directional 4-D movement (±1 in each of 4 axes).

EXAMPLES

Example 1:

Input: N=2 all true

Output: 1

Explanation: All cells connected in 2×2×2×2 hypercube.

Example 2:

Input: N=2 alternating true/false

Output: Multiple components

Explanation: Disconnected pockets.

CONSTRAINTS

• 1 <= N <= 8

• grid[i][j][k][l] is boolean

4D Array BFS Connected Components Hard

■ BFS with int[4] state. 8 direction vectors (±1 for each of 4 axes). Visited 4-D boolean. Components++ each unvisited
Hint: true cell. O(N^4).
TOPIC 7 Programs Based on Access Modifiers
Java encapsulation (public/private/protected/default) — core OOP round at every MNC.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 Bank Account Encapsulation EASY


1
■ Infosys Source: Core Java OOP

PROBLEM STATEMENT

A banking application must protect account balance from direct access.

Design a BankAccount class with private double balance. Provide public deposit(double), withdraw(double) and
getBalance().

Validate: no negative deposits, no overdraft. Throw custom exceptions.

EXAMPLES

Example 1:

Input: deposit(500), withdraw(200), getBalance()

Output: 300.0

Explanation: 500 deposited, 200 withdrawn.

Example 2:

Input: withdraw(600) on balance 500

Output: InsufficientFundsException

Explanation: Cannot overdraft.

CONSTRAINTS

• 0 <= amount <= 10^9

• balance starts at 0

Access Modifiers Encapsulation Custom Exception

■ private double balance = 0; if(amount<0) throw IllegalArgumentException; if(amount>balance) throw


Hint: InsufficientFundsException.
Q0 Package-Private Calculator EASY
2
■ TCS Source: Core Java OOP

PROBLEM STATEMENT

A math library exposes only add() and subtract() as public. The internal multiply() helper must be accessible only within
the same package (default access).

Demonstrate that multiply() cannot be called from outside the package.

EXAMPLES

Example 1:

Input: [Link](5,3)

Output: 8

Explanation: Public method accessible.

Example 2:

Input: [Link](5,3) from different package

Output: Compile-time error

Explanation: Default access blocked.

CONSTRAINTS

• Values fit in int

Access Modifiers Package-private Default Access

■ No modifier on multiply() = package-private. public for add/subtract. Show compile error in different-package main
Hint: class.
Q0 Vehicle Hierarchy with Protected Speed EASY
3
■ Wipro Source: Core Java OOP

PROBLEM STATEMENT

A vehicle simulation uses inheritance. Vehicle base class has protected int speed.

Car subclass (different package) inherits speed and overrides accelerate().

Demonstrate that protected allows subclass access across packages but blocks unrelated classes.

EXAMPLES

Example 1:

Input: new Car().accelerate()

Output: Car accelerating at speed 120

Explanation: Car overrides and accesses protected speed.

Example 2:

Input: new Vehicle().speed from unrelated class

Output: Compile error

Explanation: Protected blocked outside hierarchy.

CONSTRAINTS

• Demonstrate across two packages

Access Modifiers Protected Inheritance Cross-Package

■ protected int speed in package A. Car extends Vehicle in package B — works. UnrelatedClass in package B —
Hint: compile error.
Q0 Singleton with Private Constructor EASY
4
■ HCL Source: Design Pattern

PROBLEM STATEMENT

A configuration manager must have exactly one instance throughout the application lifecycle.

Implement thread-safe Singleton using private constructor and double-checked locking with volatile.

Explain why volatile is essential on multi-core CPUs.

EXAMPLES

Example 1:

Input: [Link]() from 2 threads

Output: Same object reference both times

Explanation: Thread-safe singleton.

Example 2:

Input: new ConfigManager()

Output: Compile error

Explanation: Private constructor blocked.

CONSTRAINTS

• Thread-safe under concurrent access

• Java 8+

Access Modifiers Singleton volatile Thread-safety

■ private static volatile ConfigManager instance; synchronized block with double null-check. volatile prevents
Hint: instruction reordering.
Q0 Immutable Class with Private Setters EASY
5
■ Accenture Source: Core Java OOP

PROBLEM STATEMENT

A financial record system needs immutable Transaction objects — once created no field can change.

Design an immutable Transaction class: all fields private final, only constructor sets them, no setters.

Also make the class final.

EXAMPLES

Example 1:

Input: new Transaction(101, 500.0, 'CREDIT')

Output: Transaction created

Explanation: Fields set via constructor only.

Example 2:

Input: [Link] = 100

Output: Compile error

Explanation: No setter, field is private final.

CONSTRAINTS

• Demonstrate immutability

• Defensive copy for mutable fields

Access Modifiers Immutability final Private Fields

■ final class Transaction { private final int id; private final double amount; public Transaction(int id, double amount) {...}
Hint: only getters. }

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Builder Pattern with Private Setters MODERATE
6
■ Flipkart Source: Effective Java

PROBLEM STATEMENT

Flipkart's product catalogue creates complex Product objects.

Implement Builder pattern: Product fields all private, only inner [Link] can set them.

Build must validate required fields and demonstrate method chaining.

EXAMPLES

Example 1:

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

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

Explanation: Method chaining.

Example 2:

Input: .build() without required name

Output: ValidationException

Explanation: Builder validates required fields.

CONSTRAINTS

• At least 5 fields

• Required vs optional fields

Access Modifiers Builder Pattern Inner Class Method Chaining

■ Static inner class Builder. [Link] = value; in builder (inner class has access). build() validates then returns new
Hint: Product(this).
Q0 Library System — Package Encapsulation MODERATE
7
■ Cognizant Source: OOP Design

PROBLEM STATEMENT

A library system exposes only borrow() and return() as public API.

Internal isAvailable(), updateInventory() are package-private — inaccessible from client code.

Design two packages: [Link] (public) and [Link] (default access).

EXAMPLES

Example 1:

Input: [Link](bookId)

Output: Book borrowed

Explanation: Public API works.

Example 2:

Input: [Link]() from client

Output: Compile error

Explanation: Default access blocked.

CONSTRAINTS

• Two-package design

• Demonstrate compile-time enforcement

Access Modifiers Package Design Encapsulation API Boundary

■ Public interface in api package. Default-access implementation classes in internal package. Client only imports api
Hint: package.
Q0 Reflection to Access Private Fields MODERATE
8
■ Oracle Source: Java Advanced

PROBLEM STATEMENT

A testing framework needs to inspect private fields of legacy classes without modifying them.

Use Java Reflection to read and modify a private field at runtime.

Discuss security manager implications and when this is appropriate.

EXAMPLES

Example 1:

Input: Field f = [Link]("balance"); [Link](true); [Link](obj)

Output: Returns private balance value

Explanation: Reflection bypasses access control.

Example 2:

Input: With SecurityManager active

Output: IllegalAccessException or SecurityException

Explanation: Security manager can block it.

CONSTRAINTS

• Java 8–11 (setAccessible works)

• Java 17+ may throw InaccessibleObjectException with modules

Access Modifiers Reflection setAccessible Testing

■ Class c = [Link](); Field f = [Link](name); [Link](true); value = [Link](obj). Wrap in


Hint: try-catch.

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Plugin System with ServiceLoader VERY HARD
9
■ JetBrains Source: Java Advanced

PROBLEM STATEMENT

IntelliJ IDEA loads plugins without exposing internal implementation.

Design a plugin system: public Plugin interface in api package; all implementations are package-private.

Expose only via ServiceLoader-based factory so clients never instantiate implementations directly.

EXAMPLES

Example 1:

Input: [Link]("spell-check")

Output: SpellCheckPlugin instance via interface

Explanation: Factory hides impl class.

Example 2:

Input: new SpellCheckPlugin() from client

Output: Compile error (package-private)

Explanation: Direct instantiation blocked.

CONSTRAINTS

• META-INF/services file for ServiceLoader

• Two modules or packages

Access Modifiers ServiceLoader Plugin Architecture Hard

■ Interface public in api. Impl package-private in impl package. Factory uses [Link]([Link]).
Hint: Register impl in META-INF/services.
Q1 Java 9 Module System — Qualified Exports VERY HARD
0
■ Oracle Source: JPMS Spec

PROBLEM STATEMENT

Oracle's cloud SDK must export its API only to trusted partner modules, while keeping all internal packages completely
hidden — even from reflection attacks.

Design [Link] files demonstrating qualified exports and selective opens.

EXAMPLES

Example 1:

module [Link] { exports [Link] to [Link]; opens [Link]


Input:
to framework; }

Output: Partner can use api, framework can reflect internal

Explanation: Qualified exports restrict access.

Example 2:

Input: Untrusted module accessing [Link]

Output: InaccessibleObjectException

Explanation: JPMS enforces module boundary.

CONSTRAINTS

• Java 9+ module system

• Demonstrate with two [Link] files

Access Modifiers JPMS Module System Qualified Exports Hard

■ exports pkg to trustedModule; — qualified export. opens pkg to reflectionFramework; — opens for reflection only.
Hint: Default: nothing exported.
TOPIC 8 Programs Based on Run-time Polymorphism
Method overriding, dynamic dispatch and design patterns — tested at FAANG and product MNCs.

■■ EASY — 5 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

Q0 Animal Sound — Dynamic Dispatch EASY


1
■ TCS Source: Core Java OOP

PROBLEM STATEMENT

A zoo management system models animals.

Create Animal base class with makeSound(). Subclasses Dog, Cat, Cow each override it.

Store mixed objects in Animal[] array and call makeSound() on each.

Explain at what point the JVM decides which method runs.

EXAMPLES

Example 1:

Input: Animal[] zoo = {new Dog(), new Cat(), new Cow()}; for(Animal a:zoo) [Link]();

Output: Woof! Meow! Moo!

Explanation: JVM resolves at runtime via vtable.

Example 2:

Input: Animal a = new Dog(); [Link]();

Output: Woof!

Explanation: Reference type Animal, actual type Dog — runtime dispatch.

CONSTRAINTS

• At least 3 subclasses

• Demonstrate with mixed array

Polymorphism Method Overriding Dynamic Dispatch

■ Decision made at runtime based on actual object type (not reference type). JVM uses vtable internally for virtual
Hint: method dispatch.
Q0 Shape Area Calculator EASY
2
■ Wipro Source: Core Java OOP

PROBLEM STATEMENT

A geometry app calculates areas for different shapes using one unified loop.

Abstract class Shape has abstract double area(). Circle, Rectangle, Triangle each override it.

Create Shape[] of mixed types and compute total area.

EXAMPLES

Example 1:

Input: shapes=[Circle(5), Rectangle(4,6), Triangle(3,4)]

Output: 78.54+24+6 = 108.54

Explanation: Each area() computed polymorphically.

Example 2:

Input: shapes=[Circle(1)]

Output: 3.14159

Explanation: Pi * r^2.

CONSTRAINTS

• @Override in all subclasses

• Abstract class cannot be instantiated

Polymorphism Abstract Class Override

■ abstract class Shape { abstract double area(); }. Shape s = new Circle(r); [Link]() calls [Link]() at runtime.
Hint:
Q0 Payment Processing System EASY
3
■ Paytm Source: OOP Design

PROBLEM STATEMENT

A payment gateway processes different payment types uniformly.

Abstract class Payment has processPayment(double amount). Subclasses CreditCard, UPI, NetBanking each override
it.

Demonstrate via Payment reference without knowing the concrete type.

EXAMPLES

Example 1:

Input: Payment p = new UPI(); [Link](500);

Output: Processing UPI payment of 500

Explanation: Correct subclass method called.

Example 2:

Input: Payment[] gw = {new CreditCard(),new UPI()}; for(p:gw) [Link](100);

Output: CreditCard 100, UPI 100

Explanation: Polymorphic loop.

CONSTRAINTS

• At least 3 payment types

• Each has different internal logic

Polymorphism Abstract Class OCP

■ Payment p = [Link](type); [Link](amt); — caller unaware of concrete class. Open-Closed Principle.


Hint:
Q0 Notification System — Interface Polymorphism EASY
4
■ Infosys Source: OOP Design

PROBLEM STATEMENT

A notification service sends alerts via multiple channels.

Interface Notification has send(String message). EmailNotification, SMSNotification, PushNotification implement it.

Build NotificationService accepting List and sending all.

EXAMPLES

Example 1:

Input: [Link]([Link](email,sms,push), "Order shipped")

Output: Email: Order shipped | SMS: Order shipped | Push: Order shipped

Explanation: All three channels fire.

Example 2:

Input: [Link](emptyList, "msg")

Output: Nothing sent

Explanation: Empty list handled.

CONSTRAINTS

• Program to interface

• New channels addable without changing NotificationService

Polymorphism Interface List OCP

■ [Link](List list, String msg) { [Link](n -> [Link](msg)); } — pure polymorphism.


Hint:
Q0 Tax Calculator — Runtime Type Selection EASY
5
■ Cognizant Source: OOP Design

PROBLEM STATEMENT

A GST billing system applies different tax rates per product category.

Abstract TaxCalculator has computeTax(double price). FoodTax(5%), ElectronicsTax(18%), LuxuryTax(28%) extend it.

For a cart of mixed items, compute each item's tax polymorphically.

EXAMPLES

Example 1:

Input: cart=[Food(100), Electronics(50), Luxury(200)]

Output: 5.0 + 9.0 + 56.0 = 70.0 total tax

Explanation: Each rate applied correctly.

Example 2:

Input: cart=[Food(0)]

Output: 0.0

Explanation: Zero price item.

CONSTRAINTS

• Rates as constants in each subclass

• price >= 0

Polymorphism Abstract Class Tax Strategy

■ TaxCalculator t = new FoodTax(); [Link](price) — polymorphism picks correct rate. Store in Product as
Hint: TaxCalculator reference.

■■ MODERATE — 3 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Strategy Pattern — Runtime Behaviour Swap MODERATE
6
■ Gaming Studio Source: Design Patterns

PROBLEM STATEMENT

A game character can switch attack styles at runtime without recompiling.

Interface AttackStrategy has attack(). SwordAttack, MagicAttack, ArcherAttack implement it.

Character holds AttackStrategy reference and can swap via setStrategy().

EXAMPLES

Example 1:

Input: [Link](new MagicAttack()); [Link]();

Output: Magic bolt fired!

Explanation: Strategy swapped at runtime.

Example 2:

Input: [Link](new SwordAttack()); [Link]();

Output: Sword slash!

Explanation: Same hero, different behaviour.

CONSTRAINTS

• No if/switch in Character class

• New strategies addable without modifying Character

Polymorphism Strategy Pattern OCP Composition

■ interface AttackStrategy { void attack(); }. Character { AttackStrategy s; setStrategy(s); attack() { [Link](); } } —


Hint: Open-Closed Principle.
Q0 Chain of Responsibility — Request Pipeline MODERATE
7
■ Netflix Source: Design Patterns

PROBLEM STATEMENT

Netflix's API gateway processes each request through a pipeline: AuthHandler → RateLimitHandler → LogHandler →
BusinessHandler.

Each handler decides whether to process or pass to next.

New handlers must be insertable without modifying existing ones.

EXAMPLES

Example 1:

Input: Request(token='valid', rate='ok')

Output: Passes Auth → RateLimit → Log → Business — response returned

Explanation: Full pipeline.

Example 2:

Input: Request(token='invalid')

Output: AuthHandler rejects — 401 returned

Explanation: Chain stops at auth.

CONSTRAINTS

• abstract Handler with setNext()

• Must be O(handlers) time per request

Polymorphism Chain of Responsibility Design Pattern

■ abstract Handler { Handler next; void setNext(Handler h); abstract void handle(Request r); }. Concrete: if can handle,
Hint: handle; else [Link](r). Chain assembled by caller.
Q0 Template Method Pattern — Report Generation MODERATE
8
■ Accenture Source: Design Patterns

PROBLEM STATEMENT

Accenture's reporting engine generates PDF, Excel, and HTML reports with the same pipeline: fetchData →
processData → formatOutput → deliver.

Only formatOutput and deliver vary per format. Extract common algorithm into an abstract base class.

EXAMPLES

Example 1:

Input: new PDFReport().generate()

Output: Fetch → Process → Format as PDF → Deliver via email

Explanation: Template executes; subclass fills PDF steps.

Example 2:

Input: new ExcelReport().generate()

Output: Fetch → Process → Format as Excel → Deliver via FTP

Explanation: Same template, different format/deliver.

CONSTRAINTS

• generate() is final in base class

• fetchData and processData in base class

• formatOutput and deliver abstract

Polymorphism Template Method Abstract Class final method

■ final void generate() { fetchData(); processData(); formatOutput(); deliver(); }. abstract formatOutput(); abstract
Hint: deliver(); — Template Method pattern.

■■ VERY HARD — 2 Questions ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■


Q0 Visitor Pattern — AST Double Dispatch VERY HARD
9
■ Palantir Source: Compiler Design

PROBLEM STATEMENT

Palantir's DSL compiler evaluates and pretty-prints an AST (Abstract Syntax Tree) with nodes: AddNode, MulNode,
NumNode.

Two visitors: EvalVisitor (compute value) and PrettyPrintVisitor (infix with parentheses).

Eliminate ALL instanceof checks using double dispatch.

EXAMPLES

Example 1:

Input: [Link](new AddNode(new NumNode(3), new NumNode(4)))

Output: 7

Explanation: 3+4 evaluated without instanceof.

Example 2:

[Link](new MulNode(new NumNode(2), new AddNode(new NumNode(3),new


Input:
NumNode(4))))

Output: 2*(3+4)

Explanation: Infix with parentheses.

CONSTRAINTS

• Zero instanceof anywhere

• New node types require only a new visit() overload in each visitor

• New visitors require only a new Visitor class

Polymorphism Visitor Pattern Double Dispatch AST Hard

■ interface Node { T accept(Visitor v); }. [Link](v) { return [Link](this); }. Visitor { T visit(AddNode n); T
Hint: visit(MulNode n); T visit(NumNode n); }. Double dispatch: both Node and Visitor types resolved at runtime.
Q1 JVM vtable — Megamorphic Call Site Benchmark VERY HARD
0
■ Azul Systems Source: JVM Performance

PROBLEM STATEMENT

Azul's JVM performance team discovers that a hot dispatch loop degrades from 1ms to 12ms latency after a
deployment introduces a third polymorphic type at a single call site (megamorphic).

Write a JMH benchmark isolating monomorphic vs bimorphic vs megamorphic performance.

Propose sealed class redesign to restore monomorphic dispatch.

EXAMPLES

Example 1:

Input: JMH: monomorphic loop 10^7 calls

Output: ~0.5ns/call — JIT fully inlines

Explanation: One type at call site.

Example 2:

Input: JMH: megamorphic loop (4+ types)

Output: ~4ns/call — vtable dispatch, no inline

Explanation: JIT gives up inlining.

CONSTRAINTS

• Java 17+ sealed classes

• JMH micro-benchmark

• Measure with @Benchmark and @BenchmarkMode([Link])

Polymorphism JVM JIT vtable JMH Sealed Classes Hard

■ Monomorphic: JIT inlines method body. Bimorphic: conditional inline. Megamorphic (3+ concrete types): vtable
Hint: dispatch, deoptimised. Sealed + final subclasses help JIT re-monomorphise.
Java Complete Scenario Question Bank · 8 Topics · 80 Questions · 5 Easy + 3 Moderate + 2 Hard per topic | LeetCode · HackerRank · MNC
Archives

You might also like