0% found this document useful (0 votes)
2 views56 pages

Level 5-LMS Java Patterns

Java programs in for Loop concept for practice
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views56 pages

Level 5-LMS Java Patterns

Java programs in for Loop concept for practice
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

public class Main {

// Function to calculate factorial under modulo


static long factorial(int n, long m) {
long result = 1;
for (int i = 1; i <= n; i++) {
result = (result * i) % m;
}
return result;
}
// Function to calculate nCr % m
static long nCr(int n, int r, long m) {
long nFact = factorial(n, m);
long rFact = factorial(r, m);
long nrFact = factorial(n - r, m);
long result = (nFact / (rFact * nrFact)) % m;
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link](); // input1
int r = [Link](); // input2
long m = [Link](); // input3
[Link](nCr(n, r, m));
}
}
public class StringPermutations {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
List<String> results = new ArrayList<>();
generatePermutations("", input, results);
// 1. Sort the results in ascending order
[Link](results);
// 2. Print the total count
[Link]([Link]());
// 3. Print each permutation
for (String s : results) {
[Link](s);
}
[Link]();
}
/**
* Recursive function to generate all unique permutations.
*/
private static void generatePermutations(String prefix, String remaining,
List<String> results) {
int n = [Link]();
if (n == 0) {
[Link](prefix);
} else {
for (int i = 0; i < n; i++) {
// Take one character and recurse with the rest
generatePermutations(
prefix + [Link](i),
[Link](0, i) + [Link](i + 1, n),
results
);
}
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input: number of coins
int m = [Link]();
// Input: coin values
int[] coins = new int[m];
for (int i = 0; i < m; i++) {
coins[i] = [Link]();
}
// Input: target amount
int N = [Link]();
// DP array
int[] dp = new int[N + 1];
// Base case
dp[0] = 1;
// Fill DP array
for (int i = 0; i < m; i++) {
for (int j = coins[i]; j <= N; j++) {
dp[j] += dp[j - coins[i]];
}
}
// Output result
[Link](dp[N]);
}
}

j - coin = 4 - 2 = 2 why hear j is 4

Good 👍 this is a very important doubt, let’s clear it completely.

j - coin = 4 - 2 = 2
👉 Why is j = 4 here?

🔷 Where does j come from?


From this loop:

for (int j = coin; j <= N; j++)

For coin = 2, loop becomes:

j = 2, 3, 4, 5

🔷 So j changes step by step


Iteration j value
1 2
2 3
3 4
4 5

Now your case: j = 4


👉 At one step in the loop:

j = 4
coin = 2

So we calculate:

j - coin = 4 - 2 = 2

What does this mean?


👉 We are currently trying to:

Find ways to make amount 4

🔷 Why subtract coin?


Because logic is:
To make j → use (j - coin) + coin

So for j = 4
To make 4:
→ first make 2
→ then add coin 2
Target = 4
Coin = 2

Step 1: Make 2
Step 2: Add 2

→ Total = 4

Why we don't fix j = 4 always?


👉 Because loop runs for all values:

j = 2 → build 2
j = 3 → build 3
j = 4 → build 4
j = 5 → build 5

Key Insight
👉 j is:

the current amount we are trying to build

So:

 When j = 4 → we are solving for amount 4


 When j = 5 → we are solving for amount 5
 coins = [1, 2, 3, 4, 5]
N = 5

 🔷 Initial DP Array
 dp = [1, 0, 0, 0, 0, 0]

 👉 Only dp[0] = 1, rest are 0

Using coin = 1
We run:

dp[j] += dp[j - 1]
Update step-by-step:
j Calculation dp array
1 dp[1] = 0 + dp[0] = 1 [1, 1, 0, 0, 0, 0]
2 dp[2] = 0 + dp[1] = 1 [1, 1, 1, 0, 0, 0]
3 dp[3] = 0 + dp[2] = 1 [1, 1, 1, 1, 0, 0]
4 dp[4] = 0 + dp[3] = 1 [1, 1, 1, 1, 1, 0]
5 dp[5] = 0 + dp[4] = 1 [1, 1, 1, 1, 1, 1]

After coin 1:

dp = [1, 1, 1, 1, 1, 1]

Step 2: Using coin = 2

dp[j] += dp[j - 2]

j Calculation dp array
2 dp[2] = 1 + dp[0] = 2 [1, 1, 2, 1, 1, 1]
3 dp[3] = 1 + dp[1] = 2 [1, 1, 2, 2, 1, 1]
4 dp[4] = 1 + dp[2] = 3 [1, 1, 2, 2, 3, 1]
5 dp[5] = 1 + dp[3] = 3 [1, 1, 2, 2, 3, 3]
After coin 2:

dp = [1, 1, 2, 2, 3, 3]

Using coin = 3

dp[j] += dp[j - 3]

j Calculation dp array
3 dp[3] = 2 + dp[0] = 3 [1, 1, 2, 3, 3, 3]
4 dp[4] = 3 + dp[1] = 4 [1, 1, 2, 3, 4, 3]
5 dp[5] = 3 + dp[2] = 5 [1, 1, 2, 3, 4, 5]
Using coin = 4

dp[j] += dp[j - 4]

j Calculation dp array
4 dp[4] = 4 + dp[0] = 5 [1, 1, 2, 3, 5, 5]
5 dp[5] = 5 + dp[1] = 6 [1, 1, 2, 3, 5, 6]
Using coin = 5

dp[j] += dp[j - 5]

j Calculation dp array
5 dp[5] = 6 + dp[0] = 7 [1, 1, 2, 3, 5, 7]
Final Answer

dp[5] = 7
import [Link].*;
public class Main {
public static int[][] mergeIntervals(int[][] intervals) {
// Sort using Comparator (no lambda)
[Link](intervals, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
List<int[]> result = new ArrayList<>();
int start = intervals[0][0];
int end = intervals[0][1];
for (int i = 1; i < [Link]; i++) {
int currStart = intervals[i][0];
int currEnd = intervals[i][1];
if (currStart <= end) {
end = [Link](end, currEnd);
} else {
[Link](new int[]{start, end});
start = currStart;
end = currEnd;
}
}
[Link](new int[]{start, end});
return [Link](new int[[Link]()][]);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input as string
String input = [Link]();
// Remove outer brackets [[ ]]
input = [Link](2, [Link]() - 2);
// Split intervals
String[] parts = [Link]("\\], \\[");
int[][] intervals = new int[[Link]][2];
// Convert string to int array
for (int i = 0; i < [Link]; i++) {
String[] nums = parts[i].split(",");
intervals[i][0] = [Link](nums[0]);
intervals[i][1] = [Link](nums[1]);
}
// Merge intervals
int[][] result = mergeIntervals(intervals);
// Print output
[Link]("[");
for (int i = 0; i < [Link]; i++) {
[Link]("[" + result[i][0] + "," + result[i][1] + "]");
if (i != [Link] - 1) {
[Link](", ");
}
}
[Link]("]");
}
}.

public class Main {


// Parse intervals using substring method
public static int[][] parseIntervals(String input) {
// Remove spaces
input = [Link]("\\s", "");
// Remove outer [[ ]]
input = [Link](2, [Link]() - 2);
// Split into individual intervals
String[] parts = [Link]("\\],\\[");
int[][] intervals = new int[[Link]][2];
for (int i = 0; i < [Link]; i++) {
String[] nums = parts[i].split(",");
intervals[i][0] = [Link](nums[0]);
intervals[i][1] = [Link](nums[1]);
}
return intervals;
}
// Parse new interval
public static int[] parseNewInterval(String input) {
input = [Link]("\\s", "");
input = [Link](1, [Link]() - 1);
String[] nums = [Link](",");
return new int[]{
[Link](nums[0]),
[Link](nums[1])
};
}
// Insert interval logic
public static int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> result = new ArrayList<>();
int i = 0;
int n = [Link];
// 1. Add intervals before new interval
while (i < n && intervals[i][1] < newInterval[0]) {
[Link](intervals[i]);
i++;
}
// 2. Merge overlapping intervals
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = [Link](newInterval[0], intervals[i][0]);
newInterval[1] = [Link](newInterval[1], intervals[i][1]);
i++;
}
// 3. Add merged interval
[Link](newInterval);
// 4. Add remaining intervals
while (i < n) {
[Link](intervals[i]);
i++;
}
return [Link](new int[[Link]()][]);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input intervals
[Link]("Enter intervals (e.g. [[1,3],[6,9]]): ");
String intervalInput = [Link]();
// Input new interval
[Link]("Enter new interval (e.g. [2,5]): ");
String newIntervalInput = [Link]();
// Parse inputs
int[][] intervals = parseIntervals(intervalInput);
int[] newInterval = parseNewInterval(newIntervalInput);
// Process
int[][] result = insert(intervals, newInterval);
// Output
[Link]("Result:");
for (int[] arr : result) {
[Link]("[" + arr[0] + "," + arr[1] + "]");
}
[Link]();
}
}
Existing: [1---3] [6---9]

New: [2------5]

After merge:

[1------5]

Final:

[1------5] [6---9]
import [Link].*;

public class Solution {

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

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

int rs = 0;

int cls = 0;

int re = [Link] - 1;

int cle = matrix[0].length - 1;

while (rs <= re && cls <= cle) {

// Top row

for (int i = cls; i <= cle; i++) {

[Link](matrix[rs][i]);

rs++;

// Right column

for (int i = rs; i <= re; i++) {

[Link](matrix[i][cle]);

}
cle--;

// Bottom row

if (rs <= re) {

for (int i = cle; i >= cls; i--) {

[Link](matrix[re][i]);

re--;

// Left column

if (cls <= cle) {

for (int i = re; i >= rs; i--) {

[Link](matrix[i][cls]);

cls++;

return ans;

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input rows and columns

[Link]("Enter number of rows: ");

int m = [Link]();

[Link]("Enter number of columns: ");

int n = [Link]();

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

// Input matrix

[Link]("Enter matrix elements:");

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

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


matrix[i][j] = [Link]();

// Call function

List<Integer> result = spiralOrder(matrix);

// Output

[Link]("Spiral Order:");

for (int num : result) {

[Link](num + " ");

Why we use Increment (++) and Decrement (--)

In your code, these variables represent boundaries of the matrix:

 rs → row start (top boundary)


 re → row end (bottom boundary)
 cls → column start (left boundary)
 cle → column end (right boundary)

What happens in Spiral?

We move layer by layer like this:

⬇️ Right column
➡️ Top row

⬆️ Left column
⬅️ Bottom row

After completing one round, we shrink the boundaries.

Why rs++ (Increment row start)?

After printing the top row, that row is DONE ✅


So we move boundary down

rs++;

👉 Means: "Next time, start from the next row"


Why re-- (Decrement row end)?

After printing the bottom row, it's DONE ✅


So we move boundary up

re--;
Means: "Ignore last row now"

Why cls++ (Increment column start)?

After printing the left column, it's DONE ✅


So move boundary right

cls++;

🔽 Why cle-- (Decrement column end)?

After printing the right column, it's DONE ✅


So move boundary left

cle--;

🎯 Simple Visualization

Imagine peeling an onion 🧅 layer by layer:

Initial:
[ rs .......... re ]
[ ................ ]
[ cls cle ]

rs moves down ⬇️
After one round:

re moves up ⬆️
cls moves right ➡️
cle moves left ⬅️
Operation Why
rs++ Top row already used
re-- Bottom row already used
cls++ Left column already used
cle-- Right column already used
Why we use if conditions?

These two conditions:

if (rs <= re)


if (cls <= cle)

are used to avoid duplicate traversal and errors.


🔴 Problem WITHOUT if

When the matrix becomes small (like 1 row or 1 column left), your loop might:

 Traverse the same row/column again ❌


 Or go out of bounds ❌

✅ Case 1: Why if (rs <= re)


if (rs <= re) {
for (int i = cle; i >= cls; i--) {
[Link](matrix[re][i]);
}
re--;
}

👉 This is for the bottom row

💡 Why needed?

After moving:

 Top row (rs++)


 Right column (cle--)

Sometimes no bottom row remains.

❌ Without if:

You might print the same row twice.

🔍 Example

Matrix:

1 2 3
4 5 6

After top & right traversal:

 rs = 1
 re = 1

Only one row left

If you don’t check:


👉 Bottom row will print again → duplicate
✅ Case 2: Why if (cls <= cle)
if (cls <= cle) {
for (int i = re; i >= rs; i--) {
[Link](matrix[i][cls]);
}
cls++;
}

👉 This is for the left column

💡 Why needed?

After:

 Right column processed


 Boundaries shrink

Sometimes no column remains

🔍 Example

Matrix:

1
2
3

Only one column.

Without if:
👉 Left column will print again ❌

🎯 Key Idea

These conditions ensure:

✔ We only traverse when something is left


✔ No duplicate printing
✔ No invalid index access
🔑 Simple Rule
Condition Purpose

rs <= re Check if rows still exist

cls <= cle Check if columns still exist

public class Solution {

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

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

int rs = 0;

int cls = 0;

int re = [Link] - 1;

int cle = matrix[0].length - 1;

while (rs <= re && cls <= cle) {

// 1. Left column (TOP → BOTTOM)

for (int i = rs; i <= re; i++) {

[Link](matrix[i][cls]);

cls++;

// 2. Bottom row (LEFT → RIGHT)


for (int i = cls; i <= cle; i++) {

[Link](matrix[re][i]);

re--;

// 3. Right column (BOTTOM → TOP)

if (cls <= cle) {

for (int i = re; i >= rs; i--) {

[Link](matrix[i][cle]);

cle--;

// 4. Top row (RIGHT → LEFT)

if (rs <= re) {

for (int i = cle; i >= cls; i--) {

[Link](matrix[rs][i]);

rs++;

return ans;

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter number of rows: ");

int m = [Link]();

[Link]("Enter number of columns: ");

int n = [Link]();

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

[Link]("Enter matrix elements:");

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

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


matrix[i][j] = [Link]();

List<Integer> result = spiralOrder(matrix);

[Link]("Anti-Clockwise Spiral Order:");

for (int num : result) {

[Link](num + " ");

}
public class Solution {

// Parse list of intervals like [[1,3],[5,6]]

public static int[][] parseIntervals(String input) {

input = [Link]("\\s", ""); // remove spaces

input = [Link](2, [Link]() - 2); // remove [[ ]]

String[] parts = [Link]("\\],\\[");

int[][] intervals = new int[[Link]][2];


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

String[] nums = parts[i].split(",");

intervals[i][0] = [Link](nums[0]);

intervals[i][1] = [Link](nums[1]);

return intervals;

// Intersection logic (same as before)

public static int[][] intervalIntersection(int[][] firstList, int[][] secondList) {

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

int i = 0, j = 0;

while (i < [Link] && j < [Link]) {

int start = [Link](firstList[i][0], secondList[j][0]);

int end = [Link](firstList[i][1], secondList[j][1]);

if (start <= end) {

[Link](new int[]{start, end});

if (firstList[i][1] < secondList[j][1]) {

i++;

} else {

j++;

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

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input as string

[Link]("Enter first interval list (e.g. [[1,3],[5,6]]):");

String firstInput = [Link]();

[Link]("Enter second interval list (e.g. [[2,5],[7,8]]):");


String secondInput = [Link]();

int[][] firstList = parseIntervals(firstInput);

int[][] secondList = parseIntervals(secondInput);

int[][] ans = intervalIntersection(firstList, secondList);

// Output

[Link]("Intersection intervals:");

for (int[] interval : ans) {

[Link]("[" + interval[0] + ", " + interval[1] + "]");

Why start <= end?

Because:

 If start > end → no overlap


 If start == end → touching point (still valid intersection)

5. Move the pointer intelligently


if (firstList[i][1] < secondList[j][1]) {
i++;
} else {
j++;
}

👉 You move the pointer of the interval that ends earlier

Why?

Because:

 That interval cannot overlap with future intervals anymore


 So you discard it and move forward

📊 Example Walkthrough
Input:
firstList = [[1,3],[5,6]]
secondList = [[2,5],[7,8]]
Step-by-step:
firstList[i] secondList[j] Overlap

[1,3] [2,5] [2,3]

[5,6] [2,5] [5,5]

[5,6] [7,8] none

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

🚀 Key Insights

 Uses two pointers → efficient traversal


 Time complexity: O(n + m)
 Works because intervals are assumed sorted

🧩 Summary

 Compare current intervals from both lists


 Compute overlap using max(start) and min(end)
 Add valid intersections
 Move the pointer of the interval that finishes first
public class CarPooling {
public static boolean carPooling(int[][] trips, int capacity) {
int[] arr = new int[1001];
// Mark pick-up and drop points
for (int i = 0; i < [Link]; i++) {
int numPassengers = trips[i][0];
int from = trips[i][1];
int to = trips[i][2];
arr[from] += numPassengers;
arr[to] -= numPassengers;
}
int currentPassengers = 0;
// Check capacity
for (int i = 0; i < 1001; i++) {
currentPassengers += arr[i];
if (currentPassengers > capacity) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input number of trips
int capacity = [Link]();
int n = [Link]();
int[][] trips = new int[n][3];
// Input trips
[Link]("Enter trips (numPassengers from to):");
for (int i = 0; i < n; i++) {
trips[i][0] = [Link](); // passengers
trips[i][1] = [Link](); // from
trips[i][2] = [Link](); // to
}

boolean result = carPooling(trips, capacity);


[Link](result);
}
}
public class Main {

public int findMinArrow(int[][] points) {

if (points == null || [Link] == 0) {

return 0;

[Link](points, (a, b) -> [Link](a[1], b[1]));

int arrows = 1;

int arrowPos = points[0][1];

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

if (points[i][0] > arrowPos) {

arrows++;

arrowPos = points[i][1];

return arrows;

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

int n = [Link]();
int points[][] = new int[n][2];

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

points[i][0] = [Link]();

points[i][1] = [Link]();

Main obj = new Main();

int result = [Link](points);

[Link](result);

}
import [Link].*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String input = [Link]();
char[] chars = [Link]();
[Link](chars); // sort to help avoid duplicates
boolean[] used = new boolean[[Link]];
List<String> result = new ArrayList<>();
generate(chars, used, new StringBuilder(), result);
[Link]([Link]());
for (String s : result) {
[Link](s);
}
}
public static void generate(char[] chars, boolean[] used, StringBuilder current, List<String>
result) {
if ([Link]() == [Link]) {
[Link]([Link]());
return;
}
for (int i = 0; i < [Link]; i++) {
// Skip already used characters
if (used[i]) continue;
// Skip duplicates
if (i > 0 && chars[i] == chars[i - 1] && !used[i - 1]) continue;
used[i] = true;
[Link](chars[i]);
generate(chars, used, current, result);
// Backtrack
[Link]([Link]() - 1);
used[i] = false;
}
}
}
public class Main {
public static void countPerStudent(int[] subjects, int[] students) {
[Link](subjects); // sort subjects
for (int i = 0; i < [Link]; i++) {
int count = countLessThan(subjects, students[i]);
[Link]("Student " + (i + 1) + ": " + count);
}
}
// Binary search: count of elements < target
public static int countLessThan(int[] arr, int target) {
int left = 0, right = [Link] - 1;
int ans = 0;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] < target) { // STRICTLY LESS THAN
ans = mid + 1;
left = mid + 1;
} else {
right = mid - 1;
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int K = [Link]();
int[] subjects = new int[K];
for (int i = 0; i < K; i++) {
subjects[i] = [Link]();
}
int N = [Link]();
int[] students = new int[N];
for (int i = 0; i < N; i++) {
students[i] = [Link]();
}
countPerStudent(subjects, students);
}
}
public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

if (![Link]()) return;

int t = [Link](); // Number of test cases

while (t-- > 0) { int n = [Link]();

int[] a = new int;

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

a[i] = [Link]();

int target = [Link]();

// 1. Sort the array to handle duplicates and ensure non-descending order

[Link](a);

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

findCombinations(0, a, target, new ArrayList<>(), results);

// 2. Print results in the specified format


if ([Link]()) {

[Link]("Empty");

} else {

StringBuilder sb = new StringBuilder();

for (List<Integer> combo : results) {

[Link]("(");

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

[Link]([Link](i)).append(i == [Link]() - 1 ? "" : " ");

[Link](")");

[Link]([Link]());

[Link]();

private static void findCombinations(int index, int[] a, int target, List<Integer> current,
List<List<Integer>> results) {

if (target == 0) {

[Link](new ArrayList<>(current));

return;

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

// Skip duplicate elements at the same recursion level

if (i > index && a[i] == a[i - 1]) continue;

// Optimization: if the current element exceeds the target, stop this branch

if (a[i] > target) break;


[Link](a[i]);

// Move to i + 1 because each element can be used only once

findCombinations(i + 1, a, target - a[i], current, results);

[Link]([Link]() - 1); // Backtrack

} or

import [Link].*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

if (![Link]()) return;

int t = [Link](); // number of test cases

[Link](); // consume newline

while (t-- > 0) {

// Read array as space-separated integers

String line = [Link]();

String[] parts = [Link]().split("\\s+");

int[] a = new int[[Link]];

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

a[i] = [Link](parts[i]);

int target = [Link]();

[Link](); // consume newline

// Sort array

[Link](a);

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

findCombinations(0, a, target, new ArrayList<>(), results);


// Print results

if ([Link]()) {

[Link]("Empty");

} else {

StringBuilder sb = new StringBuilder();

for (List<Integer> combo : results) {

[Link]("(");

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

[Link]([Link](i));

if (i != [Link]() - 1) [Link](" ");

[Link](")");

[Link]([Link]());

[Link]();

private static void findCombinations(int index, int[] a, int target,

List<Integer> current,

List<List<Integer>> results) {

if (target == 0) {

[Link](new ArrayList<>(current));

return;

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

// Skip duplicates

if (i > index && a[i] == a[i - 1]) continue;

// Stop if element exceeds target

if (a[i] > target) break;


[Link](a[i]);

findCombinations(i + 1, a, target - a[i], current, results);

[Link]([Link]() - 1); // backtrack

}
public static int removeoverlap(int intervals[][]){

[Link](intervals, new Comparator<int[]>() {

public int compare(int a[], int b[]) {

return a[0] - b[0];

});

int end = intervals[0][1];

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

int currentstart = intervals[i][0];

int currentEnd = intervals[i][1];

// overlap condition (strict)

if(currentstart < end){

count++;

// keep the interval with smaller end

end = [Link](end, currentEnd);

} else {

// no overlap

end = currentEnd;

return count;

Given Input
[1,2], [2,3], [3,4], [1,3]
✅ After Sorting
[1,2], [1,3], [2,3], [3,4]
Step-by-step Diagram (Simplified)
Step 1: Start
[1------2]
end = 2

Step 2: Compare with [1,3]


[1------2]
[1-----------3]

❌ Overlap (1 < 2)

👉 Remove one interval


👉 Keep the one with smaller end

✔ Keep:

[1------2]

🧮 count = 1
Step 3: Compare with [2,3]
[1------2] [2------3]

✅ No overlap (just touching)

✔ Keep both

end = 3

Step 4: Compare with [3,4]


[2------3] [3------4]

✅ No overlap

✔ Keep both

end = 4

✅ Final Kept Intervals


[1,2], [2,3], [3,4]

You might also like