Java Complete Scenario Question Bank
Java Complete Scenario Question Bank
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
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
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:
Output: 5
Explanation: Buy on day 2 (price=1) and sell on day 5 (price=6), profit = 6-1 = 5.
Example 2:
Output: 0
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
■ 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
The user clicks 'Reverse Playlist'. Reverse the array in-place without using any extra array.
EXAMPLES
Example 1:
Input: [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: [1,2]
Output: [2,1]
CONSTRAINTS
■ 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
EXAMPLES
Example 1:
Input: [12,35,1,10,34,1]
Output: 34
Example 2:
Input: [10,10,10]
Output: -1
CONSTRAINTS
■ 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
Zero-value pixels represent empty slots and must be shifted to the end during compression.
EXAMPLES
Example 1:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: [0]
Output: [0]
CONSTRAINTS
■ Slow pointer 'pos' for next non-zero write position. After loop, fill pos..n-1 with 0. O(n).
Hint:
PROBLEM STATEMENT
Find the contiguous subarray with the largest sum. Also return its start and end indices.
EXAMPLES
Example 1:
Input: [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Example 2:
Input: [5,4,-1,7,8]
Output: 23
CONSTRAINTS
■ 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
Due to a system glitch, some IDs appear twice. Find all duplicates.
EXAMPLES
Example 1:
Input: [4,3,2,7,8,2,3,1]
Output: [2,3]
Example 2:
Input: [1,1,2]
Output: [1]
CONSTRAINTS
• n == [Link]
■ 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
EXAMPLES
Example 1:
Output: [5,6,7,1,2,3,4]
Example 2:
Output: [3,99,-1,-100]
CONSTRAINTS
■ k = k % n. Reverse entire array, reverse first k, reverse remaining n-k. Three reversals = O(n), O(1) space.
Hint:
PROBLEM STATEMENT
Google's urban flooding simulator models a city skyline as elevation map height[].
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
Example 2:
Input: [4,2,0,3,2,5]
Output: 9
CONSTRAINTS
• n == [Link]
■ 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.
EXAMPLES
Example 1:
Output: 2.00000
Example 2:
Output: 2.50000
CONSTRAINTS
■ 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.
PROBLEM STATEMENT
Return the running sum array where result[i] is the total signups from day 0 through day i.
EXAMPLES
Example 1:
Input: [1,2,3,4]
Output: [1,3,6,10]
Example 2:
Input: [1,1,1,1,1]
Output: [1,2,3,4,5]
CONSTRAINTS
■ 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
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]
Example 2:
Input: [1]
Output: 1:1
CONSTRAINTS
■ 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
Duplicate entries exist due to migration bugs. Remove duplicates in-place so each ID appears once.
EXAMPLES
Example 1:
Input: [1,1,2]
Output: 2
Example 2:
Input: [0,0,1,1,1,2,2,3,3,4]
Output: 5
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Input: [1,2,3,4,5]
Output: true
Example 2:
Input: [1,3,2,4]
Output: false
CONSTRAINTS
■ 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
Given array belt[] and integer d, return the array after left rotation by d positions.
EXAMPLES
Example 1:
Output: [3,4,5,1,2]
Example 2:
Output: [2,3,1]
CONSTRAINTS
■ d = d % n. Reverse entire array, reverse first n-d, reverse last d. Three reversals O(n) O(1).
Hint:
PROBLEM STATEMENT
Find the total count of contiguous subarrays whose sum equals exactly k.
EXAMPLES
Example 1:
Output: 2
Example 2:
Output: 2
CONSTRAINTS
PROBLEM STATEMENT
EXAMPLES
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
CONSTRAINTS
• n == [Link]
■ 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
Find the duplicate without modifying the array and using O(1) extra space.
EXAMPLES
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
CONSTRAINTS
• [Link] == n+1
■ Floyd's Cycle Detection: treat values as next pointers. Find cycle entry = duplicate. O(n) O(1).
Hint:
PROBLEM STATEMENT
Find the length of the longest subsequence where scores are strictly increasing.
EXAMPLES
Example 1:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Example 2:
Input: [0,1,0,3,2,3]
Output: 4
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Output: [3,3,5,5,6,7]
Example 2:
Output: [1]
CONSTRAINTS
■ 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.
PROBLEM STATEMENT
EXAMPLES
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2],[3,4]]
Output: [[1,3],[2,4]]
CONSTRAINTS
• m == [Link]
• n == matrix[i].length
PROBLEM STATEMENT
A warehouse management system prints shelf inventory in spiral order (clockwise from top-left) for audit reports.
EXAMPLES
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [[1,2],[3,4]]
Output: [1,2,4,3]
CONSTRAINTS
• m == [Link]
• n == matrix[i].length
■ 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.
EXAMPLES
Example 1:
Output: true
Example 2:
Output: false
CONSTRAINTS
• m == [Link]
• n == matrix[i].length
■ 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
Calculate the sum of all elements on the primary diagonal and secondary diagonal.
EXAMPLES
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 25
Example 2:
Input: [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
Output: 8
CONSTRAINTS
• n == [Link] == mat[i].length
■ 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
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]]
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]]
CONSTRAINTS
• n == [Link] == matrix[i].length
• 1 <= n <= 20
■ 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:
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.
EXAMPLES
Example 1:
Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
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]]
CONSTRAINTS
• m == [Link]
• n == matrix[0].length
■ 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:
Output: [[2,2,2],[2,2,0],[2,0,1]]
Example 2:
Output: [[0,0,0],[0,0,0]]
CONSTRAINTS
• m == [Link]
• n == image[i].length
■ 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
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
CONSTRAINTS
• m == [Link]
• n == grid[i].length
■ DFS: when you find '1', increment count, then DFS to mark all connected '1's as visited ('0'). O(m*n).
Hint:
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
Example 2:
Input: [[0]]
Output: 0
Explanation: No 1s.
Example 3:
Input: [[1]]
Output: 1
CONSTRAINTS
• rows == [Link]
• cols == matrix[0].length
■ 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.
EXAMPLES
Example 1:
Input: [[0,1],[1,0]]
Output: 2
Example 2:
Input: [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
CONSTRAINTS
• n == [Link] == grid[i].length
• grid[i][j] is 0 or 1
■ 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.
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
Example 2:
Input: n=1
Output: Row0:[0]
CONSTRAINTS
• 1 <= n <= 10
■ 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]
Example 2:
Input: [[10,20],[5]]
Output: [30,5]
CONSTRAINTS
■ 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
Store rows 0 to n as a jagged array where each row has (rowNum+1) elements.
EXAMPLES
Example 1:
Input: n=4
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Example 2:
Input: n=1
Output: [[1],[1,1]]
CONSTRAINTS
• 0 <= n <= 30
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]]
Example 2:
Input: [[10,20,30]]
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Input: [[1,2],[3],[4,5,6]]
Output: [1,2,3,4,5,6]
Example 2:
Input: [[10],[20,30]]
Output: [10,20,30]
CONSTRAINTS
■ Compute totalLen = sum of arr[i].length. Allocate result[totalLen]. Copy with index pointer. O(total elements).
Hint:
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:
Output: C=[[1,2,3,4],[1,2,5]]
Example 2:
Output: C=[[1,2]]
CONSTRAINTS
■ 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
Transpose the jagged array. Rows have different lengths — determine correct output dimensions.
EXAMPLES
Example 1:
Input: [[1,2,3],[4,5]]
Output: [[1,4],[2,5],[3,0]]
Example 2:
Input: [[1],[2,3]]
Output: [[1,2],[0,3]]
CONSTRAINTS
■ 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:
Output: [(0,1),(1,1)]
Example 2:
Output: []
CONSTRAINTS
■ Nested loop over all (i,j). Check arr[i][j] == target, add (i,j) to result list. O(total elements).
Hint:
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).
EXAMPLES
Example 1:
Output: [[7,0,0],[-7,0,3]]
Example 2:
Output: [[0]]
CONSTRAINTS
• m == [Link]
• k == A[0].length == [Link]
• n == B[0].length
■ 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.
EXAMPLES
Example 1:
Input: grid=[[0,0,0],[0,1,0,0],[0,0]]
Output: 4
Example 2:
Input: grid=[[0]]
Output: 0
CONSTRAINTS
• 0=free, 1=blocked
■ 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.
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.
EXAMPLES
Example 1:
Input: [1,7,3,6,5,6]
Output: 3
Example 2:
Input: [1,2,3]
Output: −1
Example 3:
Input: [2,1,-1]
Output: 0
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Output: true
Example 2:
Output: false
CONSTRAINTS
■ 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).
EXAMPLES
Example 1:
Input: [3,5,1]
Output: true
Example 2:
Input: [1,2,4]
Output: false
CONSTRAINTS
■ 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:
Output: 12.75
Example 2:
Output: 5.00
CONSTRAINTS
• n == [Link]
■ 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
CONSTRAINTS
■ 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:
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].
EXAMPLES
Example 1:
Input: [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: [-1,1,0,-3,3]
Output: [0,0,9,0,0]
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Input: [2,3,1,1,4]
Output: 2
Example 2:
Input: [2,3,0,1,4]
Output: 2
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Output: [-1,3,-1]
Example 2:
Output: [3,-1]
CONSTRAINTS
■ Monotonic decreasing stack over nums2. Pop when current > stack top; that element's NGE is current. Store in
Hint: HashMap. O(n).
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
Example 2:
Input: [5,4,3,2,1]
Output: 10
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Output: 2
Example 2:
Output: −1
CONSTRAINTS
■ 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.
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
Example 2:
Input: L=1,M=1,N=1
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Output: C=[[[4,6]]]
Example 2:
Output: C=[[[5]]]
CONSTRAINTS
■ 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:
Example 2:
Input: video[1][1][1]={{{9}}}
Output: [9.0]
CONSTRAINTS
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]]]
Example 2:
Input: [[[0]]]
CONSTRAINTS
■ 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]]]
Example 2:
Input: [[[42]]]
CONSTRAINTS
■ Track globalMax = Integer.MIN_VALUE and position. Triple nested loop update. O(L*M*N).
Hint:
PROBLEM STATEMENT
In one step each cell becomes the average of itself and its 6 axis-aligned neighbours (handle boundaries with
clamping).
EXAMPLES
Example 1:
Output: After 1 step: boundary cells slightly lower due to fewer neighbours.
Example 2:
Output: [50]
CONSTRAINTS
■ 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:
Example 2:
CONSTRAINTS
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.
EXAMPLES
Example 1:
Output: 3
Example 2:
Output: 0
CONSTRAINTS
• grid[i][j][k] is 0 or 1
■ 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:
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.
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
CONSTRAINTS
■ 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:
Output: 1
Example 2:
CONSTRAINTS
• 1 <= N <= 8
• grid[i][j][k][l] is boolean
■ 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.
PROBLEM STATEMENT
Design a BankAccount class with private double balance. Provide public deposit(double), withdraw(double) and
getBalance().
EXAMPLES
Example 1:
Output: 300.0
Example 2:
Output: InsufficientFundsException
CONSTRAINTS
• balance starts at 0
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).
EXAMPLES
Example 1:
Input: [Link](5,3)
Output: 8
Example 2:
CONSTRAINTS
■ 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.
Demonstrate that protected allows subclass access across packages but blocks unrelated classes.
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
• Java 8+
■ 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.
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
• Demonstrate immutability
■ final class Transaction { private final int id; private final double amount; public Transaction(int id, double amount) {...}
Hint: only getters. }
PROBLEM STATEMENT
Implement Builder pattern: Product fields all private, only inner [Link] can set them.
EXAMPLES
Example 1:
Output: Product{name=Phone,price=999}
Example 2:
Output: ValidationException
CONSTRAINTS
• At least 5 fields
■ 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
EXAMPLES
Example 1:
Input: [Link](bookId)
Example 2:
CONSTRAINTS
• Two-package design
■ 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.
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
PROBLEM STATEMENT
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")
Example 2:
CONSTRAINTS
■ 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.
EXAMPLES
Example 1:
Example 2:
Output: InaccessibleObjectException
CONSTRAINTS
■ 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.
PROBLEM STATEMENT
Create Animal base class with makeSound(). Subclasses Dog, Cat, Cow each override it.
EXAMPLES
Example 1:
Input: Animal[] zoo = {new Dog(), new Cat(), new Cow()}; for(Animal a:zoo) [Link]();
Example 2:
Output: Woof!
CONSTRAINTS
• At least 3 subclasses
■ 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.
EXAMPLES
Example 1:
Example 2:
Input: shapes=[Circle(1)]
Output: 3.14159
Explanation: Pi * r^2.
CONSTRAINTS
■ 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
Abstract class Payment has processPayment(double amount). Subclasses CreditCard, UPI, NetBanking each override
it.
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
PROBLEM STATEMENT
Interface Notification has send(String message). EmailNotification, SMSNotification, PushNotification implement it.
EXAMPLES
Example 1:
Output: Email: Order shipped | SMS: Order shipped | Push: Order shipped
Example 2:
CONSTRAINTS
• Program to interface
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.
EXAMPLES
Example 1:
Example 2:
Input: cart=[Food(0)]
Output: 0.0
CONSTRAINTS
• price >= 0
■ TaxCalculator t = new FoodTax(); [Link](price) — polymorphism picks correct rate. Store in Product as
Hint: TaxCalculator reference.
PROBLEM STATEMENT
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
PROBLEM STATEMENT
Netflix's API gateway processes each request through a pipeline: AuthHandler → RateLimitHandler → LogHandler →
BusinessHandler.
EXAMPLES
Example 1:
Example 2:
Input: Request(token='invalid')
CONSTRAINTS
■ 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:
Example 2:
CONSTRAINTS
■ final void generate() { fetchData(); processData(); formatOutput(); deliver(); }. abstract formatOutput(); abstract
Hint: deliver(); — Template Method pattern.
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).
EXAMPLES
Example 1:
Output: 7
Example 2:
Output: 2*(3+4)
CONSTRAINTS
• New node types require only a new visit() overload in each visitor
■ 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).
EXAMPLES
Example 1:
Example 2:
CONSTRAINTS
• JMH micro-benchmark
■ 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