Sitemap
Kirti Konka

Kirti Konka

Learning, building, and evolving—every step shaping the developer I'm becoming.

All in one — Java Basic Programs

33 min readJan 4, 2026

Prime Number or Not
A prime number is a whole number greater than 1 that has exactly two distinct positive divisors.

// Brute Force
Time: O(n)
Space: O(1)

public static boolean isPrime(int n) {
if (n < 2) {
return false;
}

for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}

return true;
}

// Sqrt Optimization
Time: O(√n)
Space: O(1)
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}

for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}

return true;
}

//Odd Divisor Optimization
Time: O(√n)
Space: O(1)
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}

if (n == 2) {
return true;
}

if (n % 2 == 0) {
return false;
}

for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}

return true;
}

// Sieve of Erantosthenes
Time: O(n log log n)
Space: O(n)
public static boolean[] sieve(int n) {

boolean[] isPrime = new boolean[n + 1];

Arrays.fill(isPrime, true);

isPrime[0] = false;
isPrime[1] = false;

for (int i = 2; i * i <= n; i++) {

if (isPrime[i]) {

for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}

return isPrime;
}

// Segmented Sieve
public static List<Integer> segmentedSieve(int L, int R) {

int limit = (int) Math.sqrt(R);

boolean[] smallPrime = new boolean[limit + 1];
Arrays.fill(smallPrime, true);

smallPrime[0] = false;
smallPrime[1] = false;

for (int i = 2; i * i <= limit; i++) {

if (smallPrime[i]) {
for (int j = i * i; j <= limit; j += i) {
smallPrime[j] = false;
}
}
}

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

for (int i = 2; i <= limit; i++) {
if (smallPrime[i]) {
primes.add(i);
}
}

boolean[] segment = new boolean[R - L + 1];
Arrays.fill(segment, true);

for (int p : primes) {

int start = Math.max(
p * p,
((L + p - 1) / p) * p
);

for (int j = start; j <= R; j += p) {
segment[j - L] = false;
}
}

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

for (int i = 0; i < segment.length; i++) {

if (segment[i] && L + i >= 2) {
result.add(L + i);
}
}

return result;
}

// Miller Rabin
static long modPow(long a, long d, long mod) {

long result = 1;

a %= mod;

while (d > 0) {

if ((d & 1) == 1) {
result = (result * a) % mod;
}

a = (a * a) % mod;
d >>= 1;
}

return result;
}
                PRIME NUMBER
│
┌───────────┴───────────┐
│ │
ONE NUMBER MANY NUMBERS
│ │
│ ┌─────┴─────┐
│ │ │
√n test N range [L,R]
│ │ │
┌────┴────┐ Sieve Segmented Sieve
│ │
Normal Odd/6k±1
│
└─── Large n ───→ Miller-Rabin

Prime Factors

// TC - O(n√n)
import java.util.Scanner;
public class Main {
public static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 24
System.out.print("Prime factors of " + n + ": ");
boolean first = true;
for (int i = 1; i <= n; i++) {
if (n % i == 0 && isPrime(i)) {
if (!first) {
System.out.print(", ");
}
System.out.print(i);
first = false;
}
}
System.out.println(); // 2, 3
}
}

Sum of the digits in a number

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 5 // 25
int sum = 0;
while (n > 0)
{
int lastDigit = n % 10;
sum = sum + lastDigit;
n = n / 10;
}
System.out.println(sum); // 5 // 7
}
}

Palindrome or Not

import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
// Reverse the order and see if it is same as original or not
// 701 =? 107
// 101 =? 101
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int x = N;
int rev = 0;
while (x > 0)
{
int lastDigit = x % 10;
rev = rev * 10 + lastDigit;
x = x / 10;
}
if(N == rev)
{
System.out.println("Palindrome");
}
else
{
System.out.println("Not Palindrome");
}
}
}
// Two Pointers
// s = "a b c c b a"
// i j
// i = 0;
// j = s.length() - 1

public static void main(String[] args)
{
StringBuilder s = new StringBuilder(s);
String s = "abcdef";
int i = 0;
j = s.length() - 1;
boolean isFlag = true;
while(i < j)
{
if(s.charAt(i) != s.charAt(j))
{
isFlag = false;
break;
}
i++;
j--;
}
if(isFlag == true)
{
System.Out.Println("Is Palindrome");
}
else
{
System.Out.Println("Is not Palindrome");
}
}

Armstrong or Not

import java.util.Scanner;
public class Main{
public static int powerFn(int a, int b)
{
int ans = 1;
for(int i = 1; i <= b; i++)
{
ans = ans * a;
}
return ans;
}
public static void main(String[] args)
{
// If sum is same as original number or not
// Step 1 - Count number of digits present - 704 = 3 -> d
// Step 2 - (lastDigit)^d = n
// Step 3 - sum == n ?

// Example
// 7^3 + 0^3 + 4^3 =? 704
// 1^4 + 6^4 + 3^4 + 4^4 =? 1634
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int copyN = n;
int numberOfDigits = 0;
while(n > 0)
{
// Calculate how many digits we have
numberOfDigits ++;
n = n / 10;
}
int sum = 0;
copyN = n;
while(n > 0)
{
int lastDigit = copyN % 10;
sum = sum + powerFn(lastDigit, numberOfDigits); // Main logic
copyN = copyN / 10;
}
if(sum == n)
{
System.out.println("Armstrong");
}
else
{
System.out.println("Not Armstrong");
}
}
}
import java.util.Scanner;
class Main {
public static boolean isArmstrong(int n)
{
int copy = n;
int sum = 0;
while(n > 0)
{
int lastDigit = n%10; // find last Digit
// sum of cube of digit
sum = sum + lastDigit * lastDigit * lastDigit;
n = n/10; // remove last digit
}
if(sum == copy)
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=1; i<=n; i++)
{
if(isArmstrong(i) == true)
{
System.out.println(i);
}
}
}
}

Armstrong numbers between 1 and N

import java.util.Scanner;
public class Main {
public static int powerFn(int a , int b)
{
int ans = 1;
for(int i = 1; i <= b; i++)
{
ans = ans * a;
}
return ans;
}

public static boolean Armstrong(int N)
{
int x = N;
int count = 0;
int sum = 0;

while(x > 0)
{
count++;
x /= 10;
}

x = N;

while(x > 0)
{
int lastDigit = x % 10;
sum += powerFn(lastDigit, count);
x /= 10;
}

return sum == N;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int st = in.nextInt();
int end = in.nextInt();

for(int i = st; i <= end; i++)
{
if(Armstrong(i))
{
System.out.print(i + " ");
}
}
}
}

Fibonacci Series up to N terms

public class Main {
public static void main(String[] args) {

int n = 10;

if (n <= 0) {
return;
}

int fTerm = 0;
int sTerm = 1;

if (n >= 1) System.out.print(fTerm);
if (n >= 2) System.out.print(" " + sTerm);

for (int i = 3; i <= n; i++) {
int tTerm = fTerm + sTerm;
System.out.print(" " + tTerm);
fTerm = sTerm;
sTerm = tTerm;
}
// 0 1 1 2 3 5 8 13 21 34
}
}

Binary to Decimal

public class Main{
public static void main(String[] args)
{
int n = 1010; // Binary
int power = 1;
int sum = 0;
while(n > 0)
{
int lastDigit = n % 10;
sum = sum + lastDigit * power;
power = power * 2;
n = n / 10;
}
System.out.println(sum); // 10 -> Decimal
}
}

// Optimised
public class Main{
public static void main(String[] args)
{
String binary = "1010";
int sum = 0;
int power = 1;

for(int i = binary.length() - 1; i >= 0; i--) {
int digit = binary.charAt(i) - '0';
sum += digit * power;
power *= 2;
}
System.out.println(sum); // 10 -> Decimal
}
}

Decimal To Binary

public static void decimalToBinary(int n) {
StringBuilder sb = new StringBuilder();

while (n > 0) {
sb.append(n % 2); // remainder (0 or 1)
n /= 2;
}

System.out.println(sb.reverse().toString());
}

// Another approach
public static void decimalToBinaryBitwise(int n) {
StringBuilder sb = new StringBuilder();

while (n > 0) {
sb.append(n & 1); // extract last bit
n = n >> 1; // shift right
}

System.out.println(sb.reverse().toString());
}

Patterns — Part 1

Patterns — Part 2

Get Kirti Konka’s stories in your inbox

Join Medium for free to get updates from this writer.

Find nCr

import java.util.Scanner;

public class Main {

public static long factorial(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

public static long nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);
int n = in.nextInt(); // 5
int r = in.nextInt(); // 2

if (n < 0 || r < 0 || r > n) {
System.out.println("Invalid input: ensure 0 ≤ r ≤ n");
return;
}

long result = nCr(n, r); // 10

System.out.println("nCr (" + n + "C" + r + ") = " + result);
}
}

nPr = n! / (n-r)!

import java.util.Scanner;

public class Main {

public static long factorial(int n) {
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);
int n = in.nextInt(); // 5
int r = in.nextInt(); // 2

if (n < 0 || r < 0 || r > n) {
System.out.println("Invalid input: ensure 0 ≤ r ≤ n");
return;
}

long nFact = factorial(n);
long nrFact = factorial(n - r);
long nPr = nFact / nrFact; // 20

System.out.println("nPr (" + n + "P" + r + ") = " + nPr);
}
}

Check if an element is present in an array or not?

import java.util.Scanner;
public static boolean ifElementPresent(int arr[], int target)
{
for(int i = 0; i < arr.length; i++)
{
if(arr[i] == target)
{
return true;
}
return false;
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int target = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
if(ifElementPresent(arr, target) == true)
{
System.Out.Println("Element is Present");
}
else
{
System.Out.Println("Element is absent");
}
}

Minimum, Maximum

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
int maximum = arr[0];
int minimum = arr[0];
for(int i = 1; i < n; i++)
{
if(arr[i] > maximum)
{
maximum = arr[i];
}
if(arr[i] < minimum)
{
minimum = arr[i];
}
}
System.Out.Println(maximum);
System.Out.Println(minimum);
}

Check if an array is sorted or not

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt(); // entering values in the array
}
boolean isArraySorted = true;
for(int = 0; i < n - 1; i++)
{
if(arr[i] > arr[i+1]) // main logic
{
isArraySorted = false;
break;
}
}
if(isArraySorted = true)
{
System.Out.Println("Array is Sorted");
}
else
{
System.Out.Println("Array is not Sorted");
}
}

Insert an element in an array at a specific position.

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt(); // entering values in the array
}
int value = in.nextInt();
int position = in.nextInt();
int answer[] = new int[n + 1];
int i = 0;
int j = 0;
while(i < n+1)
{
if(i == position - 1)
{
answer[i] = value;
}
else
{
answer[i] = arr[j];
j ++;
}
}
while(i < n+1)
{
System.Out.Println(answer[i] + " ");
}
}

Put even & odd elements of the array in 2 separate arrays

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt(); // entering values in the array
}
int countEven = 0;
int countOdd = 0;
for(int i = 0; i < n; i++)
{
if(arr[i] % 2 == 0)
{
countEven++;
}
else
{
countOdd++;
}
}
if(countEven > 0) // even array
{
int indexEven = 0;
int even[] = new int[countEven];
for(int i = 0; i < n; i++)
{
if(arr[i] % 2 == 0)
{
even[indexEven] = arr[i];
indexEven++;
System.Out.Println(arr[i] + " ");
}
System.Out.Println();
}
}
if(countOdd > 0) // odd array
{
int indexOdd = 0;
int odd[] = new int[countOdd];
for(int i = 0; i < n; i++)
{
if(arr[i] % 2 == 0)
{
odd[indexOdd] = arr[i];
indexOdd++;
System.Out.Println(arr[i] + " ");
}
System.Out.Println();
}
}
}

Smallest & second smallest in array

// 12 25 8 55 10 33
// arr[i] < minE
// secondMin = minE
// minE = arr[i]

// arr[i] > minE && arr[i] < secondMin
// secondMin = arr[i]

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
int minE = (int)(1e9);
int SminE = (int)(1e9);
for(int i = 0; i < n; i++)
{
if(arr[i] < minE)
{
SminE = minE;
minE = arr[i];
}
else if(arr[i] > minE && arr[i] < SminE)
{
SminE = arr[i];
}
}
System.Out.Println(minE);
System.Out.Println(SminE);
}

Reverse an array

// 5 1 6 2 3
// swap (arr[i], arr[j]) // odd array
// 3 2 6 1 5

// 5 1 6 2 3 7
// swap (arr[i], arr[j]) // even array
// 7 3 2 6 1 5

// if i & j are at same index then break the loop
// for swapping -> always use while loop

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
int i = 0;
int j = n - 1;
while(i < j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
for(int i = 0; i < n; i++)
{
System.Out.Println(arr[i] + " ");
}
}

Given a sorted array, find the median(increasing/decreasing)

// n -> length of an array
// arr(n/2) + arr(n/2 - 1) /2 // for even array
// arr(n/2) // for odd array

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
if(n % 2 != 0)
{
System.Out.Println(arr[n/2]);
}
else
{
double median = (double)(arr(n/2) + arr(n/2 - 1) / 2.0);
System.Out.Println(median);
}
}

Rotational Array — Right-rotate the array by n positions. — link

public void rotate(int[] nums, int k) {
int n = nums.length;
k = k % n;

reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);
}

private void reverse(int[] nums, int left, int right) {
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
// 1 2 3 4 5 // K = 3
// 2 3 4 5 1 // rotate 1
// 3 4 5 1 2 // rotate 2
// 4 5 1 2 3 // rotate 3

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
int reversed[] = new int[n];
k = k % n;
for(int i = 0; i < n; i++)
{
int newIndex = (i - k); // for greater than zero
// i - k + n // for less than zero
if(newIndex < 0)
{
newIndex += n;
}
reversed[newIndex] = arr[i];
}
for(int i = 0; i < n; i++)
{
System.Out.Println(reversed[i] + " ");
}
}
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// Input size of array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array: ");
int size = scanner.nextInt();
int[] arr = new int[size];

// Input elements of array
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Enter number of times to left rotate: ");
int count = scanner.nextInt();

// Actual rotation
count = ((count % size) + size) % size;

// Print array before rotation
System.out.println("Array before rotation");
printArray(arr);

// Rotate array N times
for (int i = 1; i <= count; i++) {
rotateByOne(arr);
}

// Print array after rotation
System.out.println("Array after rotation");
printArray(arr);

scanner.close();
}

public static void rotateByOne(int[] arr) {
int size = arr.length;
// Store the last element of array
int last = arr[size - 1];
for (int j = 1; j <= size - 1; j++){
// Move each array element to its right
arr[size - j] = arr[size - 1 - j];
}
// Copies the last element of array to the first
arr[0]= last;
}

// Print the given array
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// Input size of array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array: ");
int size = scanner.nextInt();
int[] arr = new int[size];

// Input elements of array
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Enter number of times to left rotate: ");
int count = scanner.nextInt();

// Actual rotation
count = ((count % size) + size) % size;

// Print array before rotation
System.out.println("Array before rotation");
printArray(arr);

// Rotate array N times
// Reversing the whole array
swap(arr, 0, size - 1);
// Reversing the first count elements
swap(arr, 0, count - 1);
// Reversing the elements after count elements
swap(arr, count, size - 1);
int i = 0, j = size - 1;

// Print array after rotation
System.out.println("Array after rotation");
printArray(arr);

scanner.close();
}
public static void swap(int[] arr, int start, int end){
while(start <= end){
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
// Print the given array
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
// Original array
// 1 2 3 4 5
// k = 1
// 5 1 2 3 4

// if k is equl to nums.length even after rotating k times we get the
// original array
// Rotation is cyclic

// if k is greater than nums.length
// use k = k % nums.length

// Ex 1 2 3 4 5 6 7
// k = 3
// 1 2 3 4 5 6 7 // here 5 6 7 will go in the start
// step 1 - reverse whole array
// 7 6 5 4 3 2 1

// reverse necessary part
// 0 - (k - 1) // first part
// k - (n - 1) // second part
// 7 6 5 4 3 2 1
// _____ _______
// 5 6 7 1 2 3 4
// 5 6 7 1 2 3 4 // output

class Solution{
public void reverse(int[] nums, int start, int end)
{
while(start < end)
{
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
public void rotate(int[] nums, int k)
{
int n = nums.length;
k = k % n;
reverse(nums, 0, n-1); // entire array
reverse(nums, 0, k-1); // first k elements
reverse(nums, k, n-1); // n-k elements
}
}

Search for an element in an array and pass its index

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
int answer = -1;
for(int i = 0; i < n; i++)
{
if(arr[i] == k)
{
answer = i;
break;
}
}
System.Out.Println(answer);
}

Print row-wise traversal of a 2D array — link

// Nested Loops
// Outer -> Row
// Inner -> Column

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int arr[][] = new int[n][m];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
arr[i][j] = in.nextInt();
}
}
for(int i = 0; i < n; i++) // Row
{
for(int j = 0; j < m; j++) // Col
{
System.Out.Println(arr[i][j] + " ");
}
System.Out.Println();
}
}

Print column-wise traversal of a 2D array

// Nested Loops
// Outer -> Column
// Inner -> Row

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int arr[][] = new int[n][m];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
arr[i][j] = in.nextInt();
}
}
for(int i = 0; i < m; i++) // Col
{
for(int j = 0; j < n; j++) // Row
{
System.Out.Println(arr[i][j] + " ");
}
System.Out.Println();
}
}

Sum of each Row & each Column in a 2D array — link

// outer loop // row
// sum of i,j with
// inner loop // column
// print sum

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int arr[][] = new int[n][m];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
arr[i][j] = in.nextInt();
}
}
for(int i = 0; i < n; i++) // row
{
int sum= 0;
for(int j = 0; j < m; j++)
{
sum += arr[i][j];
}
System.Out.Println(sum);
}
for(int i = 0; i < m; i++) // column
{
int sum= 0;
for(int j = 0; j < n; j++)
{
sum += arr[i][j];
}
System.Out.Println(sum);
}
}

Sum of Diagonal elements in a 2D array — link

// \   /
// \ /
// / \
// / \

// right diagonal -> i + j = n - 1
// left diagonal -> i == j

// square matrix -> n = m
// rectangle matrix -> n != m

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int arr[][] = new int[n][m];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
arr[i][j] = in.nextInt();
}
}
int sumL = 0;
int sumR = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(i == j) // Left Diagonal
{
sumL += arr[i][j];
}
if((i + j) == n - 1) // Right Diagonal
{
sumR += arr[i][j];
}
}
}
System.Out.Println(sumL);
System.Out.Println(sumR);
}
public static void diagonalSum(int[][] arr, int n, int m) {
int sumL = 0, sumR = 0;

int limit = Math.min(n, m);

for (int i = 0; i < limit; i++) {
// Left diagonal
sumL += arr[i][i];

// Right diagonal
int j = m - 1 - i;
if (j >= 0 && j < m) {
sumR += arr[i][j];
}
// Edge case: If n == m and odd size
if (n == m && n % 2 == 1) {
int mid = n / 2;
sumR -= arr[mid][mid]; // avoid double count
}
}

System.out.println("Left Diagonal Sum: " + sumL);
System.out.println("Right Diagonal Sum: " + sumR);
}

Print Lower Triangular elements

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[][] = new int[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
arr[i][j] = in.nextInt();
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(i >= j) // lower triangle
{
System.Out.Println(arr[i][j] + " ");
}
System.Out.Println(" ");
}
}
System.Out.Println();
}

Interchange diagonals in a 2D array

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[][] = new int[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
arr[i][j] = in.nextInt();
}
}
int j = 0;
for(int i = 0; i < n; i++) // swap
{
int temp = arr[i][j];
arr[i][j] = arr[i][n - 1 - j];
arr[i][n - 1 - j] = temp;
j++;
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
System.Out.Println(arr[i][j] + " ");
}
System.Out.Println();
}
}

Print Upper Triangle

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[][] = new int[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
arr[i][j] = in.nextInt();
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(i <= j) // upper triangle
{
System.Out.Println(arr[i][j] + " ");
}
System.Out.Println(" ");
}
}
System.Out.Println();
}

Print matrix diagonally

// 1  2  3  4
// 6 7 8 9
// 11 12 13 14
// 16 17 18 19

// 1 (0,0)
// 6 2 (1,0) -> (0,1)
// 11 7 3 (2,0) -> (1,1) -> (0,2)
// 16 12 8 4 (3,0) -> (2,1) -> (1,2) -> (0,3)
// 17 13 9
// 18 14
// 19

// when there is a movement in an array -> use Two Pointers

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
int arr[][] = new int[n][n];
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
arr[i][j] = in.nextInt();
}
}
// Step 1
for(int i = 0; i < row; i++)
{
int R = i;
int C = 0;
move(R,C,arr,col);
}
// Step 2
for(int j = 0; j < col; j++)
{
int R = row - i;
int C = 0;
move(R,C,arr,col);
}
}
public static void move(int R, int C, int arr[][], int col)
{
while(R >= 0 && C < col)
{
System.Out.Println(arr[R][C] + " ");
R--;
C++;
}
System.Out.Println();
}

Input of 2 matrices & product of matrices (Matrix manipulation)

// matrix a
// 1 2 3 // row 1

// matrix b
// 9 // col 1
// 6
// 3

// output
// 30 // answer for row 1 * col 1


import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[][] = new int[n][n];
int brr[][] = new int[n][n];
int crr[][] = new int[n][n];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
arr[i][j] = in.nextInt();
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
brr[i][j] = in.nextInt();
}
}
for(int i = 0; i < n; i++) // main logic // row arr[]
{
for(int j = 0; j < n; j++) // col brr[]
{
int newE = 0;
for(int k = 0; k < n; k++)
{
newE = newE + arr[i][j] * brr[i][j];
}
crr[i][j] = newE;
}
}
for(int i = 0; i < n; i++) // main logic // row arr[]
{
for(int j = 0; j < n; j++) // col brr[]
{
System.Out.Println(crr[i][j] + " ");
}
System.Out.Println();
}
}

Join 2 strings

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String a = in.next(); // Hello
String b = " World";
System.Out.Println(a.concat(b)); // Hello World
System.Out.Println(a + b); // Hello World
}

Compare 2 strings

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String a = in.next(); // Hello
String b = " World";
System.Out.Println(a.concat(b)); // Hello World
System.Out.Println(a + b); // Hello World
System.Out.Println(a.substring(1,4)); // ell
String c = "aa";
String d = "bb";
System.Out.Println(c.compareTo(d)); // Compare
}

String builder — Convert string -> Integer -> String

public static void main(String[] args)
{
StringBuilder s = new StringBuilder(s);
String s = "123";
int b = Integer.ParseInt(s);
System.Out.Println(b);

int a = 785;
String r = Integer.toString(a);
System.Out.Println(r);
}

Replace and Append — String builder

public static void main(String[] args)
{
StringBuilder s = new StringBuilder("abc");
System.Out.Println(s);
System.Out.Println(s.toString());

s.append("def"); // abcdef
s.setCharAt(0,'A'); // Abcdef
}

Reverse string — Two pointers

public static void main(String[] args)
{
StringBuilder s = new StringBuilder(s);
String s = "abcdef";
int i = 0;
int j = s.length - 1;
while(i < j)
{
char temp = s.charAt(i);
s.setCharAt(i,s.charAt(j));
s.setCharAt(j,tmp);
i++;
j--;
}
System.Out.Prinln(s); // fedcba
}

Print the index where a character occurred

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine(); // abcdefabc
char target = in.next().charAt(0);
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) == target)
{
System.Out.Println(i + " "); // a
}
}
}

Find the position of the word in an array (pattern finding) — Fixing concept — Two pointers

public static void main(String[] args)
{
String s = "I love programming I love coding";
String target = "love";
int l = s.length();
for(int i = 0; i < l; i++)
{
if(match(s,target,i) == true)
{
System.Out.Println(i + " ");
}
}
}
public static boolean match(string s, string t, int startIndex)
{
int i = startIndex;
int j = 0;
while(i < s.length() && j < t.length())
{
if(s.charAt(i) != t.charAt(j))
{
return false;
}
i++;
j++;
}
return true;
}

Maximum occurring character — Two pointers

public static void main(String[] args)
{
char answer = '';
String a = "abcdefabcasdasd";
int l = a.length();
int maxFreq = 0;
for(int i = 0; i < l; i++)
{
char fixedChar = a.charAt(i);
int currFreq = 0;
for(int j = 0; j < l; j++)
{
if(a.charAt(j) == fixedChar)
{
currFreq++;
}
}
if(currFreq > maxFreq)
{
maxFreq = currFreq;
answer = fixedChar;
}
}
System.Out.Println(answer);
System.Out.Println(maxFreq);
}

Reverse words — Reverse order of words — link

import java.util.*;
public static void main(String[] args)
{
string s= "abc def ghi edf";
int l = s.length();
string currWord = "";
int count = 1;
for(int i = 0; i < l; i++)
{
if(s.charAt(i) == '')
{
count++;
}
}
count = count + 1;
Sstring words[] = new String[count];
int index = 0;
for(int i = 0; i < l; i++)
{
if(s.charAt(i) != ' ')
{
currWord = currWord + s.charAt(i);
}
else
{
words[index] = currWord;
currWord = "";
index++;
}
}
words[index] = currWord;
reverse(words);
for(int i = 0; i < words.length; i++)
{
System.Out.println(words[i] + "");
}
}
public static void reverse(String words[])
{
int i = 0;
int j = words.length - 1;
while(i < j)
{
string temp = words[i];
words[i] = words[j];
words[j] = temp;
i++;
j--;
}
}

OOPS — this, extends, super, implements, final

// this
class Student
{
String name;
public Student(string name)
{
this.name = name; // 1st way
}
public Student(string Name)
{
name = Name; // 2nd way
}
Student obj = new Student();
}

// extends
class School
{
String name;
Static int num;
School() { }
}
class Teacher extends School
{
Teacher()
{
num++;
}
}

// super
class A
{
int a;
A() { }
void Print() { }
}
class B extends A
{
int b;
B()
{
super() // super can also be used in constructor
}
void abc()
{
super.print();
super.a; // it calls -> int a;
}
}

// implements
abstract class A
{
abstract void print();
void normalF()
{
System.Out.Println("Non Abstract Function");
}
}
class B implements A
{
void print()
{
System.Out.Println("Implementation");
}
}
public class Main
{
public static void main(String[] args)
{
A obj = new B();
obj.print();
obj.normalF();
}
}

// final
class B
{
final int val = 100l
B() { }
static void print()
{
val = 10;
}
}

Perimeter & Area of Square

class Rectangle
{
Rectangle() { }
Rectangle(int l, int b)
{
length = l;
breath = b;
}
int length;
int breath;
int perimeter()
{
return 2 * (length + breath);
}
int area()
{
return length * breath;
}
}
class Square extends Rectangle
{
Square() { }
Square(int l)
{
super(l,l);
}
}
public class Main
{
public static void main(String arg[])
{
Square obj = new Square(5);
System.Out.Println(obj.perimeter());
System.Out.Println(obj.area());
}
}

Different Drinking Experience

interface Drinks
{
void getName();
void drinkFeeling();
}
class Water implements Drinks
{
public void getName()
{
System.Out.Println("Water");
}
public void drinkFeeling()
{
System.Out.Println("Water is great");
}
}
class Milk implements Drinks
{
public void getName()
{
System.Out.Println("Milk");
}
public void drinkFeeling()
{
System.Out.Println("Milk is good");
}
}
public class Main
{
public static void main(String arg[])
{
Water obj1 = new Water();
Milk obj2 = new Milk();
obj1.getName();
obj1.drinkFeeling();
obj2.getName();
obj2.drinkFeeling();
}
}

Search element in an array.

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Input size of array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array: ");
int size = scanner.nextInt();
int[] arr = new int[size];

// Input elements of array
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Enter element to search: ");
int toSearch = scanner.nextInt();

// Assume that element does not exist in array
int searchIdx = -1;

for (int i = 0; i < size; i++) {
// If element is found in array then save its index
// and terminate from loop.
if (arr[i] == toSearch) {
searchIdx = i;
break;
}
}

// If element is not found in array
if (searchIdx != -1) {
System.out.println(toSearch
+ " is found at position " + (searchIdx + 1));
} else {
System.out.println(toSearch + " is not found in the array");
}

scanner.close();
}
}

Insert an element in an array.

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int(n);
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
for(int i = 0; i < n; i++)
{
System.Out.Println(arr[i]);
}
}

Delete an element from an array at a specified position.

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// Input size and elements in array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of the array: ");
int size = scanner.nextInt();

//Creating the array
int[] arr = new int[size];
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

// Input element position to delete
System.out.println("Enter the element position to delete: ");
int pos = scanner.nextInt();

// Check for invalid delete position
if (pos <= 0 || pos > size) {
System.out.printf("Invalid position!
Please enter position between 1 to %d", size);
}
else {
// Copy next element value to current element
for (int i = pos - 1; i < size - 1; i++) {
arr[i] = arr[i + 1];
}

// Decrement array size by 1
size--;

// Print array after deletion
System.out.print("\nElements of array after delete are: ");
for (int i = 0; i < size; i++) {
System.out.printf("%d\t", arr[i]);
}
}

scanner.close();
}
}

Copy all elements from one array to another array.

import java.util.Scanner;
public class CopyArray {
public static void main(String[] args) {
// Input size of the array
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();

//Declare the array
int[] source = new int[size];
int[] dest = new int[size];

// Input array elements
for (int i = 0; i < size; i++) {
source[i] = scanner.nextInt();
}

// Copy all elements from source array to dest array
for (int i = 0; i < size; i++) {
dest[i] = source[i];
}

// Print all elements of source array
System.out.print("Array1: ");
for (int i = 0; i < size; i++) {
System.out.print(source[i] + "\t");
}

System.out.println();

// Print all elements of dest array
System.out.print("Array2: ");
for (int i = 0; i < size; i++) {
System.out.print(dest[i] + "\t");
}
scanner.close();
}
}

Input elements in an array and print all unique elements of that array.

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// Input size of array and elements in array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array: ");
int size = scanner.nextInt();

// Creating array
int[] arr = new int[size];
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

// Print all unique elements of array
System.out.println("Unique elements in the array are: ");
for (int i = 0; i < size; i++) {
boolean isUnique = true;
// Checking with all elements of the array
for (int j = 0; j < size; j++) {
// Since both the elements at different position have equal value,
// that means the current element is not unique
if (i != j && arr[i] == arr[j]) {
isUnique = false;
break;
}
}

if (isUnique) {
System.out.print(arr[i] + " ");
}
}
System.out.println();
scanner.close();
}
}

Merge two sorted arrays into a third array. — link

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// Input size of first array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of the first array: ");
int size1 = scanner.nextInt();
int[] arr1 = new int[size1];

// Input elements in the first array
System.out.println("Enter elements in the first array: ");
for (int i = 0; i < size1; i++) {
arr1[i] = scanner.nextInt();
}

// Input size of the second array
System.out.println("Enter the size of the second array: ");
int size2 = scanner.nextInt();
int[] arr2 = new int[size2];

// Input elements in the second array
System.out.println("Enter elements in the second array: ");
for (int i = 0; i < size2; i++) {
arr2[i] = scanner.nextInt();
}

// Creating the mergedArray
int mergeSize = size1 + size2;
int[] mergeArray = new int[mergeSize];

// Merge two arrays in ascending order
int index1 = 0;
int index2 = 0;
int mergeIndex = 0;
while (index1 < size1 && index2 < size2) {
// If element of array1 is smaller than element of array2,
// we will consider it
if (arr1[index1] < arr2[index2]) {
mergeArray[mergeIndex] = arr1[index1];
index1++;
}
// Otherwise we will consider element of array2
else {
mergeArray[mergeIndex] = arr2[index2];
index2++;
}
mergeIndex++;
}

// Merge remaining array elements
while (index1 < size1) {
mergeArray[mergeIndex] = arr1[index1];
mergeIndex++;
index1++;
}
while (index2 < size2) {
mergeArray[mergeIndex] = arr2[index2];
mergeIndex++;
index2++;
}

// Print merged array
System.out.println("Array merged in ascending order: ");
for (int i = 0; i < mergeSize; i++) {
System.out.print(mergeArray[i] + "\t");
}
System.out.println();
scanner.close();
}
}

Number is positive or not

import java.util.Scanner;
class Main {
public static void main(String[] args) {
// take number input
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();

// > operator checks if the number is greater than 0 or not.
System.out.println(num > 0);
input.close();

}
}

Input elements in an array from the user, count duplicate elements in the array, and print them

import java.util.Scanner;

class Main {

public static void main(String[] args) {

// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);

// Ask the user for the size of the array
System.out.print("Enter the size of the array: ");
int n = scanner.nextInt();

// Create an array to store user-input elements
int num[] = new int[n];

// Prompt the user to enter array elements
System.out.println("Enter array elements:");

// Loop to get input elements
for (int i = 0; i < n; i++) {
num[i] = scanner.nextInt();
}

int count = 0;
//Searches for duplicate element
for(int i = 0; i < num.length; i++) {
for(int j = i + 1; j < num.length; j++) {
if(num[i] == num[j]) {
System.out.println(num[j]);
count++;
}
}
}
System.out.println("Count of duplicates - " + count);
}
}

Left rotate an array by k positions. — link

import java.util.Scanner;

class Main {

public static void main(String[] args) {

// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);

// Ask the user for the size of the array
System.out.print("Enter the size of the array: ");
int n = scanner.nextInt();

// Create an array to store user-input elements
int num[] = new int[n];

// Prompt the user to enter array elements
System.out.println("Enter array elements:");

// Loop to get input elements and calculate the sum
for (int i = 0; i < n; i++) {
num[i] = scanner.nextInt();
}

System.out.println("Enter k:");
int rotateBy = scanner.nextInt();
// Create a temporary array to store the rotated version
int temp[] = new int[n];

// Keep track of the current index in temp[]
int tempIndex = 0;

// Store the rotated elements (from index rotateBy to the end) in temp[]
for (int i = rotateBy; i < n; i++) {
temp[tempIndex] = num[i];
tempIndex++;
}

// Store the first rotateBy elements of array num[] in temp
for (int i = 0; i < rotateBy; i++) {
temp[tempIndex] = num[i];
tempIndex++;
}

// Copy the elements from temp[] back to num[]
// to get the final rotated array
for (int i = 0; i < n; i++) {
num[i] = temp[i];
}

for (int i = 0; i < n; i++) {
System.out.println(num[i]);
}

}

}

Print all negative elements in an array

import java.util.Scanner;

public class NegativeElementsInArray {
public static void main(String[] args) {

//Input size of the array
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();

//Declare the array
int[] arr = new int[size];

//Input elements in the array
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

for (int i = 0; i < size; i++) {
// If current array element is negative
if (arr[i] < 0) {
System.out.println(arr[i]);
}
}

scanner.close();
}
}

Count the total number of even and odd elements in an array.


import java.util.Scanner;
public class EvenOddCount {
public static void main(String[] args) {
// Input size of the array
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();

//Declare the array
int[] arr = new int[size];

// Input array elements
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

// Assuming that there are 0 even and odd elements
int evenCount = 0;
int oddCount = 0;

for (int i = 0; i < size; i++) {
// If the current element of the array
// is even then increment even count
if (arr[i] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}

System.out.println("Total even elements: " + evenCount);
System.out.println("Total odd elements: " + oddCount);

scanner.close();
}
}

Factorial of a number — link

import java.util.Scanner;

public class FactorialCalculator {

// Method to compute the factorial
int computeFactorial(int n) {
// Initialize factorial to 1
int factorial = 1;

// Compute factorial using a loop
for (int i = 1; i <= n; i++) {
factorial *= i;
}

// Return the computed factorial
return factorial;
}

public static void main(String[] args) {
FactorialCalculator obj = new FactorialCalculator();

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a non-negative number:");
int number = scanner.nextInt();

// Call computeFactorial method and store the result in total
int total = obj.computeFactorial(number);

// Print the result
System.out.println("The factorial of " + number + " is: " + total);
}
}

Largest number among the three given numbers

class Main {

// Method to determine and return the maximum of three numbers
int findMaximum(int num1, int num2, int num3) {

int maximum = num1; // Assume num1 is the maximum initially

if (num2 > maximum) {
maximum = num2; // Update maximum if num2 is greater
}

if (num3 > maximum) {
maximum = num3; // Update maximum if num3 is greater
}

return maximum; // Return the final maximum value
}

public static void main(String[] args) {

// Create an instance of the Main class
Main obj = new Main();

// Find and print the maximum among three numbers
int result = obj.findMaximum(3, 55, 10);
System.out.println("The maximum number is: " + result);//Output: 55

result = obj.findMaximum(0, 12, 30);
System.out.println("The maximum number is: " + result);//Output: 30
}
}

Print all subarrays of a given array

// array {1,2,3}
// subarray
// {1}
// {1,2}
// {1,2,3}
// {2}
// {2,3}
// {3}

import java.util.Scanner;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int(n);
for(int i = 0; i < n; i++)
{
arr[i] = in.nextInt();
}
for(int i = 0; i < n; i++)
{
for(int j = i; j < n; j++)
{
for(int k = i; k <= j; k++)
{
System.Out.Println(arr[k] + " ");
}
System.Out.Println();
}
}
}

Performance of Multiple Instruments (Method Overloading)

class Instrument
{
void makeNoise()
{
System.Out.Println("Instrument makes beautiful noise");
}
}
class Erhu extends Instrument
{
void makeNoise()
{
System.Out.Println("Erhu is good to hear");
}
}
class Piano extends Instrument
{
void makeNoise()
{
System.Out.Println("Piano is pleasing");
}
}
class Violin extends Instrument
{
void makeNoise()
{
System.Out.Println("Violin is pleasing");
}
}
public class Main
{
public static void main(String arg[])
{
Erhu obj = new Ehru();
Piano obj1 = new Piano();
Violin obj2 = new Violin();
obj.makeNoise();
obj1.makeNoise();
obj2.makeNoise();
}
}

Count Triplets — link

class Solution {

public int countGoodTriplets(int[] arr, int a, int b, int c) {
int ans = 0, n = arr.length;
int[] sum = new int[1001];
for (int j = 0; j < n; ++j) {
for (int k = j + 1; k < n; ++k) {
if (Math.abs(arr[j] - arr[k]) <= b) {
int lj = arr[j] - a, rj = arr[j] + a;
int lk = arr[k] - c, rk = arr[k] + c;
int l = Math.max(0, Math.max(lj, lk));
int r = Math.min(1000,Math.min(rj, rk));
if (l <= r) {

if (l == 0) {
ans = ans + sum[r];
} else {
ans = ans + (sum[r] - sum[l - 1]);
}
}
}
}
for (int k = arr[j]; k <= 1000; ++k) {
++sum[k];
}
}
return ans;
}
}

OR

class Solution {
public int countGoodTriplets(int[] arr, int a, int b, int c) {
int goodTriplets = 0;
int length = arr.length;

for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (Math.abs(arr[i] - arr[j]) <= a) {
for (int k = j + 1; k < length; k++) {
if (Math.abs(arr[j] - arr[k]) <= b &&
Math.abs(arr[i] - arr[k]) <= c) {
goodTriplets++;
}
}
}
}
}

return goodTriplets;
}
}
class Solution {

private int rangeCount(int[][] prefix,int left,int right,int low,int high)
{
if (low > high) {
return 0;
}

low = Math.max(low, 0);
high = Math.min(high, 1000);

if (low > high) {
return 0;
}

int countHigh =
prefix[right + 1][high] - prefix[left][high];

int countLow =
low == 0 ? 0 : prefix[right + 1][low - 1] - prefix[left][low - 1];

return countHigh - countLow;
}

public int countGoodTriplets(int[] arr, int a, int b, int c) {

int n = arr.length;

int[][] prefix = new int[n + 1][1001];

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

System.arraycopy(prefix[i], 0, prefix[i + 1], 0, 1001);

prefix[i + 1][arr[i]]++;
}

int answer = 0;

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

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

if (Math.abs(arr[i] - arr[j]) > a) {
continue;
}

int low = Math.max(arr[j] - b,arr[i] - c);

int high = Math.min(arr[j] + b,arr[i] + c);

answer += rangeCount(prefix, j + 1, n - 1, low, high);
}
}

return answer;
}
}

Max sum of Diagonal

import java.util.*;

public class GFG {

public static void maxDiagonalSum(int N, int M, List<List<Integer>> a) {
int[][] d1 = new int[N][M];
int[][] d2 = new int[N][M];

// Fill d1 (↘ direction)
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
d1[i][j] = a.get(i).get(j);
if (i > 0 && j > 0)
d1[i][j] += d1[i - 1][j - 1];
}
}

// Fill d2 (↙ direction)
for (int i = 0; i < N; i++) {
for (int j = M - 1; j >= 0; j--) {
d2[i][j] = a.get(i).get(j);
if (i > 0 && j < M - 1)
d2[i][j] += d2[i - 1][j + 1];
}
}

int ans = Integer.MIN_VALUE;

// Compute max diagonal sum
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
int sum = d1[i][j] + d2[i][j] - a.get(i).get(j);
ans = Math.max(ans, sum);
}
}

System.out.println(ans);
}

public static void main(String[] args) {
int N = 4, M = 4;

List<List<Integer>> arr = new ArrayList<>();
arr.add(Arrays.asList(1, 2, 2, 1));
arr.add(Arrays.asList(2, 4, 2, 4));
arr.add(Arrays.asList(2, 2, 3, 1));
arr.add(Arrays.asList(2, 4, 2, 4));

maxDiagonalSum(N, M, arr);
}
}

Remove element — link

class Solution {
public int removeElement(int[] nums, int val) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[index] = nums[i];
index++;
}
}
return index;
}
}

Print the reverse of the array

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Input size of array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[size];

// Input array elements
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

// Print array in reversed order
System.out.println("Array in reverse order: ");
for (int i = size - 1; i >= 0; i--) {
System.out.print(arr[i] + "\t");
}
System.out.println();
scanner.close();
}
}
Press enter or click to view image in full size

--

--

Kirti Konka
Kirti Konka

Written by Kirti Konka

Learning, building, and evolving—every step shaping the developer I'm becoming.