Pattern
public class DiamondPattern {
public static void main(String[] args) {
int n = 5;
// Upper part of the pattern
for (int i = 0; i < n; i++) {
// Print leading spaces
for (int s = 0; s < i; s++) {
[Link](" ");
// Print stars with space using if condition
for (int j = 0; j < n - i; j++) {
[Link]("*");
if (j < n - i - 1) { // Only print space if not last star in row
[Link](" ");
[Link]();
// Lower part of the pattern
for (int i = 0; i < n; i++) {
// Print leading spaces
for (int s = 0; s < n - i - 1; s++) {
[Link](" ");
// Print stars with space using if condition
for (int j = 0; j <= i; j++) {
[Link]("*");
if (j < i) { // Only print space if not last star in row
[Link](" ");
[Link]();
}
Out put
*****
****
***
**
**
***
****
*****
Quick note
The upper part decreases stars and increases spaces.
The lower part increases stars and decreases spaces.
Because both loops print the middle line (*) once each, the center appears
twice, forming a symmetric diamond-like pattern.
If you want, I can also:
remove the duplicate middle line, or
convert this into a perfect diamond, or
explain it line by line for exams
Centre pyramid pattern
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
char ch = [Link]().charAt(0);
// Upper half (including middle)
for (int i = 1; i <= n; i++) {
// Print spaces
for (int s = 1; s <= n - i; s++) {
[Link](" ");
}
// Print characters
for (int j = 1; j <= (2 * i - 1); j++) {
[Link](ch);
}
[Link]();
}
// Lower half
for (int i = n - 1; i >= 1; i--) {
// Print spaces
for (int s = 1; s <= n - i; s++) {
[Link](" ");
}
// Print characters
for (int j = 1; j <= (2 * i - 1); j++) {
[Link](ch);
}
[Link]();
}
}
}
Output:
*
***
*****
***
*
public class Main {
public static void main(String[] args) {
int rows=[Link](); // Starting character
int totalChars = rows * (rows + 1) / 2;
char ch = (char) ('A' + totalChars - 1);
for (int i = 1; i <= rows; i++) {
// Print spaces for alignment
for (int s = 1; s <= rows- i; s++) {
[Link](" ");
}
// Print characters in each row
for (int j = 1; j <= i; j++) {
[Link](ch + " ");
ch--;
}
[Link]();
}
}
}
Output:
IH
GFE
DCBA
public class Test {
public static void main(String args[])
{ Scanner sc=new Scanner([Link]);
int n=[Link]();
int num=1;
int[] start=new int[n];
for(int i=1;i<=n;i++) {
start[i-1]=num;
for(int j=1;j<=i;j++) {
[Link](num+" ");
num++;
}
[Link]();
}
for(int i=n;i>=1;i--) {
int temp=start[i-1];
for(int j=1;j<=i;j++) {
[Link](temp+" ");
temp++;
}
[Link]();
}
}
}
Out put
1
2 3
4 5 6
7 8 9 10
7 8 9 10
4 5 6
2 3
1
Z-shape
public class Main {
public static void main(String[] args) {
int n = 4;
// Top row
for (int i = 1; i <= n; i++) {
[Link](i + " ");
}
[Link]();
// Diagonal (right to left)
for (int i = n - 1; i >= 2; i--) {
// Spaces before number
for (int s = 1; s <= 2 * (i - 1); s++) {
[Link](" ");
}
[Link](i);
}
// Bottom row
for (int i = 1; i <= n; i++) {
[Link](i + " ");
}
}
}
Final Output:
1234
3
2
1234
Diamond
public class Main {
public static void main(String[] args) {
int n = 4;
// Upper half
for (int i = 1; i <= n; i++) {
// Left spaces
for (int s = 1; s <= n - i; s++) {
[Link](" ");
}
// First star
[Link]("*");
// Inner spaces
if (i > 1) {
for (int s = 1; s <= (2 * i - 3); s++) {
[Link](" ");
}
// Second star
[Link]("*");
}
[Link]();
}
// Lower half
for (int i = n - 1; i >= 1; i--) {
// Left spaces
for (int s = 1; s <= n - i; s++) {
[Link](" ");
}
// First star
[Link]("*");
// Inner spaces
if (i > 1) {
for (int s = 1; s <= (2 * i - 3); s++) {
[Link](" ");
}
// Second star
[Link]("*");
}
[Link]();
}
}
}
*
* *
* *
* *
* *
* *
*
Scalar Multiplication of a 3×3 Matrix in Java
Reads a 3 × 3 matrix from user input.
Reads a number (scalar value / multiplier).
Multiplies every element of the matrix by that number.
Prints the new matrix.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[][] A = new int[3][3];
// Read matrix elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
A[i][j] = [Link]();
}
}
// Read multiplier
int m = [Link]();
// Multiply and print result
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link]((A[i][j] * m) + " ");
}
[Link]();
}
}
InPut:
123
456
789
2
Output
246
8 10 12
14 16 18
Find Minimum Absolute Difference Between Array Elements in Java
Reads the size of an array (n).
Reads n integer elements.
Finds the minimum absolute difference between any two elements in the array.
Prints the smallest difference.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
// Read array elements
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
int minDist = Integer.MAX_VALUE;
// Find closest pair distance
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int diff = [Link](arr[i] - arr[j]);
if (diff < minDist) {
minDist = diff;
}
}
}
[Link](minDist);
}
Input:
5
10 3 6 8 15
Out put: 2
Sum of Digits with Double Value at Odd Positions (Luhn-like Processing) in Java
For a given integer n, take each digit from left to right. If the number is in odd place
then multiply by 2. If the result is greater than 10, add the digits to find the total and
add to sum. If it is even digit directly add to sum. Print the sum
Example 83641
8,6,1 are in odd place and 3,4 are in even place
First we take 8, multiply by 2 which is 16. Add the digits 1+6 = 7, SUM = 7
3 is in even place, so we just add to 7, SUM = 10
Next we take 6, multiply by 2 which is 12. Add the digits 1+2 = 3, SUM = 13
4 is in even place, so we add it to 13, SUM = 17
Next we take 1 which is odd place. We multiply by 2. Since the result is less than 10,
we directly add it to SUm = 19
So answer is 19. Give Java code for above data
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input number
int n = [Link]();
String num = [Link](n);
int sum = 0;
// Traverse digits from left to right
for (int i = 0; i < [Link](); i++) {
int digit = [Link](i) - '0';
// Position is odd (1-based index)
if ((i + 1) % 2 != 0) {
int result = digit * 2;
// If result is greater than 9, add its digits
if (result > 9) {
sum += (result / 10) + (result % 10);
} else {
sum += result;
}
}
// Even position
else {
sum += digit;
}
}
// Output the sum
[Link](sum);
}
Minimum Number of Jumps to Reach End of Array in Java (Greedy Approach)
public class Main {
public static int minJumps(int[] arr, int n) {
if (n <= 1) return 0;
if (arr[0] == 0) return -1;
int maxReach = arr[0];
int steps = arr[0];
int jumps = 1;
for (int i = 1; i < n; i++) {
// Reached the end
if (i == n - 1)
return jumps;
// Update max reach
maxReach = [Link](maxReach, i + arr[i]);
// Use a step
steps--;
// If no more steps left
if (steps == 0) {
jumps++;
// Cannot move further
if (i >= maxReach)//If value 0 its happen.
return -1;
// Refill steps
steps = maxReach - i;
return -1;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int T = [Link](); // number of test cases
while (T-- > 0) {
int n = [Link](); // size of array
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
[Link](minJumps(arr, n));
Input:
1
5
23114
OutPut: 2
maxReach = [Link](maxReach, i + arr[i]);
initialy max rech 0 th index value 2, max reach 2 [Link] one of that index.
Index Value What it means
0 2 From index 0 you can jump 1 or 2 steps
1 3 From index 1 you can jump 1, 2, or 3 steps
2 1 From index 2 you can jump 1 step
3 1 From index 3 you can jump 1 step
4 4 Last index
From index 0 → jump to index 1 or 2.
Best path:
o Jump 1: index 0 → index 1
o Jump 2: index 1 → index 4 (end)
Minimum jumps = 2
Example Dry Run
Example:
arr = [2, 3, 1, 1, 4]
Start:
maxReach = 2
steps = 2
jumps = 1
i=1
maxReach = max(2, 1+3=4) = 4
steps-- → 1
i=2
maxReach = max(4, 2+1=3) = 4
steps-- → 0
Now:
steps == 0
So:
jumps++ → 2
Now refill steps:
steps = maxReach - i
steps = 4 - 2 = 2
Meaning:
From index 2,
we can still move 2 more steps before next jump.
Heading: Running Median of a Stream of Numbers
Using Heaps
This Java program reads numbers one by one and prints the median after each insertion
using two heaps:
Max heap (left) → stores smaller half of numbers
Min heap (right) → stores larger half of numbers
Keeps both heaps balanced to compute the median efficiently.
Smallest element present top in priority queue.
Priority queue not keep element in ascending order,but smallest element always in
head of the queue.
Peek()-smallest element
Poll()-remove in Ascending order.
Numbers Entered Median
10 10
10, 20 (10+20)/2 = 15
10, 20, 30 20
10, 20, 30, 40 (20+30)/2 = 25
10, 20, 30, 40, 50 30
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
// Max heap for left half
PriorityQueue<Integer> left = new
PriorityQueue<>([Link]());
// Min heap for right half
PriorityQueue<Integer> right = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
int x = [Link]();
// Insert into appropriate heap
if ([Link]() || x <= [Link]()) {
[Link](x);
} else {
[Link](x);
}
// Balance heaps
if ([Link]() > [Link]() + 1) {
[Link]([Link]());
} else if ([Link]() > [Link]()) {
[Link]([Link]());
}
// Print median
if ([Link]() == [Link]()) {
int median = ([Link]() + [Link]()) / 2;
[Link](median);
} else {
[Link]([Link]());
}
}
[Link]();
}
Sliding Window Maximum using Deque (Java)
Window Maximum
[1,3,-1] 3
[3,-1,-3] 3
[-1,-3,5] 5
[-3,5,3] 5
[5,3,6] 6
[3,6,7] 7
public class Main {
public static void sliding(int[] nums, int k) {
Deque<Integer> dq = new LinkedList<>();//store indexes of array elements
for (int i = 0; i < [Link]; i++) {
while (![Link]() && [Link]() <= i - k)// first value outside window remove
[Link]();
while (![Link]() && nums[[Link]()] < nums[i])
[Link]();
[Link](i);
if (i >= k - 1)
[Link](nums[[Link]()]);
if (i >= k - 1 && i != [Link] - 1)
[Link](",");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Read array like: [1,3,-1,-3,5,3,6,7]
String line = [Link]();
// Remove brackets
line = [Link]("[", "").replace("]", "");
// Split by comma
String[] parts = [Link](",");
int[] nums = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
nums[i] = [Link](parts[i].trim());
}
// Read k
int k = [Link]();
sliding(nums, k);
}
[1,3,-1,-3,5,3,6,7]
3
Output:
3,3,5,5,6,7
What is First and Last in Deque?
In the deque:
First element → [Link]()
👉 This is the maximum element’s index in current window.
Last element → [Link]()
👉 This is the most recently added candidate index.
Why store index?
Because we need:
position checking
removing old elements
👉 dq always keeps indexes of useful elements.
Step 1 — Remove Out-of-Window Elements
Step 2 — Remove Smaller Elements
Step 3 — Add Current Index
Step 5 — Print Comma
The deque always keeps: deque always maintain insertion order.
Largest element index at front
Elements in decreasing order
Only window elements
When window moves:
old window → [0,1,2]
new window → [1,2,3]
Leftmost element goes out → remove it.
Window size k → exactly k elements
Current index i → window starts at (i-k+1)
Step-by-Step Example
We track:
current index i
current window
deque content
check condition
✅ Start
nums = [2,4,3,6,7]
k = 3
dq = empty
✅ i = 0 → element = 2
Window not formed yet.
Add index:
dq = [0]
Check:
i-k = 0-3 = -3
0 <= -3 → false
Nothing removed.
✅ i = 1 → element = 4
Before adding:
Remove smaller values → remove index 0 (because 4 > 2)
dq = [1]
Check:
i-k = 1-3 = -2
1 <= -2 → false
Nothing removed.
✅ i = 2 → element = 3
Add index:
dq = [1,2]
Window now formed (size 3).
Check:
i-k = 2-3 = -1
1 <= -1 → false
Nothing removed.
Current window:
index 0 to 2 → [2,4,3]
max = nums[1] = 4
✅ i = 3 → element = 6 ⭐ IMPORTANT STEP
Current window should be:
index 1 to 3
Check condition:
i-k = 3-3 = 0
Check front index:
[Link]() = 1
1 <= 0 → false
So index 1 still inside window.
Then remove smaller elements:
6 > 3 → remove index 2
6 > 4 → remove index 1
dq = []
Add index:
dq = [3]
✅ i = 4 → element = 7 ⭐ SEE REMOVAL CASE
New window:
index 2 to 4
Check condition:
i-k = 4-3 = 1
Check:
[Link]() = 3
3 <= 1 → false
Index 3 still valid.
Then remove smaller values:
7 > 6 → remove index 3
dq = []
Add index:
dq = [4]
🔥 When Does Removal Actually Happen?
Suppose deque had:
dq = [0,1,2]
At:
i = 3
k = 3
i-k = 0
Check:
[Link]() = 0
0 <= 0 → true
Meaning:
index 0 is outside new window (1 to 3)
So remove:
[Link]()
✅ Why We Use <= i-k (Important Idea)
At index i, valid window is:
i-k+1 to i
Anything before that:
≤ i-k
is outside → remove.
Nested List Weight Sum (Depth Sum using Recursion in Java)
Takes a nested list as a string input like [[1,1],2,[1,1]]
Each number is multiplied by its depth level
Computes the total depth-weighted sum
Uses recursion to process nested brackets.
Depth rule:
Outer level → depth 1
Inside one bracket → depth 2
Inside two brackets → depth 3, etc.
[[1,1],2,[1,1]]
Depth 2 → 1 + 1 = 2 → 2 × 2 = 4
Depth 1 → 2 × 1 = 2
Depth 2 → 1 + 1 = 2 → 2 × 2 = 4
Total = 4 + 2 + 4 = 10
public class Main {
static int index = 0;
public static int depthSum(String s, int depth) {
int sum = 0;
int num = 0;
boolean hasNum = false;
while (index < [Link]()) {
char c = [Link](index);
if (c == '[') {
index++;
sum += depthSum(s, depth + 1);
}
else if ([Link](c)) {
num = num * 10 + (c - '0');
hasNum = true;
}
else if (c == ',' || c == ']') {
if (hasNum) {
sum += num * depth;
num = 0;
hasNum = false;
}
if (c == ']') {
index++;
return sum;
}
}
index++;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input example: [[1,1],2,[1,1]]
String input = [Link]();
// index = 0;
int result = depthSum(input, 0);
[Link](result);
}
Num value get reset to zero after each sum calculation.
Longest Unique Consecutive Sequence Length in an Array (Java)
Reads n numbers into an array.
Sorts the array.
Finds the longest consecutive sequence (numbers increasing by 1).
Ignores duplicate values.
If more than one sequence has the same maximum length, it returns 0.
Otherwise, it returns the length of the longest sequence.
public class Main {
public static int longestConsecutiveLength(int[] arr) {
if ([Link] == 0) return 0;
[Link](arr); // sort before evaluating
int maxLen = 1;
int currLen = 1;
int countMax = 0;
for (int i = 1; i < [Link]; i++) {
if (arr[i] == arr[i - 1]) {
continue; // skip duplicates
}
else if (arr[i] == arr[i - 1] + 1) {
currLen++;
}
else {//stop previous sequence update value ,break previous sequence
if (currLen > maxLen) {
maxLen = currLen;
countMax = 1;
} else if (currLen == maxLen) {
countMax++;
}
currLen = 1;//start new sequnce
}
}
// check last sequence//if there is no break occur value is in consecutive
order
if (currLen > maxLen) {
maxLen = currLen;
countMax = 1;
} else if (currLen == maxLen) {
countMax++;
}
// if more than one sequence has same max length → return 0
if (countMax > 1) return 0;
return maxLen;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link](longestConsecutiveLength(arr));
}
When numbers are not consecutive.
Example:
4 → 100 (break)
Ex
Example 1 — Without Last Check (Wrong Result)
Input
arr = [1,2,3,4]
After sorting:
[1,2,3,4]
Loop Execution
Start:
maxLen = 1
currLen = 1
i=1 → 2 vs 1 → consecutive
currLen = 2
i=2 → 3 vs 2 → consecutive
currLen = 3
i=3 → 4 vs 3 → consecutive
currLen = 4
Loop ends here ❗
Notice:
No sequence break happened.
So this block never ran:
else {
if (currLen > maxLen)
So:
maxLen still = 1 (wrong!)
Last Check Fixes It
After loop:
if (currLen > maxLen)
maxLen = currLen;
Now:
maxLen = 4 (correct)
What is “last sequence” here?
When the loop finishes, the current consecutive sequence may still be running.
But inside the loop, we only update maxLen when a sequence breaks.
If the sequence does NOT break before loop ends, it will never be checked.
_______________________________________________________
or each number in the array
1. Find cumulative digit sum until a single digit (digital root).
2. Form a 6-digit string.
3. Replace odd digits with lowercase alphabets (1→a, 2→b, …, 9→i).
public class Main {
// Function to find cumulative sum until single digit
public static int getSingleDigit(int num) {
while (num > 9) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
num = sum;
}
return num;
}
// Function to convert odd digits to alphabets
public static String convertOddToChar(String s) {
StringBuilder result = new StringBuilder();
for (char ch : [Link]()) {
int digit = ch - '0';
// if odd → convert to alphabet (1=a, 2=b ... 9=i)
if (digit % 2 == 1) {
[Link]((char) ('a' + digit - 1));
} else {
[Link](digit);
}
}
return [Link]();
}
public static void main(String[] args) {
// Given array
int[] pinArray = {1, 22, 123, 4242, 45, 56};
StringBuilder sixDigit = new StringBuilder();
// Step 1: find cumulative sums
for (int num : pinArray) {
[Link](getSingleDigit(num));
}
// Step 2: replace odd digits with alphabets
String output = convertOddToChar([Link]());
[Link](output);
}
}
Output for given example: a46ci2
{1, 22, 123, 4242, 45, 56}
Steps 1 → convert each number to single digit
2 → join them → "146392"
3 → convert odd digits to letters → "a46ci2"
Rearrange Array by Placing Even Index Elements at Odd Positions and Odd
Index Elements at Even Positions
public class Test {
public static void main(String args[]) {
Scanner sc=new Scanner([Link]);
int n=[Link]();
int arr[]=new int[n];
int result[]=new int[n];
int count=2;
int flag=1;
for(int i=0;i<n;i++) {
arr[i]=[Link]();
}
result[0]=arr[0];
for(int j=0;j<n;j+=2) {
if(j!=0) {
result[flag]=arr[j];
flag+=2;}
}
for(int k=1;k<n;k+=2) {
result[count]=arr[k];
count+=2;
}
[Link]([Link](result));
}
}
Input:
5
31
32
33
34
35
OutPut:[31,33,32,35,34]
Find Minimum Absolute Difference Between All Pairs in an Array
What the Code Does
Reads n elements into an array.
Compares every pair of elements.
Finds the absolute difference between each pair.
Prints each pair with its difference.
Displays the minimum difference among all pairs.
Input:
10 25 15 30
10 and 25 -> Diff = 15
10 and 15 -> Diff = 5
10 and 30 -> Diff = 20
25 and 15 -> Diff = 10
25 and 30 -> Diff = 5
15 and 30 -> Diff = 15
public class Display {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
int mindiff = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int diff = arr[i] - arr[j];
// manually convert to positive (absolute value logic)
if (diff < 0) {
diff = -diff;
}
[Link](arr[i] + " and " + arr[j] +
" -> Diff = " + diff);
if (diff < mindiff) {
mindiff = diff;
}
}
}
[Link]("Minimum Difference: " + mindiff);
}
Two Sum Problem – Find Indices of Two Numbers That Add to Target
public class Display {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
String ar[] = [Link](" ");
int nums[] = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
nums[i] = [Link](ar[i]);
}
int target = [Link]();
int index1 = -1;
int index2 = -1;
for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (nums[i] + nums[j] == target) {
index1 = i;
index2 = j;
break;
}
}
if (index1 != -1) {
break;
}
}
if (index1 != -1) {
[Link]("Index1: " + index1);
[Link]("Index2: " + index2);
} else {
[Link]("No two sum solution");
} }
Sample Input
10 20 30 40 50
50
Output:
Index1: 0
Index2: 3
Check Isomorphic Strings
Two strings are isomorphic if each character in the first string maps to exactly
one character in the second string (one-to-one mapping), preserving order.
public class Main {
public static boolean isIsomorphic(String s, String t) {
// If lengths differ → not isomorphic
if ([Link]() != [Link]()) return false;
// Arrays to store mapping of characters
char[] mapST = new char[256]; // s -> t
char[] mapTS = new char[256]; // t -> s
for (int i = 0; i < [Link](); i++) {
char c1 = [Link](i);
char c2 = [Link](i);
// If no mapping exists yet, create mapping
if (mapST[c1] == 0 && mapTS[c2] == 0) {
mapST[c1] = c2;
mapTS[c2] = c1;
}
// If mapping exists but doesn't match
else if (mapST[c1] != c2 || mapTS[c2] != c1) {
return false;//stop loop function hear
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input two strings
String s = [Link]();
String t = [Link]();
[Link](isIsomorphic(s, t));
}
}
Input
egg
add
output:
true
No mapping exists → create mapping:
e → a
a → e
i=1
c1 = 'g'
c2 = 'd'
No mapping exists → create mapping:
g → d
d → g
i=2
c1 = 'g'
c2 = 'd'
Mapping already exists:
mapST['g'] = 'd'
mapTS['d'] = 'g'
Your function works like this:
Start checking characters
Wrong mapping found?
YES → return false (stop immediately)
NO → keep checking
Loop finishes completely
return true
Check if two string given anagram of each other
public class Main {
public static boolean isAnagram(String s1, String s2) {
// Case-sensitive → no lowercase conversion
if ([Link]() != [Link]()) return false;
int[] count = new int[256];
for (char c : [Link]()) count[c]++;
for (char c : [Link]()) {
count[c]--;
if (count[c] < 0) return false;
} return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]([Link]()); // number of test cases
for (int i = 0; i < n; i++) {
String line = [Link](); // read full line
String[] parts = [Link]("\\s+"); // handles multiple spaces
String s1 = parts[0];
String s2 = parts[1];
if (isAnagram(s1, s2))
[Link]("True");
else
[Link]("False");
}
}
}
OutPut:
3
Hello hello
listen silent
abc abc
output:
False
True
True
To reverse each and every word in a string (without changing the word
order), you:
✅ Split the string into words
✅ Reverse each word
✅ Join them back
public class Main {
public static String reverseWord(String word) {
StringBuilder sb = new StringBuilder(word);
return [Link]().toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String str = [Link](); // input full string
String[] words = [Link]("\\s+"); // split words
StringBuilder result = new StringBuilder();
for (String word : words) {
[Link](reverseWord(word)).append(" ");
}
[Link]([Link]().trim());
}
}
Input : hello world
Output : olleh dlrow
Minimum deletions to make two strings equal
you have been given string s1 and s2 using the following rule,return
the least number of steps required to make s1 equals to s2 rule
delete one character at a time in a string ex: s1 ="rolex" s2=alex
output 1 give java code.
import [Link].*;
public class Main {
// Function to find minimum deletion steps
public static int minSteps(String s1, String s2) {
int n = [Link]();
int m = [Link]();
// DP array for LCS
int[][] dp = new int[n + 1][m + 1];
// Find Longest Common Subsequence
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if ([Link](i - 1) == [Link](j - 1)) {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
dp[i][j] = [Link](dp[i - 1][j], dp[i][j - 1]);
}
}
}
int lcs = dp[n][m];
// minimum deletions
return (n - lcs) + (m - lcs);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s1 = [Link]();
String s2 = [Link]();
[Link](minSteps(s1, s2));
}
}
Input:
sea
eat
Output:
2
"" e a t
"" 0 0 0 0
s 0 000
e 0 111
a 0 122 how this table value found
Good question 👍 — let’s see how each value in the DP table is calculated step by step.
We will build the table cell by cell.
✅ Example
s1 = "sea"
s2 = "eat"
s1 → rows
s2 → columns
dp[n+1][m+1] → dp[4][4]
Step 1: Create Empty Table
First row and first column = 0
(because empty string → no common subsequence)
"" e a t
"" 0 0 0 0
s 0
e 0
a 0
Rule Used to Fill Table
For every cell:
⭐ If characters match
dp[i][j] = 1 + dp[i-1][j-1]
If characters don’t match
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
Step-by-Step Table Filling
We fill row by row.
Row 1 → character "s"
Compare s with e → ❌ not equal
Compare s with
e → ❌ not equal
dp[1][1] = max(dp[0][1], dp[1][0])
= max(0,0)
= 0
"" e a t
"" 0 0 0 0
s 0 0
Compare s with a → ❌ not equal
dp[1][2] = max(dp[0][2], dp[1][1])
= max(0,0)
= 0
Compare s with t → ❌ not equal
dp[1][3] = max(dp[0][3], dp[1][2])
= 0
Row completed:
"" e a t
"" 0 0 0 0
s 0 0 0 0
(No common character yet.)
🔴 Row 2 → character "e"
Compare e with e → ✅ match
dp[2][1] = 1 + dp[1][0]
= 1 + 0
= 1
Why 1?
→ we found common character "e".
"" e a t
"" 0 0 0 0
s 0 0 0 0
e 0 1
Compare e with a → ❌ not equal
dp[2][2] = max(dp[1][2], dp[2][1])
= max(0,1)
= 1
We keep previous best subsequence.
Compare e with t → ❌ not equal
dp[2][3] = max(dp[1][3], dp[2][2])
= max(0,1)
= 1
Row completed:
"" e a t
"" 0 0 0 0
s 0 0 0 0
e 0 1 1 1
🔴 Row 3 → character "a"
Compare a with e → ❌ not equal
dp[3][1] = max(dp[2][1], dp[3][0])
= max(1,0)
= 1
Compare a with a → ✅ match
dp[3][2] = 1 + dp[2][1]
= 1 + 1
= 2
Why 2?
previous match = "e"
new match = "a"
LCS = "ea"
Compare a with t → ❌ not equal
dp[3][3] = max(dp[2][3], dp[3][2])
= max(1,2)
= 2
Final table:
"" e a t
"" 0 0 0 0
s 0 0 0 0
e 0 1 1 1
a 0 1 2 2
✅ What This Table Means
Largest value = 2
Longest common subsequence = "ea"
LCS length = dp[3][3] = 2
⭐ Simple Way to Remember
Match → go diagonal +1
No match → take max(left, top)
That’s all the table does.
If you want, I can next show:
✅ Visual animation-style filling of DP table
✅ Trick to remember LCS easily in exams
✅ Another example (step-by-step)
Just tell me 👍
What This Table Means Largest value = 2 Longest common subsequence = "ea" why
Good 👍 — let’s understand why the largest value = 2 means LCS = "ea" in a very simple
way.
✅ What LCS Means
LCS (Longest Common Subsequence) =
👉 longest sequence of characters that appears in both strings in the same order (not
necessarily continuous).
✅ Given Example
s1 = "sea"
s2 = "eat"
✅ Step 1: Find common characters in order
Check characters of both strings:
s1 → s e a
s2 → e a t
Common characters:
e and a
And they appear in same order:
s1 → e → a
s2 → e → a
So possible common subsequence:
"ea"
Length = 2
✅ Step 2: Why DP Table Shows 2
The DP table stores:
dp[i][j] = length of longest common subsequence
for first i characters of s1
and first j characters of s2
Final cell:
dp[3][3] = 2
means:
LCS length between "sea" and "eat" = 2
✅ Step 3: Why specifically "ea" (not something else)?
Let’s check all possibilities.
Possible common subsequences:
Subsequence In s1? In s2?
s ✅ ❌
e ✅ ✅
a ✅ ✅
se ❌ ❌
Subsequence In s1? In s2?
sa ❌ ❌
ea ✅ ✅
Only longest valid one:
"ea"
No common sequence of length 3 exists.
So:
Longest length = 2
Subsequence = "ea"
✅ Step 4: Why DP increases to 2
Look at the matches:
e == e → length becomes 1
a == a → length becomes 2
DP builds sequence step by step:
"" → 0
"e" → 1
"ea" → 2
That’s why the table ends with 2.
⭐ Very Simple Understanding
DP table counts how many matching characters
can be kept in order.
We found:
e
+
a
=
2 characters
So:
Largest value = 2
→ we matched 2 characters
→ longest subsequence = "ea"
Extract Seconds from Time (HH:MM:SS) Using Regular Expression in Java
Reads a full sentence from the user.
Searches for a time format HH:MM:SS in the text.
Extracts and prints only the seconds part.
import [Link];
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Read full sentence
String input = [Link]();
// Pattern to find time in HH:MM:SS
Pattern p = [Link]("\\b\\d{2}:\\d{2}:(\\d{2})\\b");
Matcher m = [Link](input);
if ([Link]()) {
// Group 1 contains the seconds part
[Link]([Link](1));
}
[Link]();
}
The current time is 12:45:30 now
30
Count Strings, Integers, and Doubles in a Sentence Using Java
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String line = [Link]();
String[] words = [Link]("\\s+");
int stringCount = 0;
int intCount = 0;
int doubleCount = 0;
for (String w : words) {
if ([Link]("-?\\d+")) {
// Integer
intCount++;
else if ([Link]("-?\\d+\\.\\d+")) {
// Double
doubleCount++;
else if ([Link]("[a-zA-Z]+")) {
// String
stringCount++;
}
[Link]("string " + stringCount);
[Link]("integer " + intCount);
[Link]("double " + doubleCount);
[Link]();
hello 123 45.6 world -78 3.14 java
string 3
integer 2
double 2
Form the Largest Possible Number by Arranging Given Numbers in Java
Reads n numbers as strings.
Rearranges them in such a way that their concatenation forms the largest possible
number.
Uses a custom sorting rule to compare combinations of numbers.
Handles edge case when all numbers are 0.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
// Sort using custom comparator
[Link](arr, (a, b) -> (b + a).compareTo(a + b));
// Edge case: if all are zero
if (arr[0].equals("0")) {
[Link]("0");
return;
}
// Form the largest number
StringBuilder result = new StringBuilder();
for (String s : arr) {
[Link](s);
[Link]([Link]());
[Link]();
3 30 34 5 9
9534330
What This Logic Means (Simple Understanding)
Imagine collecting numbers in increasing order:
Array:
[4, 2, 1, 3]
Round 1:
Pick 1 (index 2)
Can’t pick 2 after that (because 2 is before 1)
→ Stop round
Round 2:
Pick 2 (index 1)
Pick 3 (index 3)
Can’t pick 4 (because 4 is before 3)
→ Stop round
Round 3:
Pick 4
Total rounds = 3
Chef uses internet in N time blocks
For Ti minutes → usage = Di MB per minute
Cost = 1 dollar per 1 MB
First K minutes are free
👉 Find total amount to pay.
We must:
1. Track total minutes used.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int TC = [Link](); // number of test cases
while (TC-- > 0) {
int N = [Link](); // number of usage blocks
int K = [Link](); // free minutes
int cost = 0;
for (int i = 0; i < N; i++) {
int Ti = [Link](); // minutes used
int Di = [Link](); // MB per minute
// free minutes available
if (K >= Ti) {
K -= Ti; // all free
} else {
int chargeable = Ti - K; // remaining minutes to charge
cost += chargeable * Di;
K = 0; }
// print answer for this test case
[Link](cost);
} }
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int t = [Link](); // number of test cases
while (t-- > 0) {
int n = [Link]();
int m = [Link]();
int size = n * m;
int[] A = new int[size];
int[] B = new int[size];
// read matrix A
for (int i = 0; i < size; i++) {
A[i] = [Link]();
// read matrix B
for (int i = 0; i < size; i++) {
B[i] = [Link]();
// sort both arrays
[Link](A);
[Link](B);
// check if equal
if ([Link](A, B)) {
[Link]("YES");
} else {
[Link]("NO");
[Link]();
Java Code — Longest Palindrome Length from Given String
Count frequency of each character (case sensitive).
Use all even counts fully.
From odd counts, use count - 1 and allow one odd character in the center.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
// frequency map (case sensitive)
HashMap<Character, Integer> map = new HashMap<>();
for (char ch : [Link]()) {
[Link](ch, [Link](ch, 0) + 1);
int length = 0;
boolean hasOdd = false;
for (int count : [Link]()) {
if (count % 2 == 0) {
length += count; // use all even counts
} else {
length += count - 1; // use even part
hasOdd = true;
// one odd character can be placed in center
if (hasOdd) {
length += 1;
[Link](length);
}
Java Code — Reverse Number and Add Until Palindrome
Steps:
Take number from user
Check if it is palindrome
If not → reverse it and add
Repeat until palindrome is obtained
public class Main {
// function to reverse number
public static long reverse(long num) {
long rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
return rev;
// function to check palindrome
public static boolean isPalindrome(long num) {
return num == reverse(num);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
long num = [Link]();
// if already palindrome
if (isPalindrome(num)) {
[Link]("Given Number is already a palindrome");
return;
int steps = 0;
// repeat until palindrome
while (!isPalindrome(num)) {
long rev = reverse(num);
num = num + rev;
steps++;
[Link]("Palindrome: " + num);
[Link]("Steps required: " + steps);
}
public class Main {
// Function to reverse number
public static long reverse(long num) {
long rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
return rev;
// Function to check palindrome
public static boolean isPalindrome(long num) {
return num == reverse(num);
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
long num = [Link]();
long original = num;
// If already palindrome
if (isPalindrome(num)) {
[Link]("Given Number is already a palindrome");
[Link](num + " is a palindrome");
return;
// Reverse and add until palindrome
while (!isPalindrome(num)) {
long rev = reverse(num);
long sum = num + rev;
// Print step
[Link](num + " + " + rev + " = " + sum);
num = sum;
// Final result
[Link](num + " is a palindrome");
}
Why return is Important
When number is already palindrome:
✔ We print message
✔ We stop program immediately
✔ We avoid unnecessary execution
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link](); // total number of elements
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link](maxTripletSum(arr));
[Link]();
}
public static int maxTripletSum(int[] arr) {
int n = [Link];
int[] maxRight = new int[n];
maxRight[n - 1] = arr[n - 1];
// Store maximum value from right side
for (int i = n - 2; i >= 0; i--) {
maxRight[i] = [Link](arr[i], maxRight[i + 1]);
}
TreeSet<Integer> set = new TreeSet<>();
[Link](arr[0]);
int maxSum = 0;
for (int j = 1; j < n - 1; j++) {
Integer left = [Link](arr[j]); // largest element < arr[j]
if (left != null && maxRight[j + 1] > arr[j]) {
int sum = left + arr[j] + maxRight[j + 1];
maxSum = [Link](maxSum, sum);
}
[Link](arr[j]);
}
return maxSum;
}
}
In above program index should be i < j < k .
Why This Is Not Allowed
Even though:
4 < 5 < 9 ✅ (values increasing)
The positions are wrong:
index(4) > index(5)
maxRight[n - 1] = arr[n - 1]; means:
Start building right-side maximum array from the last element.
Because:
The last element’s right maximum is itself.
Then we move backwards.
for (int j = 1; j < n - 1; j++)
Let’s understand why it starts from 1
and why it ends at n-1 (actually n-2).
Why Stop at j < n - 1 ?
Loop condition:
j < n - 1
That means:
j≤n–2
Indexes 0 1 2 3 4 5
If:
j = 5
There is no index after 5.
So no k possible ❌
The program starts by reading the number of test cases T.
It then defines the array denominations containing the available currency
denominations (500, 100, 50, 20, 10, 5, 2, and 1).
For each test case, the program reads the amount N and checks if it is within the valid
range.
It then calculates how many notes of each denomination are needed to form the
amount N. This is done by dividing N by the current denomination, updating N by
taking the remainder, and printing the number of notes required for that denomination.
If N is not valid, it prints "Invalid Input".
Sample Input:
1
10020
Sample Output:
For amount 10020:
500 : 20
10 : 2
public class MinimumNotes {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input number of test cases
int T = [Link]();
// Array of denominations
int[] denominations = {500, 100, 50, 20, 10, 5, 2, 1};
// Process each test case
while (T-- > 0) {
int N = [Link]();
if (N < 1 || N > 10000) {
[Link]("Invalid Input");
continue;
[Link]("For amount " + N + ":");
for (int denomination : denominations) {
int count = N / denomination; // Calculate the number of notes of this denomination
N = N % denomination; // Update remaining amount
if (count > 0) {
[Link](denomination + " : " + count);
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input strings
String J = [Link](); // Jewels
String S = [Link](); // Stones
// Store jewels in a HashSet for fast lookup
Set<Character> jewelSet = new HashSet<>();
for (char ch : [Link]()) {
[Link](ch);
}
// Count how many stones are jewels
int count = 0;
for (char ch : [Link]()) {
if ([Link](ch)) {
count++;
}
}
// Output result
[Link](count);
[Link]();
}
}
import [Link].*;
import [Link].*;
public class Main {
static boolean isPerfectSquare(long x) {
long s = (long) [Link](x);
return s * s == x || (s + 1) * (s + 1) == x;
}
static boolean isPerfectCube(long x) {
long c = (long) [Link](x);
return c * c * c == x ||
(c + 1) * (c + 1) * (c + 1) == x ||
(c - 1) * (c - 1) * (c - 1) == x;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
int T = [Link]();
while (T-- > 0) {
int N = [Link]();
long[] A = new long[N];
for (int i = 0; i < N; i++) {
A[i] = [Link]();
long count = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
long sum = A[i] + A[j];
if (isPerfectSquare(sum) || isPerfectCube(sum)) {
count++;
[Link](count);
[Link]();
}
import [Link].*;
public class Main {
public static String nextGreater(String num) {
char[] arr = [Link]();
int n = [Link];
// Step 1: find first decreasing digit from right
int i = n - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
// If no such position, next permutation not possible
if (i < 0) return "Not possible";
// Step 2: find next greater digit on right side
int j = n - 1;
while (arr[j] <= arr[i]) {
j--;
}
// Step 3: swap
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// Step 4: reverse remaining part
int left = i + 1, right = n - 1;
while (left < right) {
char t = arr[left];
arr[left] = arr[right];
arr[right] = t;
left++;
right--;
}
return "Next number with same set of digits is " + new String(arr);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String N = [Link]();
// If input is single digit or 0
if ([Link]() <= 1) {
[Link]("Not possible");
} else {
[Link](nextGreater(N));
}
[Link]();
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int T = [Link]();
[Link](); // consume newline
while (T-- > 0) {
String A = [Link]();
String B = [Link]();
if ([Link]() == [Link]() && (A + A).contains(B)) {
[Link]("true");
} else {
[Link]("false");
[Link]();
}
or
public class Main {
public static int maxLengthBetweenEqualCharacters(String s) {
int n = [Link]();
int maxLen = -1;
// check every pair of equal characters
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ([Link](i) == [Link](j)) {
int length = j - i - 1; // exclude both characters
maxLen = [Link](maxLen, length); }
return maxLen;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String s = [Link](); // input
[Link](maxLengthBetweenEqualCharacters(s));
} }
int length = j - i - 1;
✅ Calculates number of characters **between them**.
Why `-1`?
- Because we exclude both equal characters.
public class Main {
public static int countValidSubarrays(int[] arr, int n) {
int count = 0;
// check all subarrays
for (int i = 0; i < n; i++) {
HashSet<Integer> set = new HashSet<>();
for (int j = i; j < n; j++) {
[Link](arr[j]);
int length = j - i + 1; // subarray length
// check if length exists in subarray
if ([Link](length)) {
count++;
} }
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int T = [Link](); // number of test cases
while (T-- > 0) {
int N = [Link]();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = [Link]();
[Link](countValidSubarrays(arr, N));
}
public class Main {
static boolean found = false;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
boolean[] used = new boolean[n];
List<Integer> result = new ArrayList<>();
backtrack(arr, used, result, n);
if (found) {
for (int num : result) {
[Link](num + " ");
}
}
[Link]();
}
static void backtrack(int[] arr, boolean[] used, List<Integer> result, int n) {
if ([Link]() == n) {
found = true;
return;
}
for (int i = 0; i < n; i++) {
if (!used[i]) {
if ([Link]() == 0 ||
getLastDigit([Link]([Link]() - 1)) == getFirstDigit(arr[i])) {
used[i] = true;
[Link](arr[i]);
backtrack(arr, used, result, n);
if (found) return;
used[i] = false;
[Link]([Link]() - 1);
}
}
}
}
static int getFirstDigit(int num) {
num = [Link](num);
while (num >= 10) {
num /= 10;
}
return num;
}
static int getLastDigit(int num) {
return [Link](num) % 10;
}
}
From ex:9+6+5=20;
S=20/3-1
=20/2
10
X1=10-9=1
X2=10-6=4
X3=10-5=5
145
import [Link].*;
public class Display {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int arr[] = new int[n];
// Read array elements
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
// Replace each element with next greatest element on right
for (int i = 0; i < n - 1; i++) {
int max = arr[i + 1];
for (int j = i + 1; j < n; j++) {
if (arr[j] > max) {
max = arr[j];
}
}
arr[i] = max;
}
// Last element becomes -1
arr[n - 1] = -1;
// Print result
[Link]("The modified array:");
for (int i = 0; i < n; i++) {
[Link](arr[i] + " ");
}
}
}
import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int N = [Link](); // user enters N
Queue<String> q = new LinkedList<>();
[Link]("1");
for (int i = 1; i <= N; i++) {
String current = [Link]();
[Link](current + " ");
[Link](current + "0");
[Link](current + "1");
} poll() remove first element from queue.