0% found this document useful (0 votes)
7 views132 pages

? Java Array Programs

The document contains a series of Java programs that demonstrate various operations on arrays, including printing elements, calculating sums and averages, finding maximum and minimum values, counting even and odd numbers, reversing arrays, merging, sorting, and more. Each program is presented with its code and a brief description of its functionality. The programs cover a wide range of array manipulations and algorithms, making it a comprehensive resource for learning Java array operations.

Uploaded by

darshanv.252525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views132 pages

? Java Array Programs

The document contains a series of Java programs that demonstrate various operations on arrays, including printing elements, calculating sums and averages, finding maximum and minimum values, counting even and odd numbers, reversing arrays, merging, sorting, and more. Each program is presented with its code and a brief description of its functionality. The programs cover a wide range of array manipulations and algorithms, making it a comprehensive resource for learning Java array operations.

Uploaded by

darshanv.252525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

Java Array Programs

Program 1: Print all elements of an array

public class Program1 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

for (int num : arr) {

System.out.print(num + " ");

Program 2: Find the sum of array elements

public class Program2 {

public static void main(String[] args) {

int[] arr = {10, 20, 30, 40};

int sum = 0;

for (int num : arr) sum += num;

System.out.println("Sum = " + sum);

Program 3: Find the average of array elements

public class Program3 {

public static void main(String[] args) {

int[] arr = {5, 10, 15, 20};

int sum = 0;

for (int num : arr) sum += num;

double avg = (double) sum / arr.length;

System.out.println("Average = " + avg);


}

Program 4: Find the maximum element

public class Program4 {

public static void main(String[] args) {

int[] arr = {4, 12, 7, 19, 3};

int max = arr[0];

for (int num : arr) if (num > max) max = num;

System.out.println("Max = " + max);

Program 5: Find the minimum element

public class Program5 {

public static void main(String[] args) {

int[] arr = {4, 12, 7, 19, 3};

int min = arr[0];

for (int num : arr) if (num < min) min = num;

System.out.println("Min = " + min);

Program 6: Count even numbers in an array

public class Program6 {

public static void main(String[] args) {

int[] arr = {2, 5, 8, 11, 14};

int count = 0;

for (int num : arr) if (num % 2 == 0) count++;

System.out.println("Even count = " + count);

}
}

Program 7: Count odd numbers in an array

public class Program7 {

public static void main(String[] args) {

int[] arr = {2, 5, 8, 11, 14};

int count = 0;

for (int num : arr) if (num % 2 != 0) count++;

System.out.println("Odd count = " + count);

Program 8: Reverse an array

public class Program8 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

for (int i = arr.length - 1; i >= 0; i--) {

System.out.print(arr[i] + " ");

Program 9: Copy elements from one array to another

public class Program9 {

public static void main(String[] args) {

int[] arr1 = {1, 2, 3, 4, 5};

int[] arr2 = new int[arr1.length];

for (int i = 0; i < arr1.length; i++) arr2[i] = arr1[i];

for (int num : arr2) System.out.print(num + " ");

}
Program 10: Merge two arrays

public class Program10 {

public static void main(String[] args) {

int[] a = {1, 2, 3};

int[] b = {4, 5, 6};

int[] c = new int[a.length + b.length];

int k = 0;

for (int num : a) c[k++] = num;

for (int num : b) c[k++] = num;

for (int num : c) System.out.print(num + " ");

Program 11: Find second largest element

public class Program11 {

public static void main(String[] args) {

int[] arr = {10, 25, 47, 32, 19};

int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;

for (int num : arr) {

if (num > first) {

second = first;

first = num;

} else if (num > second && num != first) {

second = num;

System.out.println("Second Largest = " + second);

}
Program 12: Find second smallest element

public class Program12 {

public static void main(String[] args) {

int[] arr = {10, 25, 47, 32, 19};

int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;

for (int num : arr) {

if (num < first) {

second = first;

first = num;

} else if (num < second && num != first) {

second = num;

System.out.println("Second Smallest = " + second);

Program 13: Check if array contains a given element

public class Program13 {

public static void main(String[] args) {

int[] arr = {10, 20, 30, 40, 50};

int key = 30;

boolean found = false;

for (int num : arr) if (num == key) found = true;

System.out.println(found ? "Element found" : "Not found");

Program 14: Count frequency of each element

public class Program14 {


public static void main(String[] args) {

int[] arr = {1, 2, 2, 3, 4, 4, 4};

boolean[] visited = new boolean[arr.length];

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

if (visited[i]) continue;

int count = 1;

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] == arr[j]) {

count++;

visited[j] = true;

System.out.println(arr[i] + " occurs " + count + " times");

Program 15: Sort an array in ascending order

import java.util.Arrays;

public class Program15 {

public static void main(String[] args) {

int[] arr = {5, 2, 8, 1, 3};

Arrays.sort(arr);

for (int num : arr) System.out.print(num + " ");

Program 16: Sort an array in descending order

import java.util.Arrays;

import java.util.Collections;
public class Program16 {

public static void main(String[] args) {

Integer[] arr = {5, 2, 8, 1, 3};

Arrays.sort(arr, Collections.reverseOrder());

for (int num : arr) System.out.print(num + " ");

Program 17: Left rotate an array by 1 position

public class Program17 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

int first = arr[0];

for (int i = 0; i < arr.length - 1; i++) arr[i] = arr[i + 1];

arr[arr.length - 1] = first;

for (int num : arr) System.out.print(num + " ");

Program 18: Right rotate an array by 1 position

public class Program18 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

int last = arr[arr.length - 1];

for (int i = arr.length - 1; i > 0; i--) arr[i] = arr[i - 1];

arr[0] = last;

for (int num : arr) System.out.print(num + " ");

Program 19: Find the largest 3 elements


public class Program19 {

public static void main(String[] args) {

int[] arr = {10, 4, 3, 50, 23, 90};

Arrays.sort(arr);

System.out.println("Top 3 elements: " + arr[arr.length-1] + ", " + arr[arr.length-2] + ", "


+ arr[arr.length-3]);

Program 20: Find the smallest 3 elements

public class Program20 {

public static void main(String[] args) {

int[] arr = {10, 4, 3, 50, 23, 90};

Arrays.sort(arr);

System.out.println("Smallest 3 elements: " + arr[0] + ", " + arr[1] + ", " + arr[2]);

Program 21: Remove duplicates from an array

import java.util.Arrays;

public class Program21 {

public static void main(String[] args) {

int[] arr = {1, 2, 2, 3, 4, 4, 5};

Arrays.sort(arr);

int j = 0;

int[] temp = new int[arr.length];

for (int i = 0; i < arr.length - 1; i++) {

if (arr[i] != arr[i + 1]) temp[j++] = arr[i];

temp[j++] = arr[arr.length - 1];


for (int i = 0; i < j; i++) System.out.print(temp[i] + " ");

Program 22: Find the kth largest element

import java.util.Arrays;

public class Program22 {

public static void main(String[] args) {

int[] arr = {3, 2, 1, 5, 6, 4};

int k = 2;

Arrays.sort(arr);

System.out.println(k + "th Largest = " + arr[arr.length - k]);

Program 23: Find the kth smallest element

import java.util.Arrays;

public class Program23 {

public static void main(String[] args) {

int[] arr = {7, 10, 4, 3, 20, 15};

int k = 3;

Arrays.sort(arr);

System.out.println(k + "th Smallest = " + arr[k - 1]);

Program 24: Find missing number in array (1–n)

public class Program24 {

public static void main(String[] args) {

int[] arr = {1, 2, 4, 5, 6};

int n = 6;
int sum = n * (n + 1) / 2;

int actual = 0;

for (int num : arr) actual += num;

System.out.println("Missing = " + (sum - actual));

Program 25: Find duplicate elements

public class Program25 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 2, 4, 5, 1};

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] == arr[j]) {

System.out.println("Duplicate: " + arr[i]);

Program 26: Separate even and odd numbers

public class Program26 {

public static void main(String[] args) {

int[] arr = {12, 17, 70, 15, 22, 65, 21, 90};

int[] even = new int[arr.length];

int[] odd = new int[arr.length];

int e = 0, o = 0;

for (int num : arr) {

if (num % 2 == 0) even[e++] = num;


else odd[o++] = num;

System.out.print("Even: ");

for (int i = 0; i < e; i++) System.out.print(even[i] + " ");

System.out.print("\nOdd: ");

for (int i = 0; i < o; i++) System.out.print(odd[i] + " ");

Program 27: Find pairs with given sum

public class Program27 {

public static void main(String[] args) {

int[] arr = {1, 5, 7, -1, 5};

int sum = 6;

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] + arr[j] == sum) {

System.out.println("(" + arr[i] + "," + arr[j] + ")");

Program 28: Move all zeros to end

public class Program28 {

public static void main(String[] args) {

int[] arr = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0};

int index = 0;

for (int num : arr) if (num != 0) arr[index++] = num;


while (index < arr.length) arr[index++] = 0;

for (int num : arr) System.out.print(num + " ");

Program 29: Find leader elements

public class Program29 {

public static void main(String[] args) {

int[] arr = {16, 17, 4, 3, 5, 2};

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

boolean leader = true;

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] < arr[j]) {

leader = false;

break;

if (leader) System.out.print(arr[i] + " ");

Program 30: Find equilibrium index

public class Program30 {

public static void main(String[] args) {

int[] arr = {-7, 1, 5, 2, -4, 3, 0};

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

int left = 0, right = 0;

for (int j = 0; j < i; j++) left += arr[j];

for (int j = i + 1; j < arr.length; j++) right += arr[j];


if (left == right) {

System.out.println("Equilibrium index = " + i);

Program 31: Find majority element

public class Program31 {

public static void main(String[] args) {

int[] arr = {2, 2, 1, 1, 2, 2, 3};

int count = 0, candidate = -1;

for (int num : arr) {

if (count == 0) candidate = num;

count += (num == candidate) ? 1 : -1;

int freq = 0;

for (int num : arr) if (num == candidate) freq++;

if (freq > arr.length / 2) System.out.println("Majority: " + candidate);

else System.out.println("No Majority");

Program 32: Find subarray with given sum

public class Program32 {

public static void main(String[] args) {

int[] arr = {1, 4, 20, 3, 10, 5};

int sum = 33;

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

int curr = 0;
for (int j = i; j < arr.length; j++) {

curr += arr[j];

if (curr == sum) {

System.out.println("From index " + i + " to " + j);

Program 33: Kadane’s Algorithm (max subarray sum)

public class Program33 {

public static void main(String[] args) {

int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3};

int maxSoFar = arr[0], maxEnding = arr[0];

for (int i = 1; i < arr.length; i++) {

maxEnding = Math.max(arr[i], maxEnding + arr[i]);

maxSoFar = Math.max(maxSoFar, maxEnding);

System.out.println("Max Subarray Sum = " + maxSoFar);

Program 34: Check if array is sorted

public class Program34 {

public static void main(String[] args) {

int[] arr = {10, 20, 30, 40};

boolean sorted = true;

for (int i = 1; i < arr.length; i++) {

if (arr[i] < arr[i - 1]) sorted = false;


}

System.out.println(sorted ? "Sorted" : "Not Sorted");

Program 35: Find longest increasing subarray

public class Program35 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 2, 5, 6, 7, 8};

int maxLen = 1, curr = 1;

for (int i = 1; i < arr.length; i++) {

if (arr[i] > arr[i - 1]) curr++;

else {

maxLen = Math.max(maxLen, curr);

curr = 1;

maxLen = Math.max(maxLen, curr);

System.out.println("Longest Increasing Subarray Length = " + maxLen);

Program 36: Find longest equal subarray (0s and 1s)

import java.util.HashMap;

public class Program36 {

public static void main(String[] args) {

int[] arr = {0, 0, 1, 0, 1, 1, 0};

HashMap<Integer,Integer> map = new HashMap<>();

int sum = 0, maxLen = 0;

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


sum += (arr[i] == 0 ? -1 : 1);

if (sum == 0) maxLen = i + 1;

if (map.containsKey(sum)) {

maxLen = Math.max(maxLen, i - map.get(sum));

} else {

map.put(sum, i);

System.out.println("Longest Subarray Length = " + maxLen);

Program 37: Find maximum product subarray

public class Program37 {

public static void main(String[] args) {

int[] arr = {2, 3, -2, 4};

int max = arr[0], min = arr[0], result = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] < 0) {

int temp = max;

max = min;

min = temp;

max = Math.max(arr[i], max * arr[i]);

min = Math.min(arr[i], min * arr[i]);

result = Math.max(result, max);

System.out.println("Max Product = " + result);

}
}

Program 38: Find peak element

public class Program38 {

public static void main(String[] args) {

int[] arr = {1, 3, 20, 4, 1, 0};

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

if ((i == 0 || arr[i] >= arr[i - 1]) &&

(i == arr.length - 1 || arr[i] >= arr[i + 1])) {

System.out.println("Peak Element = " + arr[i]);

Program 39: Find triplet with given sum

import java.util.Arrays;

public class Program39 {

public static void main(String[] args) {

int[] arr = {12, 3, 4, 1, 6, 9};

int sum = 24;

Arrays.sort(arr);

for (int i = 0; i < arr.length - 2; i++) {

int l = i + 1, r = arr.length - 1;

while (l < r) {

if (arr[i] + arr[l] + arr[r] == sum) {

System.out.println(arr[i] + ", " + arr[l] + ", " + arr[r]);

l++; r--;

} else if (arr[i] + arr[l] + arr[r] < sum) l++;

else r--;
}

Program 40: Find common elements in three arrays

public class Program40 {

public static void main(String[] args) {

int[] a = {1, 5, 10, 20, 40, 80};

int[] b = {6, 7, 20, 80, 100};

int[] c = {3, 4, 15, 20, 30, 70, 80, 120};

int i = 0, j = 0, k = 0;

while (i < a.length && j < b.length && k < c.length) {

if (a[i] == b[j] && b[j] == c[k]) {

System.out.print(a[i] + " ");

i++; j++; k++;

} else if (a[i] < b[j]) i++;

else if (b[j] < c[k]) j++;

else k++;

Program 41: Merge two sorted arrays

public class Program41 {

public static void main(String[] args) {

int[] a = {1, 3, 5, 7};

int[] b = {2, 4, 6, 8};

int[] c = new int[a.length + b.length];

int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {

if (a[i] < b[j]) c[k++] = a[i++];

else c[k++] = b[j++];

while (i < a.length) c[k++] = a[i++];

while (j < b.length) c[k++] = b[j++];

for (int num : c) System.out.print(num + " ");

Program 42: Find intersection of two arrays

public class Program42 {

public static void main(String[] args) {

int[] a = {1, 2, 4, 5, 6};

int[] b = {2, 3, 5, 7};

for (int i : a) {

for (int j : b) {

if (i == j) System.out.print(i + " ");

Program 43: Find union of two arrays

import java.util.HashSet;

public class Program43 {

public static void main(String[] args) {

int[] a = {1, 2, 4, 5, 6};

int[] b = {2, 3, 5, 7};

HashSet<Integer> set = new HashSet<>();


for (int i : a) set.add(i);

for (int j : b) set.add(j);

System.out.println(set);

Program 44: Find array rotation count

public class Program44 {

public static void main(String[] args) {

int[] arr = {15, 18, 2, 3, 6, 12};

int minIndex = 0;

for (int i = 1; i < arr.length; i++) {

if (arr[i] < arr[minIndex]) minIndex = i;

System.out.println("Rotation Count = " + minIndex);

Program 45: Cyclically rotate array by one

public class Program45 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

int temp = arr[arr.length - 1];

for (int i = arr.length - 1; i > 0; i--) {

arr[i] = arr[i - 1];

arr[0] = temp;

for (int num : arr) System.out.print(num + " ");

}
Program 46: Left rotate array by d positions

public class Program46 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

int d = 2;

int n = arr.length;

int[] temp = new int[d];

for (int i = 0; i < d; i++) temp[i] = arr[i];

for (int i = d; i < n; i++) arr[i - d] = arr[i];

for (int i = 0; i < d; i++) arr[n - d + i] = temp[i];

for (int num : arr) System.out.print(num + " ");

Program 47: Right rotate array by d positions

public class Program47 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

int d = 3;

int n = arr.length;

int[] temp = new int[d];

for (int i = 0; i < d; i++) temp[i] = arr[n - d + i];

for (int i = n - 1; i >= d; i--) arr[i] = arr[i - d];

for (int i = 0; i < d; i++) arr[i] = temp[i];

for (int num : arr) System.out.print(num + " ");

Program 48: Find maximum circular subarray sum

public class Program48 {


static int kadane(int[] arr) {

int max = arr[0], cur = arr[0];

for (int i = 1; i < arr.length; i++) {

cur = Math.max(arr[i], cur + arr[i]);

max = Math.max(max, cur);

return max;

public static void main(String[] args) {

int[] arr = {8, -8, 9, -9, 10, -11, 12};

int maxNormal = kadane(arr);

int sum = 0;

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

sum += arr[i];

arr[i] = -arr[i];

int maxCircular = sum + kadane(arr);

System.out.println("Max Circular Sum = " + Math.max(maxNormal, maxCircular));

Program 49: Search element in rotated sorted array

public class Program49 {

static int search(int[] arr, int l, int h, int key) {

if (l > h) return -1;

int mid = (l + h) / 2;

if (arr[mid] == key) return mid;

if (arr[l] <= arr[mid]) {

if (key >= arr[l] && key <= arr[mid])


return search(arr, l, mid - 1, key);

return search(arr, mid + 1, h, key);

if (key >= arr[mid] && key <= arr[h])

return search(arr, mid + 1, h, key);

return search(arr, l, mid - 1, key);

public static void main(String[] args) {

int[] arr = {4, 5, 6, 7, 0, 1, 2};

int key = 6;

int index = search(arr, 0, arr.length - 1, key);

System.out.println("Index of " + key + " = " + index);

Program 50: Find first repeating element

import java.util.HashSet;

public class Program50 {

public static void main(String[] args) {

int[] arr = {10, 5, 3, 4, 3, 5, 6};

HashSet<Integer> set = new HashSet<>();

int repeat = -1;

for (int i = arr.length - 1; i >= 0; i--) {

if (set.contains(arr[i])) repeat = arr[i];

else set.add(arr[i]);

System.out.println("First Repeating Element = " + repeat);

}
Program 51: Find first non-repeating element

public class Program51 {

public static void main(String[] args) {

int[] arr = {9, 4, 9, 6, 7, 4};

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

boolean unique = true;

for (int j = 0; j < arr.length; j++) {

if (i != j && arr[i] == arr[j]) {

unique = false;

break;

if (unique) {

System.out.println("First non-repeating: " + arr[i]);

break;

Program 52: Find common elements in two arrays

public class Program52 {

public static void main(String[] args) {

int[] a = {1, 2, 3, 4, 5};

int[] b = {3, 4, 5, 6, 7};

for (int i : a) {

for (int j : b) {

if (i == j) System.out.print(i + " ");

}
}

Program 53: Find missing numbers from 1 to n

public class Program53 {

public static void main(String[] args) {

int[] arr = {1, 3, 5, 6};

int n = 6;

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

for (int num : arr) present[num] = true;

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

if (!present[i]) System.out.print(i + " ");

Program 54: Count pairs with given sum

public class Program54 {

public static void main(String[] args) {

int[] arr = {1, 5, 7, -1};

int sum = 6, count = 0;

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] + arr[j] == sum) count++;

System.out.println("Count = " + count);

}
Program 55: Count inversions in array

public class Program55 {

public static void main(String[] args) {

int[] arr = {1, 20, 6, 4, 5};

int count = 0;

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] > arr[j]) count++;

System.out.println("Inversions = " + count);

Program 56: Find maximum difference arr[j] - arr[i]

public class Program56 {

public static void main(String[] args) {

int[] arr = {2, 3, 10, 6, 4, 8, 1};

int min = arr[0], maxDiff = arr[1] - arr[0];

for (int i = 1; i < arr.length; i++) {

maxDiff = Math.max(maxDiff, arr[i] - min);

min = Math.min(min, arr[i]);

System.out.println("Max Difference = " + maxDiff);

Program 57: Find equilibrium point

public class Program57 {

public static void main(String[] args) {


int[] arr = {1, 3, 5, 2, 2};

int total = 0;

for (int num : arr) total += num;

int left = 0;

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

total -= arr[i];

if (left == total) {

System.out.println("Equilibrium at index " + i);

break;

left += arr[i];

Program 58: Find subarray with max product

public class Program58 {

public static void main(String[] args) {

int[] arr = {6, -3, -10, 0, 2};

int max = arr[0], min = arr[0], result = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] < 0) {

int temp = max;

max = min;

min = temp;

max = Math.max(arr[i], max * arr[i]);

min = Math.min(arr[i], min * arr[i]);

result = Math.max(result, max);


}

System.out.println("Max Product = " + result);

Program 59: Find subarray with max sum of size k

public class Program59 {

public static void main(String[] args) {

int[] arr = {100, 200, 300, 400};

int k = 2, max = 0;

for (int i = 0; i <= arr.length - k; i++) {

int sum = 0;

for (int j = 0; j < k; j++) sum += arr[i + j];

max = Math.max(max, sum);

System.out.println("Max sum of " + k + " elements = " + max);

Program 60: Find equilibrium sum index

public class Program60 {

public static void main(String[] args) {

int[] arr = {2, 3, -1, 8, 4};

int total = 0;

for (int num : arr) total += num;

int left = 0;

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

total -= arr[i];

if (left == total) {

System.out.println("Equilibrium index = " + i);


break;

left += arr[i];

Program 61: Find maximum repeating element

public class Program61 {

public static void main(String[] args) {

int[] arr = {2, 3, 3, 5, 3, 4, 1, 7};

int maxCount = 0, element = -1;

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

int count = 0;

for (int j = 0; j < arr.length; j++) {

if (arr[i] == arr[j]) count++;

if (count > maxCount) {

maxCount = count;

element = arr[i];

System.out.println("Max Repeating Element = " + element);

Program 62: Find leaders in an array

public class Program62 {

public static void main(String[] args) {

int[] arr = {16, 17, 4, 3, 5, 2};


int max = arr[arr.length - 1];

System.out.print(max + " ");

for (int i = arr.length - 2; i >= 0; i--) {

if (arr[i] > max) {

max = arr[i];

System.out.print(max + " ");

Program 63: Find maximum index difference

public class Program63 {

public static void main(String[] args) {

int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};

int maxDiff = -1;

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

for (int j = arr.length - 1; j > i; j--) {

if (arr[j] > arr[i]) {

maxDiff = Math.max(maxDiff, j - i);

System.out.println("Max Index Diff = " + maxDiff);

Program 64: Count subarrays with given sum

public class Program64 {

public static void main(String[] args) {


int[] arr = {10, 2, -2, -20, 10};

int sum = -10, count = 0;

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

int curr = 0;

for (int j = i; j < arr.length; j++) {

curr += arr[j];

if (curr == sum) count++;

System.out.println("Subarray Count = " + count);

Program 65: Find majority element (>n/2 times)

public class Program65 {

public static void main(String[] args) {

int[] arr = {3, 3, 4, 2, 4, 4, 2, 4, 4};

int candidate = arr[0], count = 1;

for (int i = 1; i < arr.length; i++) {

if (arr[i] == candidate) count++;

else count--;

if (count == 0) {

candidate = arr[i];

count = 1;

count = 0;

for (int num : arr) if (num == candidate) count++;

if (count > arr.length / 2) System.out.println("Majority: " + candidate);


else System.out.println("No Majority");

Program 66: Rearrange array alternately

public class Program66 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6};

int n = arr.length;

int[] temp = new int[n];

int small = 0, large = n - 1, i = 0;

boolean flag = true;

while (small <= large) {

if (flag) temp[i++] = arr[large--];

else temp[i++] = arr[small++];

flag = !flag;

for (i = 0; i < n; i++) arr[i] = temp[i];

for (int num : arr) System.out.print(num + " ");

Program 67: Rearrange positive and negative numbers

public class Program67 {

public static void main(String[] args) {

int[] arr = {1, -2, 3, -4, 5, -6};

int n = arr.length;

int[] temp = new int[n];

int pos = 0, neg = 1;

for (int num : arr) {


if (num >= 0 && pos < n) {

temp[pos] = num;

pos += 2;

} else if (num < 0 && neg < n) {

temp[neg] = num;

neg += 2;

for (int num : temp) System.out.print(num + " ");

Program 68: Minimum swaps to sort

import java.util.Arrays;

import java.util.HashMap;

public class Program68 {

public static void main(String[] args) {

int[] arr = {4, 3, 2, 1};

int n = arr.length;

int[] temp = arr.clone();

Arrays.sort(temp);

HashMap<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < n; i++) map.put(temp[i], i);

boolean[] visited = new boolean[n];

int swaps = 0;

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

if (visited[i] || map.get(arr[i]) == i) continue;

int cycle = 0, j = i;

while (!visited[j]) {
visited[j] = true;

j = map.get(arr[j]);

cycle++;

if (cycle > 0) swaps += (cycle - 1);

System.out.println("Min Swaps = " + swaps);

Program 69: Maximum sum of non-adjacent elements

public class Program69 {

public static void main(String[] args) {

int[] arr = {5, 5, 10, 100, 10, 5};

int incl = arr[0], excl = 0;

for (int i = 1; i < arr.length; i++) {

int newExcl = Math.max(incl, excl);

incl = excl + arr[i];

excl = newExcl;

System.out.println("Max Sum = " + Math.max(incl, excl));

Program 70: Trapping Rain Water

public class Program70 {

public static void main(String[] args) {

int[] height = {3, 0, 2, 0, 4};

int n = height.length;

int[] left = new int[n], right = new int[n];


left[0] = height[0];

for (int i = 1; i < n; i++) left[i] = Math.max(left[i - 1], height[i]);

right[n - 1] = height[n - 1];

for (int i = n - 2; i >= 0; i--) right[i] = Math.max(right[i + 1], height[i]);

int water = 0;

for (int i = 0; i < n; i++) water += Math.min(left[i], right[i]) - height[i];

System.out.println("Trapped Water = " + water);

Program 71: Find longest increasing subsequence

public class Program71 {

public static void main(String[] args) {

int[] arr = {10, 22, 9, 33, 21, 50, 41, 60};

int n = arr.length;

int[] lis = new int[n];

for (int i = 0; i < n; i++) lis[i] = 1;

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

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

if (arr[i] > arr[j] && lis[i] < lis[j] + 1) {

lis[i] = lis[j] + 1;

int max = 0;

for (int i : lis) if (i > max) max = i;

System.out.println("LIS Length = " + max);

}
Program 72: Find longest consecutive subsequence

import java.util.HashSet;

public class Program72 {

public static void main(String[] args) {

int[] arr = {1, 9, 3, 10, 4, 20, 2};

HashSet<Integer> set = new HashSet<>();

for (int num : arr) set.add(num);

int longest = 0;

for (int num : arr) {

if (!set.contains(num - 1)) {

int cur = num, length = 1;

while (set.contains(cur + 1)) { cur++; length++; }

longest = Math.max(longest, length);

System.out.println("Longest Consecutive Sequence = " + longest);

Program 73: Find subarray with 0 sum

import java.util.HashSet;

public class Program73 {

public static void main(String[] args) {

int[] arr = {4, 2, -3, 1, 6};

HashSet<Integer> set = new HashSet<>();

int sum = 0;

boolean found = false;

for (int num : arr) {

sum += num;
if (sum == 0 || set.contains(sum)) {

found = true; break;

set.add(sum);

System.out.println(found ? "Subarray with 0 sum exists" : "Does not exist");

Program 74: Find largest subarray with equal 0s and 1s

import java.util.HashMap;

public class Program74 {

public static void main(String[] args) {

int[] arr = {1, 0, 0, 1, 0, 1, 1};

HashMap<Integer, Integer> map = new HashMap<>();

int sum = 0, maxLen = 0;

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

sum += (arr[i] == 0 ? -1 : 1);

if (sum == 0) maxLen = i + 1;

if (map.containsKey(sum)) {

maxLen = Math.max(maxLen, i - map.get(sum));

} else {

map.put(sum, i);

System.out.println("Max Length = " + maxLen);

Program 75: Find subarray with given XOR


import java.util.HashMap;

public class Program75 {

public static void main(String[] args) {

int[] arr = {4, 2, 2, 6, 4};

int k = 6;

HashMap<Integer, Integer> map = new HashMap<>();

int xor = 0, count = 0;

for (int num : arr) {

xor ^= num;

if (xor == k) count++;

if (map.containsKey(xor ^ k)) count += map.get(xor ^ k);

map.put(xor, map.getOrDefault(xor, 0) + 1);

System.out.println("Count = " + count);

Program 76: Find maximum sum of k consecutive elements

public class Program76 {

public static void main(String[] args) {

int[] arr = {100, 200, 300, 400};

int k = 2, maxSum = 0;

for (int i = 0; i < k; i++) maxSum += arr[i];

int curSum = maxSum;

for (int i = k; i < arr.length; i++) {

curSum += arr[i] - arr[i - k];

maxSum = Math.max(maxSum, curSum);

System.out.println("Max Sum = " + maxSum);


}

Program 77: Find maximum sum increasing subsequence

public class Program77 {

public static void main(String[] args) {

int[] arr = {1, 101, 2, 3, 100, 4, 5};

int n = arr.length;

int[] msis = new int[n];

for (int i = 0; i < n; i++) msis[i] = arr[i];

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

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

if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) {

msis[i] = msis[j] + arr[i];

int max = msis[0];

for (int i : msis) max = Math.max(max, i);

System.out.println("Max Sum IS = " + max);

Program 78: Find maximum length bitonic subarray

public class Program78 {

public static void main(String[] args) {

int[] arr = {12, 4, 78, 90, 45, 23};

int n = arr.length;

int[] inc = new int[n], dec = new int[n];

inc[0] = 1; dec[n - 1] = 1;
for (int i = 1; i < n; i++) inc[i] = (arr[i] >= arr[i - 1]) ? inc[i - 1] + 1 : 1;

for (int i = n - 2; i >= 0; i--) dec[i] = (arr[i] >= arr[i + 1]) ? dec[i + 1] + 1 : 1;

int max = inc[0] + dec[0] - 1;

for (int i = 1; i < n; i++) max = Math.max(max, inc[i] + dec[i] - 1);

System.out.println("Max Length Bitonic = " + max);

Program 79: Find maximum profit from stock prices

public class Program79 {

public static void main(String[] args) {

int[] prices = {7, 1, 5, 3, 6, 4};

int min = prices[0], profit = 0;

for (int i = 1; i < prices.length; i++) {

min = Math.min(min, prices[i]);

profit = Math.max(profit, prices[i] - min);

System.out.println("Max Profit = " + profit);

Program 80: Find maximum profit with multiple transactions

public class Program80 {

public static void main(String[] args) {

int[] prices = {7, 1, 5, 3, 6, 4};

int profit = 0;

for (int i = 1; i < prices.length; i++) {

if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];

System.out.println("Total Profit = " + profit);


}

Program 81: Find maximum difference between two elements

public class Program81 {

public static void main(String[] args) {

int[] arr = {2, 3, 10, 6, 4, 8, 1};

int min = arr[0], maxDiff = arr[1] - arr[0];

for (int i = 1; i < arr.length; i++) {

maxDiff = Math.max(maxDiff, arr[i] - min);

min = Math.min(min, arr[i]);

System.out.println("Max Difference = " + maxDiff);

Program 82: Find maximum j - i such that arr[j] > arr[i]

public class Program82 {

public static void main(String[] args) {

int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};

int maxDiff = -1;

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

for (int j = arr.length - 1; j > i; j--) {

if (arr[j] > arr[i]) maxDiff = Math.max(maxDiff, j - i);

System.out.println("Max Index Difference = " + maxDiff);

Program 83: Find minimum number of jumps


public class Program83 {

public static void main(String[] args) {

int[] arr = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};

int jumps = 0, curEnd = 0, curFarthest = 0;

for (int i = 0; i < arr.length - 1; i++) {

curFarthest = Math.max(curFarthest, i + arr[i]);

if (i == curEnd) {

jumps++;

curEnd = curFarthest;

System.out.println("Min Jumps = " + jumps);

Program 84: Find minimum number of platforms required

import java.util.Arrays;

public class Program84 {

public static void main(String[] args) {

int[] arr = {900, 940, 950, 1100, 1500, 1800};

int[] dep = {910, 1200, 1120, 1130, 1900, 2000};

Arrays.sort(arr); Arrays.sort(dep);

int plat = 1, result = 1, i = 1, j = 0;

while (i < arr.length && j < dep.length) {

if (arr[i] <= dep[j]) {

plat++; i++;

result = Math.max(result, plat);

} else {

plat--; j++;
}

System.out.println("Min Platforms = " + result);

Program 85: Find minimum swaps to sort array

import java.util.Arrays;

import java.util.HashMap;

public class Program85 {

public static void main(String[] args) {

int[] arr = {4, 3, 2, 1};

int n = arr.length;

int[] sorted = arr.clone();

Arrays.sort(sorted);

HashMap<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < n; i++) map.put(sorted[i], i);

boolean[] visited = new boolean[n];

int swaps = 0;

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

if (visited[i] || map.get(arr[i]) == i) continue;

int cycle = 0, j = i;

while (!visited[j]) {

visited[j] = true;

j = map.get(arr[j]);

cycle++;

if (cycle > 0) swaps += (cycle - 1);

}
System.out.println("Min Swaps = " + swaps);

Program 86: Find minimum difference between elements

import java.util.Arrays;

public class Program86 {

public static void main(String[] args) {

int[] arr = {1, 5, 3, 19, 18, 25};

Arrays.sort(arr);

int minDiff = Integer.MAX_VALUE;

for (int i = 1; i < arr.length; i++) {

minDiff = Math.min(minDiff, arr[i] - arr[i - 1]);

System.out.println("Min Difference = " + minDiff);

Program 87: Find kth smallest element using sorting

import java.util.Arrays;

public class Program87 {

public static void main(String[] args) {

int[] arr = {7, 10, 4, 3, 20, 15};

int k = 3;

Arrays.sort(arr);

System.out.println(k + "th Smallest = " + arr[k - 1]);

Program 88: Find kth largest element using sorting

import java.util.Arrays;
public class Program88 {

public static void main(String[] args) {

int[] arr = {7, 10, 4, 3, 20, 15};

int k = 2;

Arrays.sort(arr);

System.out.println(k + "th Largest = " + arr[arr.length - k]);

Program 89: Find kth smallest element using quickselect

public class Program89 {

static int partition(int[] arr, int l, int r) {

int pivot = arr[r], i = l;

for (int j = l; j < r; j++) {

if (arr[j] <= pivot) {

int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;

i++;

int tmp = arr[i]; arr[i] = arr[r]; arr[r] = tmp;

return i;

static int quickSelect(int[] arr, int l, int r, int k) {

if (l <= r) {

int pi = partition(arr, l, r);

if (pi == k) return arr[pi];

if (pi > k) return quickSelect(arr, l, pi - 1, k);

return quickSelect(arr, pi + 1, r, k);

}
return -1;

public static void main(String[] args) {

int[] arr = {7, 10, 4, 3, 20, 15};

int k = 3;

System.out.println(k + "th Smallest = " + quickSelect(arr, 0, arr.length - 1, k - 1));

Program 90: Find kth largest element using quickselect

public class Program90 {

static int partition(int[] arr, int l, int r) {

int pivot = arr[r], i = l;

for (int j = l; j < r; j++) {

if (arr[j] <= pivot) {

int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;

i++;

int tmp = arr[i]; arr[i] = arr[r]; arr[r] = tmp;

return i;

static int quickSelect(int[] arr, int l, int r, int k) {

if (l <= r) {

int pi = partition(arr, l, r);

if (pi == k) return arr[pi];

if (pi > k) return quickSelect(arr, l, pi - 1, k);

return quickSelect(arr, pi + 1, r, k);

}
return -1;

public static void main(String[] args) {

int[] arr = {7, 10, 4, 3, 20, 15};

int k = 2;

System.out.println(k + "th Largest = " + quickSelect(arr, 0, arr.length - 1, arr.length - k));

Program 91: Count number of leaders in array

public class Program91 {

public static void main(String[] args) {

int[] arr = {16, 17, 4, 3, 5, 2};

int n = arr.length;

int count = 0;

int maxFromRight = arr[n - 1];

count++;

for (int i = n - 2; i >= 0; i--) {

if (arr[i] > maxFromRight) {

count++;

maxFromRight = arr[i];

System.out.println("Number of Leaders = " + count);

Program 92: Find frequency of each element

public class Program92 {

public static void main(String[] args) {


int[] arr = {10, 20, 10, 30, 20, 20, 40};

boolean[] visited = new boolean[arr.length];

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

if (visited[i]) continue;

int count = 1;

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] == arr[j]) {

visited[j] = true;

count++;

System.out.println(arr[i] + " occurs " + count + " times");

Program 93: Find subarray with given sum (non-negative numbers)

public class Program93 {

public static void main(String[] args) {

int[] arr = {1, 4, 20, 3, 10, 5};

int sum = 33;

int currSum = arr[0], start = 0;

for (int i = 1; i <= arr.length; i++) {

while (currSum > sum && start < i - 1) {

currSum -= arr[start];

start++;

if (currSum == sum) {

System.out.println("Found subarray from index " + start + " to " + (i - 1));


return;

if (i < arr.length) currSum += arr[i];

System.out.println("No subarray found");

Program 94: Find largest three elements

public class Program94 {

public static void main(String[] args) {

int[] arr = {10, 4, 3, 50, 23, 90};

int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE, third = Integer.MIN_VALUE;

for (int num : arr) {

if (num > first) {

third = second;

second = first;

first = num;

} else if (num > second) {

third = second;

second = num;

} else if (num > third) {

third = num;

System.out.println("Three largest: " + first + " " + second + " " + third);

Program 95: Find smallest three elements


public class Program95 {

public static void main(String[] args) {

int[] arr = {10, 4, 3, 50, 23, 90};

int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE, third =


Integer.MAX_VALUE;

for (int num : arr) {

if (num < first) {

third = second;

second = first;

first = num;

} else if (num < second) {

third = second;

second = num;

} else if (num < third) {

third = num;

System.out.println("Three smallest: " + first + " " + second + " " + third);

Program 96: Rearrange positive and negative numbers alternatively

import java.util.*;

public class Program96 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, -4, -1, 4};

ArrayList<Integer> pos = new ArrayList<>();

ArrayList<Integer> neg = new ArrayList<>();

for (int num : arr) {


if (num >= 0) pos.add(num);

else neg.add(num);

int i = 0, j = 0, k = 0;

while (i < pos.size() && j < neg.size()) {

arr[k++] = pos.get(i++);

arr[k++] = neg.get(j++);

while (i < pos.size()) arr[k++] = pos.get(i++);

while (j < neg.size()) arr[k++] = neg.get(j++);

System.out.println(Arrays.toString(arr));

Program 97: Check if array is sorted

public class Program97 {

public static void main(String[] args) {

int[] arr = {10, 20, 30, 40, 50};

boolean sorted = true;

for (int i = 1; i < arr.length; i++) {

if (arr[i] < arr[i - 1]) {

sorted = false;

break;

System.out.println("Is Sorted? " + sorted);

Program 98: Count pairs with given sum


public class Program98 {

public static void main(String[] args) {

int[] arr = {1, 5, 7, -1, 5};

int sum = 6, count = 0;

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] + arr[j] == sum) count++;

System.out.println("Count = " + count);

Program 99: Count triplets with given sum

public class Program99 {

public static void main(String[] args) {

int[] arr = {1, 5, 3, 2};

int sum = 8, count = 0;

for (int i = 0; i < arr.length - 2; i++) {

for (int j = i + 1; j < arr.length - 1; j++) {

for (int k = j + 1; k < arr.length; k++) {

if (arr[i] + arr[j] + arr[k] == sum) count++;

System.out.println("Triplets count = " + count);

Program 100: Rearrange array in zig-zag fashion


import java.util.Arrays;

public class Program100 {

public static void main(String[] args) {

int[] arr = {4, 3, 7, 8, 6, 2, 1};

boolean flag = true; // true for <

for (int i = 0; i < arr.length - 1; i++) {

if (flag) {

if (arr[i] > arr[i + 1]) {

int temp = arr[i];

arr[i] = arr[i + 1];

arr[i + 1] = temp;

} else {

if (arr[i] < arr[i + 1]) {

int temp = arr[i];

arr[i] = arr[i + 1];

arr[i + 1] = temp;

flag = !flag;

System.out.println("Zig-Zag: " + Arrays.toString(arr));

Program 101: Find maximum difference between two elements

public class Program101 {

public static void main(String[] args) {

int[] arr = {2, 3, 10, 6, 4, 8, 1};


int min = arr[0], maxDiff = arr[1] - arr[0];

for (int i = 1; i < arr.length; i++) {

maxDiff = Math.max(maxDiff, arr[i] - min);

min = Math.min(min, arr[i]);

System.out.println("Maximum Difference = " + maxDiff);

Program 102: Find minimum difference between two elements

import java.util.Arrays;

public class Program102 {

public static void main(String[] args) {

int[] arr = {1, 5, 3, 19, 18, 25};

Arrays.sort(arr);

int minDiff = Integer.MAX_VALUE;

for (int i = 1; i < arr.length; i++) {

minDiff = Math.min(minDiff, arr[i] - arr[i - 1]);

System.out.println("Minimum Difference = " + minDiff);

Program 103: Find equilibrium index of an array

public class Program103 {

public static void main(String[] args) {

int[] arr = {-7, 1, 5, 2, -4, 3, 0};

int total = 0, leftSum = 0;

for (int num : arr) total += num;

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


total -= arr[i];

if (leftSum == total) {

System.out.println("Equilibrium index = " + i);

leftSum += arr[i];

Program 104: Find majority element in array

public class Program104 {

public static void main(String[] args) {

int[] arr = {2, 2, 1, 1, 2, 2, 3};

int count = 0, candidate = -1;

for (int num : arr) {

if (count == 0) {

candidate = num;

count = 1;

} else if (candidate == num) {

count++;

} else {

count--;

int freq = 0;

for (int num : arr) if (num == candidate) freq++;

if (freq > arr.length / 2) System.out.println("Majority Element = " + candidate);

else System.out.println("No Majority Element");

}
}

Program 105: Replace every element with next greatest element

public class Program105 {

public static void main(String[] args) {

int[] arr = {16, 17, 4, 3, 5, 2};

int n = arr.length;

int max = arr[n - 1];

arr[n - 1] = -1;

for (int i = n - 2; i >= 0; i--) {

int temp = arr[i];

arr[i] = max;

if (temp > max) max = temp;

for (int num : arr) System.out.print(num + " ");

Program 106: Find smallest positive missing number

import java.util.HashSet;

public class Program106 {

public static void main(String[] args) {

int[] arr = {0, -10, 1, 3, -20};

HashSet<Integer> set = new HashSet<>();

for (int num : arr) set.add(num);

int i = 1;

while (true) {

if (!set.contains(i)) {

System.out.println("Smallest Missing = " + i);

break;
}

i++;

Program 107: Count inversions in an array

public class Program107 {

public static void main(String[] args) {

int[] arr = {1, 20, 6, 4, 5};

int count = 0;

for (int i = 0; i < arr.length - 1; i++) {

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] > arr[j]) count++;

System.out.println("Inversions = " + count);

Program 108: Find maximum subarray product

public class Program108 {

public static void main(String[] args) {

int[] arr = {2, 3, -2, 4};

int max = arr[0], min = arr[0], result = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] < 0) {

int temp = max;

max = min;

min = temp;
}

max = Math.max(arr[i], max * arr[i]);

min = Math.min(arr[i], min * arr[i]);

result = Math.max(result, max);

System.out.println("Max Subarray Product = " + result);

Program 109: Find maximum subarray sum (Kadane’s Algorithm)

public class Program109 {

public static void main(String[] args) {

int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3};

int maxSoFar = arr[0], currMax = arr[0];

for (int i = 1; i < arr.length; i++) {

currMax = Math.max(arr[i], currMax + arr[i]);

maxSoFar = Math.max(maxSoFar, currMax);

System.out.println("Max Subarray Sum = " + maxSoFar);

Program 110: Find maximum sum of circular subarray

public class Program110 {

static int kadane(int[] arr) {

int max = arr[0], cur = arr[0];

for (int i = 1; i < arr.length; i++) {

cur = Math.max(arr[i], cur + arr[i]);

max = Math.max(max, cur);

}
return max;

public static void main(String[] args) {

int[] arr = {8, -8, 9, -9, 10, -11, 12};

int maxNormal = kadane(arr);

int sum = 0;

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

sum += arr[i];

arr[i] = -arr[i];

int maxCircular = sum + kadane(arr);

System.out.println("Max Circular Sum = " + Math.max(maxNormal, maxCircular));

Program 111: Find longest consecutive subsequence

import java.util.HashSet;

public class Program111 {

public static void main(String[] args) {

int[] arr = {1, 9, 3, 10, 4, 20, 2};

HashSet<Integer> set = new HashSet<>();

for (int num : arr) set.add(num);

int longest = 0;

for (int num : set) {

if (!set.contains(num - 1)) {

int curr = num, streak = 1;

while (set.contains(curr + 1)) {

curr++;

streak++;
}

longest = Math.max(longest, streak);

System.out.println("Longest Consecutive Subsequence = " + longest);

Program 112: Find length of longest increasing subsequence

public class Program112 {

public static void main(String[] args) {

int[] arr = {10, 22, 9, 33, 21, 50, 41, 60};

int n = arr.length;

int[] lis = new int[n];

for (int i = 0; i < n; i++) lis[i] = 1;

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

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

if (arr[i] > arr[j] && lis[i] < lis[j] + 1) {

lis[i] = lis[j] + 1;

int max = 0;

for (int val : lis) max = Math.max(max, val);

System.out.println("LIS Length = " + max);

Program 113: Find length of longest bitonic subsequence

public class Program113 {


public static void main(String[] args) {

int[] arr = {1, 11, 2, 10, 4, 5, 2, 1};

int n = arr.length;

int[] inc = new int[n];

int[] dec = new int[n];

for (int i = 0; i < n; i++) inc[i] = dec[i] = 1;

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

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

if (arr[i] > arr[j] && inc[i] < inc[j] + 1)

inc[i] = inc[j] + 1;

for (int i = n - 2; i >= 0; i--) {

for (int j = n - 1; j > i; j--) {

if (arr[i] > arr[j] && dec[i] < dec[j] + 1)

dec[i] = dec[j] + 1;

int max = 0;

for (int i = 0; i < n; i++) max = Math.max(max, inc[i] + dec[i] - 1);

System.out.println("LBS Length = " + max);

Program 114: Find maximum sum increasing subsequence

public class Program114 {

public static void main(String[] args) {

int[] arr = {1, 101, 2, 3, 100, 4, 5};


int n = arr.length;

int[] msis = new int[n];

for (int i = 0; i < n; i++) msis[i] = arr[i];

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

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

if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i])

msis[i] = msis[j] + arr[i];

int max = 0;

for (int val : msis) max = Math.max(max, val);

System.out.println("Max Sum Increasing Subsequence = " + max);

Program 115: Find maximum length of subarray with equal 0s and 1s

import java.util.HashMap;

public class Program115 {

public static void main(String[] args) {

int[] arr = {0, 0, 1, 0, 1, 0, 0};

HashMap<Integer, Integer> map = new HashMap<>();

int sum = 0, maxLen = 0;

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

sum += (arr[i] == 0) ? -1 : 1;

if (sum == 0) maxLen = i + 1;

if (map.containsKey(sum)) maxLen = Math.max(maxLen, i - map.get(sum));

else map.put(sum, i);

System.out.println("Max Length = " + maxLen);


}

Program 116: Find longest subarray with given sum

import java.util.HashMap;

public class Program116 {

public static void main(String[] args) {

int[] arr = {10, 5, 2, 7, 1, 9};

int k = 15;

HashMap<Integer, Integer> map = new HashMap<>();

int sum = 0, maxLen = 0;

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

sum += arr[i];

if (sum == k) maxLen = i + 1;

if (!map.containsKey(sum)) map.put(sum, i);

if (map.containsKey(sum - k)) maxLen = Math.max(maxLen, i - map.get(sum - k));

System.out.println("Longest Subarray Length = " + maxLen);

Program 117: Find subarray with 0 sum

import java.util.HashSet;

public class Program117 {

public static void main(String[] args) {

int[] arr = {4, 2, -3, 1, 6};

HashSet<Integer> set = new HashSet<>();

int sum = 0;

boolean found = false;

for (int num : arr) {


sum += num;

if (sum == 0 || set.contains(sum)) {

found = true;

break;

set.add(sum);

System.out.println("Subarray with 0 Sum Exists? " + found);

Program 118: Find largest subarray with equal number of 0s and 1s

import java.util.HashMap;

public class Program118 {

public static void main(String[] args) {

int[] arr = {1, 0, 0, 1, 0, 1, 1};

HashMap<Integer, Integer> map = new HashMap<>();

int sum = 0, maxLen = 0;

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

sum += (arr[i] == 0) ? -1 : 1;

if (sum == 0) maxLen = i + 1;

if (map.containsKey(sum)) maxLen = Math.max(maxLen, i - map.get(sum));

else map.put(sum, i);

System.out.println("Largest Subarray Length = " + maxLen);

Program 119: Find subarray with equal number of 0s, 1s, and 2s

import java.util.HashMap;
public class Program119 {

static class Pair {

int x, y;

Pair(int a, int b) { x = a; y = b; }

public boolean equals(Object o) {

if (!(o instanceof Pair)) return false;

Pair p = (Pair) o;

return x == p.x && y == p.y;

public int hashCode() { return 31 * x + y; }

public static void main(String[] args) {

int[] arr = {0, 1, 0, 2, 0, 1, 0};

int c0 = 0, c1 = 0, c2 = 0;

HashMap<Pair, Integer> map = new HashMap<>();

map.put(new Pair(0, 0), -1);

int maxLen = 0;

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

if (arr[i] == 0) c0++;

else if (arr[i] == 1) c1++;

else c2++;

Pair key = new Pair(c1 - c0, c2 - c1);

if (map.containsKey(key)) maxLen = Math.max(maxLen, i - map.get(key));

else map.put(key, i);

System.out.println("Largest Subarray Length = " + maxLen);

}
Program 120: Find equilibrium point in array (prefix sum method)

public class Program120 {

public static void main(String[] args) {

int[] arr = {3, 4, 8, -9, 20, 6};

int total = 0, left = 0;

for (int num : arr) total += num;

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

total -= arr[i];

if (left == total) {

System.out.println("Equilibrium Index = " + i);

return;

left += arr[i];

System.out.println("No Equilibrium Point");

Program 121: Count number of rotations in a rotated sorted array

public class Program121 {

public static void main(String[] args) {

int[] arr = {15, 18, 2, 3, 6, 12};

int n = arr.length;

int minIndex = 0, minValue = arr[0];

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

if (arr[i] < minValue) {

minValue = arr[i];

minIndex = i;

}
}

System.out.println("Array is rotated " + minIndex + " times.");

Program 122: Find missing number in an array (1 to n)

public class Program122 {

public static void main(String[] args) {

int[] arr = {1, 2, 4, 5, 6};

int n = 6;

int total = n * (n + 1) / 2;

int sum = 0;

for (int num : arr) sum += num;

System.out.println("Missing number = " + (total - sum));

Program 123: Find majority element (appears more than n/2 times)

public class Program123 {

public static void main(String[] args) {

int[] arr = {3, 3, 4, 2, 4, 4, 2, 4, 4};

int candidate = -1, count = 0;

for (int num : arr) {

if (count == 0) {

candidate = num;

count = 1;

} else if (num == candidate) {

count++;

} else {

count--;
}

count = 0;

for (int num : arr) if (num == candidate) count++;

if (count > arr.length / 2)

System.out.println("Majority Element = " + candidate);

else

System.out.println("No Majority Element");

Program 124: Find maximum product subarray

public class Program124 {

public static void main(String[] args) {

int[] arr = {2, 3, -2, 4};

int max = arr[0], min = arr[0], result = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] < 0) {

int temp = max;

max = min;

min = temp;

max = Math.max(arr[i], arr[i] * max);

min = Math.min(arr[i], arr[i] * min);

result = Math.max(result, max);

System.out.println("Maximum Product Subarray = " + result);

}
Program 125: Find maximum sum subarray (Kadane’s Algorithm)

public class Program125 {

public static void main(String[] args) {

int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3};

int maxSoFar = arr[0], maxEndingHere = arr[0];

for (int i = 1; i < arr.length; i++) {

maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);

maxSoFar = Math.max(maxSoFar, maxEndingHere);

System.out.println("Maximum Subarray Sum = " + maxSoFar);

Program 126: Rearrange array such that arr[i] = i if possible

import java.util.Arrays;

public class Program126 {

public static void main(String[] args) {

int[] arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1};

int n = arr.length;

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

while (arr[i] != -1 && arr[i] != i) {

int temp = arr[arr[i]];

arr[arr[i]] = arr[i];

arr[i] = temp;

System.out.println("Rearranged: " + Arrays.toString(arr));

}
Program 127: Find the equilibrium index

public class Program127 {

public static void main(String[] args) {

int[] arr = {-7, 1, 5, 2, -4, 3, 0};

int total = 0;

for (int num : arr) total += num;

int leftSum = 0;

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

total -= arr[i];

if (leftSum == total) {

System.out.println("Equilibrium Index = " + i);

return;

leftSum += arr[i];

System.out.println("No Equilibrium Index");

Program 128: Find peak element

public class Program128 {

public static void main(String[] args) {

int[] arr = {1, 3, 20, 4, 1, 0};

for (int i = 1; i < arr.length - 1; i++) {

if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) {

System.out.println("Peak Element = " + arr[i]);

return;

}
System.out.println("Peak Element = " + arr[arr.length - 1]);

Program 129: Maximum difference between two elements

public class Program129 {

public static void main(String[] args) {

int[] arr = {2, 3, 10, 6, 4, 8, 1};

int min = arr[0], maxDiff = arr[1] - arr[0];

for (int i = 1; i < arr.length; i++) {

maxDiff = Math.max(maxDiff, arr[i] - min);

min = Math.min(min, arr[i]);

System.out.println("Max Difference = " + maxDiff);

Program 130: Rearrange array in increasing-decreasing order

import java.util.Arrays;

import java.util.Collections;

public class Program130 {

public static void main(String[] args) {

Integer[] arr = {8, 7, 1, 6, 5, 9};

Arrays.sort(arr);

int n = arr.length;

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

System.out.print(arr[i] + " ");

for (int i = n - 1; i >= n / 2; i--) {

System.out.print(arr[i] + " ");


}

Program 131: Rearrange array in max-min form

import java.util.Arrays;

public class Program131 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

int[] result = new int[arr.length];

int i = 0, j = arr.length - 1, k = 0;

while (i <= j) {

if (k < arr.length) result[k++] = arr[j--];

if (k < arr.length) result[k++] = arr[i++];

System.out.println("Rearranged: " + Arrays.toString(result));

Program 132: Check if two arrays are disjoint

public class Program132 {

public static void main(String[] args) {

int[] arr1 = {12, 34, 11, 9, 3};

int[] arr2 = {7, 2, 1, 5};

boolean disjoint = true;

for (int a : arr1) {

for (int b : arr2) {

if (a == b) {

disjoint = false;

break;
}

System.out.println("Disjoint? " + disjoint);

Program 133: Find common elements between three arrays

public class Program133 {

public static void main(String[] args) {

int[] arr1 = {1, 5, 10, 20, 40, 80};

int[] arr2 = {6, 7, 20, 80, 100};

int[] arr3 = {3, 4, 15, 20, 30, 70, 80, 120};

int i = 0, j = 0, k = 0;

while (i < arr1.length && j < arr2.length && k < arr3.length) {

if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {

System.out.print(arr1[i] + " ");

i++; j++; k++;

} else if (arr1[i] < arr2[j]) i++;

else if (arr2[j] < arr3[k]) j++;

else k++;

Program 134: Print distinct elements

import java.util.HashSet;

public class Program134 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 2, 1, 4, 5};


HashSet<Integer> set = new HashSet<>();

for (int num : arr) set.add(num);

System.out.println("Distinct Elements: " + set);

Program 135: Count distinct elements

import java.util.HashSet;

public class Program135 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 2, 1, 4, 5};

HashSet<Integer> set = new HashSet<>();

for (int num : arr) set.add(num);

System.out.println("Count of Distinct = " + set.size());

Program 136: Find union of two arrays

import java.util.HashSet;

public class Program136 {

public static void main(String[] args) {

int[] arr1 = {1, 2, 4, 5};

int[] arr2 = {2, 3, 5, 6};

HashSet<Integer> set = new HashSet<>();

for (int n : arr1) set.add(n);

for (int n : arr2) set.add(n);

System.out.println("Union: " + set);

Program 137: Find intersection of two arrays


import java.util.HashSet;

public class Program137 {

public static void main(String[] args) {

int[] arr1 = {1, 2, 4, 5};

int[] arr2 = {2, 3, 5, 6};

HashSet<Integer> set = new HashSet<>();

for (int n : arr1) set.add(n);

for (int n : arr2) {

if (set.contains(n)) System.out.print(n + " ");

Program 138: Find symmetric difference of two arrays

import java.util.HashSet;

public class Program138 {

public static void main(String[] args) {

int[] arr1 = {1, 2, 4, 5};

int[] arr2 = {2, 3, 5, 6};

HashSet<Integer> set1 = new HashSet<>();

HashSet<Integer> set2 = new HashSet<>();

for (int n : arr1) set1.add(n);

for (int n : arr2) set2.add(n);

HashSet<Integer> temp = new HashSet<>(set1);

set1.removeAll(set2);

set2.removeAll(temp);

set1.addAll(set2);

System.out.println("Symmetric Difference: " + set1);

}
}

Program 139: Find kth smallest element

import java.util.Arrays;

public class Program139 {

public static void main(String[] args) {

int[] arr = {12, 3, 5, 7, 19};

int k = 2;

Arrays.sort(arr);

System.out.println(k + "th Smallest = " + arr[k - 1]);

Program 140: Find kth largest element

import java.util.Arrays;

public class Program140 {

public static void main(String[] args) {

int[] arr = {12, 3, 5, 7, 19};

int k = 2;

Arrays.sort(arr);

System.out.println(k + "th Largest = " + arr[arr.length - k]);

Program 141: Reverse array using recursion

import java.util.Arrays;

public class Program141 {

static void reverse(int[] arr, int start, int end) {

if (start >= end) return;

int temp = arr[start];

arr[start] = arr[end];
arr[end] = temp;

reverse(arr, start + 1, end - 1);

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

reverse(arr, 0, arr.length - 1);

System.out.println("Reversed: " + Arrays.toString(arr));

Program 142: Rotate array left by d positions

import java.util.Arrays;

public class Program142 {

static void leftRotate(int[] arr, int d) {

int n = arr.length;

d = d % n;

int[] temp = new int[d];

for (int i = 0; i < d; i++) temp[i] = arr[i];

for (int i = d; i < n; i++) arr[i - d] = arr[i];

for (int i = 0; i < d; i++) arr[n - d + i] = temp[i];

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

leftRotate(arr, 2);

System.out.println("Rotated Left: " + Arrays.toString(arr));

Program 143: Rotate array right by d positions

import java.util.Arrays;
public class Program143 {

static void rightRotate(int[] arr, int d) {

int n = arr.length;

d = d % n;

int[] temp = new int[d];

for (int i = 0; i < d; i++) temp[i] = arr[n - d + i];

for (int i = n - 1; i >= d; i--) arr[i] = arr[i - d];

for (int i = 0; i < d; i++) arr[i] = temp[i];

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

rightRotate(arr, 2);

System.out.println("Rotated Right: " + Arrays.toString(arr));

Program 144: Check if two arrays are equal

import java.util.Arrays;

public class Program144 {

public static void main(String[] args) {

int[] arr1 = {1, 2, 3, 4, 5};

int[] arr2 = {1, 2, 3, 4, 5};

boolean equal = Arrays.equals(arr1, arr2);

System.out.println("Arrays Equal? " + equal);

Program 145: Find missing and repeating elements

public class Program145 {

public static void main(String[] args) {


int[] arr = {4, 3, 6, 2, 1, 1};

int n = arr.length;

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

int repeating = -1, missing = -1;

for (int num : arr) {

if (seen[num]) repeating = num;

seen[num] = true;

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

if (!seen[i]) missing = i;

System.out.println("Repeating = " + repeating + ", Missing = " + missing);

Program 146: Find duplicate elements

public class Program146 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 1, 3, 6, 6};

System.out.print("Duplicates: ");

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] == arr[j]) {

System.out.print(arr[i] + " ");

break;

}
}

Program 147: Remove duplicates from sorted array

import java.util.Arrays;

public class Program147 {

public static void main(String[] args) {

int[] arr = {1, 1, 2, 2, 3, 4, 4, 5};

int j = 0;

for (int i = 0; i < arr.length - 1; i++) {

if (arr[i] != arr[i + 1]) arr[j++] = arr[i];

arr[j++] = arr[arr.length - 1];

int[] result = Arrays.copyOf(arr, j);

System.out.println("Without Duplicates: " + Arrays.toString(result));

Program 148: Find all pairs with given difference

public class Program148 {

public static void main(String[] args) {

int[] arr = {1, 5, 3, 4, 2};

int diff = 2;

System.out.print("Pairs: ");

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

for (int j = i + 1; j < arr.length; j++) {

if (Math.abs(arr[i] - arr[j]) == diff) {

System.out.print("(" + arr[i] + "," + arr[j] + ") ");

}
}

Program 149: Find element with odd frequency

public class Program149 {

public static void main(String[] args) {

int[] arr = {2, 3, 2, 3, 5};

int result = 0;

for (int num : arr) result ^= num;

System.out.println("Odd Frequency Element = " + result);

Program 150: Find element occurring once when others appear thrice

public class Program150 {

public static void main(String[] args) {

int[] arr = {3, 3, 2, 3};

int ones = 0, twos = 0;

for (int num : arr) {

ones = (ones ^ num) & ~twos;

twos = (twos ^ num) & ~ones;

System.out.println("Single Element = " + ones);

Program 151: Move negative numbers to one side

import java.util.Arrays;

public class Program151 {

public static void main(String[] args) {

int[] arr = {-1, 2, -3, 4, 5, -6};


int j = 0;

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

if (arr[i] < 0) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

j++;

System.out.println("Rearranged: " + Arrays.toString(arr));

Program 152: Find maximum product of two integers

public class Program152 {

public static void main(String[] args) {

int[] arr = {1, 4, 3, -6, -7, 0};

int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;

int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;

for (int num : arr) {

if (num > max1) { max2 = max1; max1 = num; }

else if (num > max2) max2 = num;

if (num < min1) { min2 = min1; min1 = num; }

else if (num < min2) min2 = num;

int prod = Math.max(max1 * max2, min1 * min2);

System.out.println("Max Product = " + prod);

}
Program 153: Check if array elements are consecutive

import java.util.HashSet;

public class Program153 {

public static void main(String[] args) {

int[] arr = {5, 4, 2, 3, 1};

int min = arr[0], max = arr[0];

HashSet<Integer> set = new HashSet<>();

for (int num : arr) {

set.add(num);

if (num < min) min = num;

if (num > max) max = num;

if (max - min + 1 == arr.length && set.size() == arr.length)

System.out.println("Consecutive");

else

System.out.println("Not Consecutive");

Program 154: Check if array can form arithmetic progression

import java.util.Arrays;

public class Program154 {

public static void main(String[] args) {

int[] arr = {3, 5, 1};

Arrays.sort(arr);

int diff = arr[1] - arr[0];

boolean ap = true;

for (int i = 2; i < arr.length; i++) {

if (arr[i] - arr[i - 1] != diff) {


ap = false;

break;

System.out.println("Can form AP? " + ap);

Program 155: Check if array can form geometric progression

import java.util.Arrays;

public class Program155 {

public static void main(String[] args) {

int[] arr = {2, 6, 18, 54};

Arrays.sort(arr);

boolean gp = true;

double ratio = (double) arr[1] / arr[0];

for (int i = 2; i < arr.length; i++) {

if ((double) arr[i] / arr[i - 1] != ratio) {

gp = false;

break;

System.out.println("Can form GP? " + gp);

Program 156: Find maximum length subarray with sum k

public class Program156 {

public static void main(String[] args) {

int[] arr = {10, 5, 2, 7, 1, 9};


int k = 15, maxLen = 0;

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

int sum = 0;

for (int j = i; j < arr.length; j++) {

sum += arr[j];

if (sum == k) maxLen = Math.max(maxLen, j - i + 1);

System.out.println("Max Length Subarray = " + maxLen);

Program 157: Find longest increasing subsequence length

public class Program157 {

public static void main(String[] args) {

int[] arr = {10, 22, 9, 33, 21, 50, 41, 60};

int n = arr.length;

int[] lis = new int[n];

for (int i = 0; i < n; i++) lis[i] = 1;

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

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

if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1;

int max = 0;

for (int num : lis) if (num > max) max = num;

System.out.println("LIS Length = " + max);

}
Program 158: Find maximum length of bitonic subsequence

public class Program158 {

public static void main(String[] args) {

int[] arr = {1, 11, 2, 10, 4, 5, 2, 1};

int n = arr.length;

int[] lis = new int[n], lds = new int[n];

for (int i = 0; i < n; i++) lis[i] = lds[i] = 1;

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

for (int j = 0; j < i; j++)

if (arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1;

for (int i = n - 2; i >= 0; i--)

for (int j = n - 1; j > i; j--)

if (arr[i] > arr[j] && lds[i] < lds[j] + 1) lds[i] = lds[j] + 1;

int max = 0;

for (int i = 0; i < n; i++) max = Math.max(max, lis[i] + lds[i] - 1);

System.out.println("Longest Bitonic Subsequence Length = " + max);

Program 159: Find maximum length of alternating subsequence

public class Program159 {

public static void main(String[] args) {

int[] arr = {1, 5, 4};

int n = arr.length;

int inc = 1, dec = 1;

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

if (arr[i] > arr[i - 1]) inc = dec + 1;

else if (arr[i] < arr[i - 1]) dec = inc + 1;

}
System.out.println("Longest Alternating Subsequence = " + Math.max(inc, dec));

Program 160: Find maximum sum increasing subsequence

public class Program160 {

public static void main(String[] args) {

int[] arr = {1, 101, 2, 3, 100, 4, 5};

int n = arr.length;

int[] msis = new int[n];

for (int i = 0; i < n; i++) msis[i] = arr[i];

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

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

if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) {

msis[i] = msis[j] + arr[i];

int max = 0;

for (int sum : msis) if (sum > max) max = sum;

System.out.println("Max Sum Increasing Subsequence = " + max);

Program 161: Find maximum circular subarray sum

public class Program161 {

public static void main(String[] args) {

int[] arr = {8, -4, 3, -5, 4};

int maxKadane = kadane(arr);

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

total += arr[i];

arr[i] = -arr[i];

int maxWrap = total + kadane(arr);

System.out.println("Max Circular Subarray Sum = " + Math.max(maxKadane, maxWrap));

static int kadane(int[] arr) {

int maxSoFar = arr[0], maxEndingHere = arr[0];

for (int i = 1; i < arr.length; i++) {

maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);

maxSoFar = Math.max(maxSoFar, maxEndingHere);

return maxSoFar;

Program 162: Find maximum length of subarray with equal 0s and 1s

import java.util.*;

public class Program162 {

public static void main(String[] args) {

int[] arr = {1, 0, 0, 1, 0, 1, 1};

Map<Integer, Integer> map = new HashMap<>();

int sum = 0, maxLen = 0;

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

sum += (arr[i] == 0 ? -1 : 1);

if (sum == 0) maxLen = i + 1;

if (map.containsKey(sum)) maxLen = Math.max(maxLen, i - map.get(sum));


else map.put(sum, i);

System.out.println("Max Length Subarray (Equal 0s & 1s) = " + maxLen);

Program 163: Rearrange array so that arr[i] becomes arr[arr[i]]

import java.util.Arrays;

public class Program163 {

public static void main(String[] args) {

int[] arr = {3, 2, 0, 1};

int n = arr.length;

for (int i = 0; i < n; i++) arr[i] += (arr[arr[i]] % n) * n;

for (int i = 0; i < n; i++) arr[i] /= n;

System.out.println("Rearranged: " + Arrays.toString(arr));

Program 164: Find maximum distance between same elements

import java.util.*;

public class Program164 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 1, 4, 2, 5};

Map<Integer, Integer> firstIndex = new HashMap<>();

int maxDist = 0;

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

if (!firstIndex.containsKey(arr[i])) firstIndex.put(arr[i], i);

else maxDist = Math.max(maxDist, i - firstIndex.get(arr[i]));

System.out.println("Max Distance = " + maxDist);


}

Program 165: Find maximum repeating element

public class Program165 {

public static void main(String[] args) {

int[] arr = {2, 3, 3, 5, 3, 4, 1, 7};

int maxCount = 0, result = arr[0];

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

int count = 0;

for (int j = 0; j < arr.length; j++) {

if (arr[j] == arr[i]) count++;

if (count > maxCount) {

maxCount = count;

result = arr[i];

System.out.println("Max Repeating Element = " + result);

Program 166: Find element with left side smaller and right side greater

public class Program166 {

public static void main(String[] args) {

int[] arr = {4, 2, 5, 7};

for (int i = 1; i < arr.length - 1; i++) {

int leftMax = arr[0], rightMin = arr[arr.length - 1];

for (int j = 0; j < i; j++) leftMax = Math.max(leftMax, arr[j]);

for (int j = i + 1; j < arr.length; j++) rightMin = Math.min(rightMin, arr[j]);


if (arr[i] >= leftMax && arr[i] <= rightMin) {

System.out.println("Element = " + arr[i]);

return;

System.out.println("No such element");

Program 167: Count inversions in array

public class Program167 {

public static void main(String[] args) {

int[] arr = {1, 20, 6, 4, 5};

int count = 0;

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] > arr[j]) count++;

System.out.println("Inversions = " + count);

Program 168: Find maximum j - i such that arr[j] > arr[i]

public class Program168 {

public static void main(String[] args) {

int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};

int maxDiff = -1;

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

for (int j = arr.length - 1; j > i; j--) {


if (arr[j] > arr[i]) {

maxDiff = Math.max(maxDiff, j - i);

break;

System.out.println("Max j - i = " + maxDiff);

Program 169: Find equilibrium point (efficient)

public class Program169 {

public static void main(String[] args) {

int[] arr = {3, 4, 8, -9, 20, 6};

int total = 0;

for (int num : arr) total += num;

int leftSum = 0;

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

total -= arr[i];

if (leftSum == total) {

System.out.println("Equilibrium Point = " + i);

return;

leftSum += arr[i];

System.out.println("No Equilibrium Point");

Program 170: Find maximum water trapped between buildings


public class Program170 {

public static void main(String[] args) {

int[] height = {3, 0, 0, 2, 0, 4};

int n = height.length;

int[] left = new int[n];

int[] right = new int[n];

left[0] = height[0];

for (int i = 1; i < n; i++) left[i] = Math.max(left[i - 1], height[i]);

right[n - 1] = height[n - 1];

for (int i = n - 2; i >= 0; i--) right[i] = Math.max(right[i + 1], height[i]);

int water = 0;

for (int i = 0; i < n; i++) water += Math.min(left[i], right[i]) - height[i];

System.out.println("Water Trapped = " + water);

Program 171: Rearrange array in alternating positive and negative (order maintained)

import java.util.*;

public class Program171 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, -4, -1, 4};

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

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

for (int num : arr) {

if (num >= 0) pos.add(num);

else neg.add(num);

int i = 0, j = 0, k = 0;

while (i < pos.size() && j < neg.size()) {


arr[k++] = pos.get(i++);

arr[k++] = neg.get(j++);

while (i < pos.size()) arr[k++] = pos.get(i++);

while (j < neg.size()) arr[k++] = neg.get(j++);

System.out.println("Rearranged: " + Arrays.toString(arr));

Program 172: Find the smallest subarray with sum greater than a given value

public class Program172 {

public static void main(String[] args) {

int[] arr = {1, 4, 45, 6, 0, 19};

int x = 51, minLen = arr.length + 1;

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

int sum = arr[i];

if (sum > x) {

System.out.println(1);

return;

for (int j = i + 1; j < arr.length; j++) {

sum += arr[j];

if (sum > x && (j - i + 1) < minLen) minLen = j - i + 1;

System.out.println("Min Length Subarray = " + minLen);

Program 173: Find peak element in array


public class Program173 {

public static void main(String[] args) {

int[] arr = {5, 10, 20, 15};

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

if ((i == 0 || arr[i - 1] <= arr[i]) && (i == arr.length - 1 || arr[i + 1] <= arr[i])) {

System.out.println("Peak Element = " + arr[i]);

break;

Program 174: Find maximum subarray sum modulo m

public class Program174 {

public static void main(String[] args) {

int[] arr = {3, 3, 9, 9, 5};

int m = 7, maxSum = 0;

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

int sum = 0;

for (int j = i; j < arr.length; j++) {

sum += arr[j];

maxSum = Math.max(maxSum, sum % m);

System.out.println("Max Subarray Sum % m = " + maxSum);

Program 175: Find maximum absolute difference between nearest left and right smaller
elements
public class Program175 {

public static void main(String[] args) {

int[] arr = {2, 1, 8};

int result = 0;

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

int left = 0, right = 0;

for (int j = i - 1; j >= 0; j--) {

if (arr[j] < arr[i]) {

left = arr[j];

break;

for (int j = i + 1; j < arr.length; j++) {

if (arr[j] < arr[i]) {

right = arr[j];

break;

result = Math.max(result, Math.abs(left - right));

System.out.println("Max Difference = " + result);

Program 176: Find maximum length bitonic subarray

public class Program176 {

public static void main(String[] args) {

int[] arr = {12, 4, 78, 90, 45, 23};

int n = arr.length;
int[] inc = new int[n];

int[] dec = new int[n];

inc[0] = 1;

dec[n - 1] = 1;

for (int i = 1; i < n; i++) inc[i] = arr[i] > arr[i - 1] ? inc[i - 1] + 1 : 1;

for (int i = n - 2; i >= 0; i--) dec[i] = arr[i] > arr[i + 1] ? dec[i + 1] + 1 : 1;

int max = inc[0] + dec[0] - 1;

for (int i = 1; i < n; i++) max = Math.max(max, inc[i] + dec[i] - 1);

System.out.println("Max Length Bitonic Subarray = " + max);

Program 177: Count number of elements smaller than current element

import java.util.*;

public class Program177 {

public static void main(String[] args) {

int[] arr = {8, 1, 2, 2, 3};

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

int count = 0;

for (int j = 0; j < arr.length; j++) {

if (arr[j] < arr[i]) count++;

System.out.println(arr[i] + " -> " + count);

Program 178: Find equilibrium point using prefix sum

public class Program178 {

public static void main(String[] args) {


int[] arr = {1, 3, 5, 2, 2};

int total = 0;

for (int num : arr) total += num;

int leftSum = 0;

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

if (leftSum == total - leftSum - arr[i]) {

System.out.println("Equilibrium Index = " + i);

return;

leftSum += arr[i];

System.out.println("No Equilibrium Index");

Program 179: Find maximum product of three numbers

import java.util.Arrays;

public class Program179 {

public static void main(String[] args) {

int[] arr = {-10, -10, 5, 2};

Arrays.sort(arr);

int n = arr.length;

int prod1 = arr[n - 1] * arr[n - 2] * arr[n - 3];

int prod2 = arr[0] * arr[1] * arr[n - 1];

System.out.println("Max Product of 3 = " + Math.max(prod1, prod2));

Program 180: Count pairs with given difference

public class Program180 {


public static void main(String[] args) {

int[] arr = {1, 5, 3, 4, 2};

int diff = 2, count = 0;

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

for (int j = i + 1; j < arr.length; j++) {

if (Math.abs(arr[i] - arr[j]) == diff) count++;

System.out.println("Pairs with difference " + diff + " = " + count);

Program 181: Count occurrences of each element (HashMap)

import java.util.HashMap;

public class Program181 {

public static void main(String[] args) {

int[] arr = {10, 20, 10, 30, 20, 20, 40};

HashMap<Integer, Integer> freq = new HashMap<>();

for (int v : arr) freq.put(v, freq.getOrDefault(v, 0) + 1);

System.out.println("Frequencies: " + freq);

Program 182: Left rotate array by k (reversal algorithm)

import java.util.Arrays;

public class Program182 {

static void reverse(int[] a, int l, int r) {

while (l < r) { int t = a[l]; a[l++] = a[r]; a[r--] = t; }

public static void main(String[] args) {


int[] arr = {1,2,3,4,5,6,7};

int k = 3; int n = arr.length;

k %= n;

reverse(arr, 0, k-1);

reverse(arr, k, n-1);

reverse(arr, 0, n-1);

System.out.println("Left rotated: " + Arrays.toString(arr));

Program 183: Transpose of a matrix (2D array)

import java.util.Arrays;

public class Program183 {

public static void main(String[] args) {

int[][] m = {{1,2,3},{4,5,6}};

int r = m.length, c = m[0].length;

int[][] t = new int[c][r];

for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) t[j][i] = m[i][j];

for (int[] row : t) System.out.println(Arrays.toString(row));

Program 184: Check if two arrays are permutations of each other (sorting)

import java.util.Arrays;

public class Program184 {

public static void main(String[] args) {

int[] a = {1,2,3,4};

int[] b = {4,3,2,1};

Arrays.sort(a); Arrays.sort(b);

System.out.println("Permutation? " + Arrays.equals(a,b));


}

Program 185: Find a pair with given sum (HashSet, O(n))

import java.util.HashSet;

public class Program185 {

public static void main(String[] args) {

int[] arr = {8, 7, 2, 5, 3, 1};

int target = 10;

HashSet<Integer> set = new HashSet<>();

for (int v : arr) {

if (set.contains(target - v)) {

System.out.println("Pair: " + v + ", " + (target - v));

return;

set.add(v);

System.out.println("No pair found");

Program 186: Three-sum — find triplets with zero sum (sorting + two pointers)

import java.util.Arrays;

public class Program186 {

public static void main(String[] args) {

int[] arr = {-1, 0, 1, 2, -1, -4};

Arrays.sort(arr);

for (int i = 0; i < arr.length - 2; i++) {

if (i > 0 && arr[i] == arr[i-1]) continue;

int l = i+1, r = arr.length-1;


while (l < r) {

int s = arr[i] + arr[l] + arr[r];

if (s == 0) {

System.out.println(arr[i] + ", " + arr[l] + ", " + arr[r]);

l++; r--;

while (l < r && arr[l] == arr[l-1]) l++;

while (l < r && arr[r] == arr[r+1]) r--;

} else if (s < 0) l++; else r--;

Program 187: Product of array except self (no division)

import java.util.Arrays;

public class Program187 {

public static void main(String[] args) {

int[] arr = {1,2,3,4};

int n = arr.length;

int[] left = new int[n], right = new int[n], prod = new int[n];

left[0] = 1;

for (int i = 1; i < n; i++) left[i] = left[i-1] * arr[i-1];

right[n-1] = 1;

for (int i = n-2; i >= 0; i--) right[i] = right[i+1] * arr[i+1];

for (int i = 0; i < n; i++) prod[i] = left[i] * right[i];

System.out.println("Product except self: " + Arrays.toString(prod));

Program 188: Dutch National Flag (sort 0s,1s,2s)


import java.util.Arrays;

public class Program188 {

public static void main(String[] args) {

int[] arr = {2,0,2,1,1,0};

int low = 0, mid = 0, high = arr.length - 1;

while (mid <= high) {

if (arr[mid] == 0) { int t = arr[low]; arr[low++] = arr[mid]; arr[mid++] = t; }

else if (arr[mid] == 1) mid++;

else { int t = arr[mid]; arr[mid] = arr[high]; arr[high--] = t; }

System.out.println(Arrays.toString(arr));

Program 189: Median of merged arrays (merge then median)

import java.util.Arrays;

public class Program189 {

public static void main(String[] args) {

int[] a = {1,3,5}, b = {2,4,6};

int[] merged = new int[a.length + b.length];

int i=0,j=0,k=0;

while (i<a.length && j<b.length) merged[k++] = (a[i] < b[j]) ? a[i++] : b[j++];

while (i<a.length) merged[k++] = a[i++];

while (j<b.length) merged[k++] = b[j++];

int n = merged.length;

double median = (n % 2 == 0) ? (merged[n/2 - 1] + merged[n/2]) / 2.0 : merged[n/2];

System.out.println("Median = " + median);

}
Program 190: Top k frequent elements (max frequency using PQ)

import java.util.*;

public class Program190 {

public static void main(String[] args) {

int[] arr = {1,1,1,2,2,3,3,3,3,4};

int k = 2;

HashMap<Integer,Integer> freq = new HashMap<>();

for (int v : arr) freq.put(v, freq.getOrDefault(v,0)+1);

PriorityQueue<Integer> pq = new PriorityQueue<>((x,y) -> freq.get(y)-freq.get(x));

pq.addAll(freq.keySet());

System.out.print("Top " + k + " : ");

for (int i=0;i<k;i++) System.out.print(pq.poll() + " ");

Program 191: Length of longest alternating subarray

public class Program191 {

public static void main(String[] args) {

int[] arr = {1,3,2,4,3,5};

int inc = 1, dec = 1, ans = 1;

for (int i = 1; i < arr.length; i++) {

if (arr[i] > arr[i-1]) inc = dec + 1;

else if (arr[i] < arr[i-1]) dec = inc + 1;

ans = Math.max(ans, Math.max(inc, dec));

System.out.println("Longest alternating length = " + ans);

Program 192: Partition array into two subsets with equal sum (DP subset-sum)
import java.util.BitSet;

public class Program192 {

public static void main(String[] args) {

int[] arr = {1,5,11,5};

int sum = 0;

for (int v : arr) sum += v;

if (sum % 2 != 0) { System.out.println("Not possible"); return; }

int target = sum / 2;

BitSet dp = new BitSet(target + 1);

dp.set(0);

for (int num : arr) {

for (int s = target; s >= num; s--) if (dp.get(s - num)) dp.set(s);

System.out.println("Partition possible? " + dp.get(target));

Program 193: Find duplicate using Floyd's cycle detection (nums in [1..n-1])

public class Program193 {

public static void main(String[] args) {

int[] nums = {1,3,4,2,2}; // one duplicate

int tortoise = nums[0], hare = nums[0];

do { tortoise = nums[tortoise]; hare = nums[nums[hare]]; } while (tortoise != hare);

tortoise = nums[0];

while (tortoise != hare) { tortoise = nums[tortoise]; hare = nums[hare]; }

System.out.println("Duplicate = " + tortoise);

Program 194: Check if one array is subset of another


import java.util.HashSet;

public class Program194 {

public static void main(String[] args) {

int[] A = {11,1,13,21,3,7};

int[] B = {11,3,7,1};

HashSet<Integer> set = new HashSet<>();

for (int v : A) set.add(v);

boolean isSubset = true;

for (int v : B) if (!set.contains(v)) { isSubset = false; break; }

System.out.println("B subset of A? " + isSubset);

Program 195: Maximum sum with no two adjacent (DP)

public class Program195 {

public static void main(String[] args) {

int[] arr = {5, 5, 10, 100, 10, 5};

int incl = 0, excl = 0;

for (int v : arr) {

int newExcl = Math.max(incl, excl);

incl = excl + v;

excl = newExcl;

System.out.println("Max sum with no adjacent = " + Math.max(incl, excl));

Program 196: Find k smallest elements (max-heap of size k)

import java.util.PriorityQueue;

import java.util.Arrays;
public class Program196 {

public static void main(String[] args) {

int[] arr = {7,10,4,3,20,15};

int k = 3;

PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b) -> b - a);

for (int v : arr) {

maxHeap.offer(v);

if (maxHeap.size() > k) maxHeap.poll();

System.out.println("K smallest: " + Arrays.toString(maxHeap.toArray()));

Program 197: Find all missing numbers in 1..n (multiple missing)

import java.util.ArrayList;

public class Program197 {

public static void main(String[] args) {

int[] arr = {4,3,2,7,8,2,3,1};

int n = arr.length;

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

int idx = Math.abs(arr[i]) - 1;

if (idx >= 0 && idx < n) arr[idx] = -Math.abs(arr[idx]);

ArrayList<Integer> miss = new ArrayList<>();

for (int i = 0; i < n; i++) if (arr[i] > 0) miss.add(i + 1);

System.out.println("Missing: " + miss);

Program 198: Find element that appears once while others appear twice (XOR)
public class Program198 {

public static void main(String[] args) {

int[] arr = {2,3,2,4,4};

int x = 0;

for (int v : arr) x ^= v;

System.out.println("Single element = " + x);

Program 199: Count rotations in sorted rotated array (binary search for min)

public class Program199 {

public static int countRotations(int[] arr) {

int low = 0, high = arr.length - 1;

while (low <= high) {

if (arr[low] <= arr[high]) return low; // already sorted

int mid = (low + high) / 2;

int next = (mid + 1) % arr.length;

int prev = (mid - 1 + arr.length) % arr.length;

if (arr[mid] <= arr[next] && arr[mid] <= arr[prev]) return mid;

else if (arr[mid] <= arr[high]) high = mid - 1;

else low = mid + 1;

return 0;

public static void main(String[] args) {

int[] arr = {15,18,2,3,6,12};

System.out.println("Rotation count = " + countRotations(arr));

}
Program 200: Spiral traversal of a 2D array (flatten to 1D)

import java.util.ArrayList;

import java.util.List;

public class Program200 {

public static void main(String[] args) {

int[][] mat = {

{1,2,3,4},

{5,6,7,8},

{9,10,11,12}

};

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

int top = 0, bottom = mat.length-1, left = 0, right = mat[0].length-1;

while (top <= bottom && left <= right) {

for (int j = left; j <= right; j++) spiral.add(mat[top][j]);

top++;

for (int i = top; i <= bottom; i++) spiral.add(mat[i][right]);

right--;

if (top <= bottom) {

for (int j = right; j >= left; j--) spiral.add(mat[bottom][j]);

bottom--;

if (left <= right) {

for (int i = bottom; i >= top; i--) spiral.add(mat[i][left]);

left++;

System.out.println("Spiral: " + spiral);

}
}

Program 201: Find equilibrium index in array

public class Program201 {

public static void main(String[] args) {

int[] arr = { -7, 1, 5, 2, -4, 3, 0 };

int total = 0, leftSum = 0;

for (int num : arr) total += num;

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

total -= arr[i];

if (leftSum == total) {

System.out.println("Equilibrium index: " + i);

return;

leftSum += arr[i];

System.out.println("No equilibrium index");

Program 202: Find maximum index difference

public class Program202 {

public static void main(String[] args) {

int[] arr = {34, 8, 10, 3, 2, 80, 30, 33, 1};

int n = arr.length, maxDiff = -1;

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

for (int j = n - 1; j > i; j--) {

if (arr[j] > arr[i] && maxDiff < (j - i)) {

maxDiff = j - i;
}

System.out.println("Max index diff = " + maxDiff);

Program 203: Find leaders in array

public class Program203 {

public static void main(String[] args) {

int[] arr = {16, 17, 4, 3, 5, 2};

int n = arr.length;

int max = arr[n - 1];

System.out.print("Leaders: " + max);

for (int i = n - 2; i >= 0; i--) {

if (arr[i] > max) {

max = arr[i];

System.out.print(" " + max);

Program 204: Find maximum product of a triplet

public class Program204 {

public static void main(String[] args) {

int[] arr = {1, 10, -5, 1, -100};

int maxProduct = Integer.MIN_VALUE;

for (int i = 0; i < arr.length - 2; i++) {

for (int j = i + 1; j < arr.length - 1; j++) {


for (int k = j + 1; k < arr.length; k++) {

maxProduct = Math.max(maxProduct, arr[i] * arr[j] * arr[k]);

System.out.println("Max product of triplet = " + maxProduct);

Program 205: Replace every element with product of all other elements

import java.util.Arrays;

public class Program205 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4};

int n = arr.length;

int[] prod = new int[n];

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

prod[i] = 1;

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

if (i != j) prod[i] *= arr[j];

System.out.println(Arrays.toString(prod));

Program 206: Find element occurring more than n/2 times (Majority Element)

public class Program206 {

public static void main(String[] args) {

int[] arr = {3, 3, 4, 2, 4, 4, 2, 4, 4};


int count = 0, candidate = -1;

for (int num : arr) {

if (count == 0) {

candidate = num;

count = 1;

} else if (num == candidate) count++;

else count--;

count = 0;

for (int num : arr) if (num == candidate) count++;

if (count > arr.length / 2) System.out.println("Majority element: " + candidate);

else System.out.println("No majority element");

Program 207: Find subarray with maximum product

public class Program207 {

public static void main(String[] args) {

int[] arr = {2, 3, -2, 4};

int maxProd = arr[0], minProd = arr[0], result = arr[0];

for (int i = 1; i < arr.length; i++) {

int temp = Math.max(arr[i], Math.max(maxProd * arr[i], minProd * arr[i]));

minProd = Math.min(arr[i], Math.min(maxProd * arr[i], minProd * arr[i]));

maxProd = temp;

result = Math.max(result, maxProd);

System.out.println("Max product subarray = " + result);

}
Program 208: Find element with left side smaller and right side greater

public class Program208 {

public static void main(String[] args) {

int[] arr = {4, 2, 5, 7};

int n = arr.length;

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

int leftMax = arr[0];

for (int j = 0; j < i; j++) leftMax = Math.max(leftMax, arr[j]);

int rightMin = arr[i + 1];

for (int j = i + 1; j < n; j++) rightMin = Math.min(rightMin, arr[j]);

if (arr[i] > leftMax && arr[i] < rightMin) {

System.out.println("Element found: " + arr[i]);

return;

System.out.println("No such element");

Program 209: Minimum swaps to sort array

import java.util.*;

public class Program209 {

public static void main(String[] args) {

int[] arr = {4, 3, 2, 1};

int n = arr.length;

boolean[] visited = new boolean[n];

int[][] pair = new int[n][2];

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

pair[i][0] = arr[i];
pair[i][1] = i;

Arrays.sort(pair, Comparator.comparingInt(a -> a[0]));

int ans = 0;

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

if (visited[i] || pair[i][1] == i) continue;

int cycleSize = 0, j = i;

while (!visited[j]) {

visited[j] = true;

j = pair[j][1];

cycleSize++;

if (cycleSize > 0) ans += (cycleSize - 1);

System.out.println("Min swaps: " + ans);

Program 210: Rearrange array alternatively (max, min, second max, second min…)

import java.util.Arrays;

public class Program210 {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7};

int n = arr.length;

int[] temp = new int[n];

int start = 0, end = n - 1, k = 0;

while (start <= end) {

if (k < n) temp[k++] = arr[end--];

if (k < n) temp[k++] = arr[start++];


}

System.out.println(Arrays.toString(temp));

Program 211: Find all pairs with difference k

public class Program211 {

public static void main(String[] args) {

int[] arr = {1, 5, 3, 4, 2};

int k = 2;

int count = 0;

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

for (int j = i + 1; j < arr.length; j++) {

if (Math.abs(arr[i] - arr[j]) == k) count++;

System.out.println("Pairs count = " + count);

Program 212: Find median of array

import java.util.Arrays;

public class Program212 {

public static void main(String[] args) {

int[] arr = {90, 100, 40, 60, 20};

Arrays.sort(arr);

double median;

int n = arr.length;

if (n % 2 == 0)

median = (arr[n/2 - 1] + arr[n/2]) / 2.0;


else

median = arr[n/2];

System.out.println("Median = " + median);

Program 213: Find mode of array

public class Program213 {

public static void main(String[] args) {

int[] arr = {1, 3, 3, 3, 2, 2, 4};

int mode = arr[0], maxCount = 0;

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

int count = 0;

for (int j = 0; j < arr.length; j++) {

if (arr[j] == arr[i]) count++;

if (count > maxCount) {

maxCount = count;

mode = arr[i];

System.out.println("Mode = " + mode);

Program 214: Find kth smallest element

import java.util.Arrays;

public class Program214 {

public static void main(String[] args) {

int[] arr = {7, 10, 4, 3, 20, 15};


int k = 3;

Arrays.sort(arr);

System.out.println(k + "th smallest = " + arr[k - 1]);

Program 215: Find kth largest element

import java.util.Arrays;

public class Program215 {

public static void main(String[] args) {

int[] arr = {7, 10, 4, 3, 20, 15};

int k = 2;

Arrays.sort(arr);

System.out.println(k + "th largest = " + arr[arr.length - k]);

Program 216: Find floor and ceiling of a number

import java.util.Arrays;

public class Program216 {

public static void main(String[] args) {

int[] arr = {1, 2, 8, 10, 10, 12, 19};

int x = 5;

int floor = -1, ceil = -1;

for (int num : arr) {

if (num <= x) floor = num;

if (num >= x && ceil == -1) ceil = num;

System.out.println("Floor = " + floor + ", Ceil = " + ceil);

}
}

Program 217: Count inversions in array

public class Program217 {

public static void main(String[] args) {

int[] arr = {1, 20, 6, 4, 5};

int count = 0;

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

for (int j = i + 1; j < arr.length; j++) {

if (arr[i] > arr[j]) count++;

System.out.println("Inversions count = " + count);

Program 218: Find length of longest increasing subsequence

public class Program218 {

public static void main(String[] args) {

int[] arr = {10, 22, 9, 33, 21, 50, 41, 60};

int n = arr.length;

int[] lis = new int[n];

for (int i = 0; i < n; i++) lis[i] = 1;

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

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

if (arr[i] > arr[j] && lis[i] < lis[j] + 1)

lis[i] = lis[j] + 1;

int max = 0;
for (int val : lis) max = Math.max(max, val);

System.out.println("Length of LIS = " + max);

Program 219: Find maximum length subarray with equal 0s and 1s

import java.util.HashMap;

public class Program219 {

public static void main(String[] args) {

int[] arr = {0, 0, 1, 0, 1, 1, 0};

HashMap<Integer, Integer> map = new HashMap<>();

int sum = 0, maxLen = 0;

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

sum += (arr[i] == 0) ? -1 : 1;

if (sum == 0) maxLen = i + 1;

if (map.containsKey(sum))

maxLen = Math.max(maxLen, i - map.get(sum));

else

map.put(sum, i);

System.out.println("Max length = " + maxLen);

Program 220: Find smallest subarray with sum greater than given value

public class Program220 {

public static void main(String[] args) {

int[] arr = {1, 4, 45, 6, 0, 19};

int x = 51;

int minLen = arr.length + 1;


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

int sum = arr[i];

if (sum > x) {

System.out.println("Min length = 1");

return;

for (int j = i + 1; j < arr.length; j++) {

sum += arr[j];

if (sum > x && (j - i + 1) < minLen) {

minLen = j - i + 1;

System.out.println("Min length = " + (minLen == arr.length + 1 ? 0 : minLen));

Program 221: Rotate matrix 90 degrees clockwise

import java.util.Arrays;

public class Program221 {

public static void main(String[] args) {

int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};

int n = mat.length;

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

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

int t = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = t;

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


for (int j = 0, k = n-1; j < k; j++, k--) {

int t = mat[i][j]; mat[i][j] = mat[i][k]; mat[i][k] = t;

for (int[] row : mat) System.out.println(Arrays.toString(row));

Program 222: Count inversions in an array (merge sort)

public class Program222 {

static long mergeSort(int[] arr, int l, int r) {

if (l >= r) return 0;

int m = (l+r)/2;

long inv = mergeSort(arr, l, m) + mergeSort(arr, m+1, r);

inv += merge(arr, l, m, r);

return inv;

static long merge(int[] arr, int l, int m, int r) {

int[] left = new int[m-l+1], right = new int[r-m];

for (int i=0;i<left.length;i++) left[i]=arr[l+i];

for (int i=0;i<right.length;i++) right[i]=arr[m+1+i];

int i=0,j=0,k=l; long inv=0;

while (i<left.length && j<right.length) {

if (left[i]<=right[j]) arr[k++]=left[i++];

else { arr[k++]=right[j++]; inv += left.length-i; }

while(i<left.length) arr[k++]=left[i++];

while(j<right.length) arr[k++]=right[j++];
return inv;

public static void main(String[] args) {

int[] arr = {2,4,1,3,5};

System.out.println("Inversions = " + mergeSort(arr,0,arr.length-1));

Program 223: Find majority element (>n/2 times)

public class Program223 {

public static void main(String[] args) {

int[] arr = {3,3,4,2,4,4,2,4,4};

int count=0,candidate=0;

for(int num:arr){

if(count==0){candidate=num;}

count+=(num==candidate)?1:-1;

count=0;

for(int num:arr) if(num==candidate) count++;

if(count>arr.length/2) System.out.println("Majority = "+candidate);

else System.out.println("No majority element");

Program 224: Kadane’s Algorithm for max subarray sum

public class Program224 {

public static void main(String[] args) {

int[] arr = {-2,1,-3,4,-1,2,1,-5,4};


int maxSoFar=arr[0], maxEnding=arr[0];

for(int i=1;i<arr.length;i++){

maxEnding = Math.max(arr[i], maxEnding+arr[i]);

maxSoFar = Math.max(maxSoFar, maxEnding);

System.out.println("Max subarray sum = " + maxSoFar);

Program 225: Trapping Rain Water

public class Program225 {

public static void main(String[] args) {

int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};

int n = height.length;

int[] left = new int[n], right = new int[n];

left[0]=height[0]; for(int i=1;i<n;i++) left[i]=Math.max(left[i-1],height[i]);

right[n-1]=height[n-1]; for(int i=n-2;i>=0;i--) right[i]=Math.max(right[i+1],height[i]);

int water=0; for(int i=0;i<n;i++) water+=Math.min(left[i],right[i])-height[i];

System.out.println("Water trapped = " + water);

Program 226: Max product subarray

public class Program226 {

public static void main(String[] args) {

int[] arr = {2,3,-2,4};

int max=arr[0],min=arr[0],res=arr[0];

for(int i=1;i<arr.length;i++){
if(arr[i]<0){int t=max;max=min;min=t;}

max=Math.max(arr[i],max*arr[i]);

min=Math.min(arr[i],min*arr[i]);

res=Math.max(res,max);

System.out.println("Max product = "+res);

Program 227: Sliding Window Maximum

import java.util.*;

public class Program227 {

public static void main(String[] args) {

int[] arr = {1,3,-1,-3,5,3,6,7};

int k=3;

Deque<Integer> dq = new LinkedList<>();

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

if(!dq.isEmpty() && dq.peek()==i-k) dq.poll();

while(!dq.isEmpty() && arr[dq.peekLast()]<arr[i]) dq.pollLast();

dq.offer(i);

if(i>=k-1) System.out.print(arr[dq.peek()]+" ");

Program 228: Find equilibrium index

public class Program228 {

public static void main(String[] args) {


int[] arr = {-7,1,5,2,-4,3,0};

int total=0; for(int v:arr) total+=v;

int left=0;

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

total-=arr[i];

if(left==total){ System.out.println("Equilibrium index = "+i); break; }

left+=arr[i];

Program 229: Minimum jumps to reach end

public class Program229 {

public static void main(String[] args) {

int[] arr = {2,3,1,1,4};

int jumps=0,curEnd=0,curFarthest=0;

for(int i=0;i<arr.length-1;i++){

curFarthest=Math.max(curFarthest,i+arr[i]);

if(i==curEnd){

jumps++;

curEnd=curFarthest;

System.out.println("Min jumps = " + jumps);

Program 230: Maximum circular subarray sum


public class Program230 {

static int kadane(int[] arr){

int max=arr[0],cur=arr[0];

for(int i=1;i<arr.length;i++){cur=Math.max(arr[i],cur+arr[i]);max=Math.max(max,cur);}

return max;

public static void main(String[] args) {

int[] arr = {5,-3,5};

int normal=kadane(arr);

int sum=0; for(int v:arr) sum+=v;

for(int i=0;i<arr.length;i++) arr[i]=-arr[i];

int circular=sum+kadane(arr);

System.out.println("Max circular sum = " +


(circular==0?normal:Math.max(normal,circular)));

Program 231: Stock Buy and Sell (max profit with one transaction)

public class Program231 {

public static void main(String[] args) {

int[] prices = {7,1,5,3,6,4};

int min=prices[0],profit=0;

for(int p:prices){

min=Math.min(min,p);

profit=Math.max(profit,p-min);

System.out.println("Max profit = " + profit);

}
}

Program 232: Stock Buy and Sell (multiple transactions)

public class Program232 {

public static void main(String[] args) {

int[] prices = {7,1,5,3,6,4};

int profit=0;

for(int i=1;i<prices.length;i++){

if(prices[i]>prices[i-1]) profit+=prices[i]-prices[i-1];

System.out.println("Max profit (multiple) = " + profit);

Program 233: Longest Consecutive Sequence

import java.util.HashSet;

public class Program233 {

public static void main(String[] args) {

int[] arr = {100,4,200,1,3,2};

HashSet<Integer> set = new HashSet<>();

for(int v:arr) set.add(v);

int longest=0;

for(int v:set){

if(!set.contains(v-1)){

int len=1;

while(set.contains(v+len)) len++;

longest=Math.max(longest,len);

}
}

System.out.println("Longest consecutive length = "+longest);

Program 234: Find peak element

public class Program234 {

public static void main(String[] args) {

int[] arr = {1,2,1,3,5,6,4};

int l=0,r=arr.length-1;

while(l<r){

int m=(l+r)/2;

if(arr[m]<arr[m+1]) l=m+1; else r=m;

System.out.println("Peak element index = " + l);

Program 235: Minimum difference between elements of array

import java.util.Arrays;

public class Program235 {

public static void main(String[] args) {

int[] arr = {1,5,3,19,18,25};

Arrays.sort(arr);

int min=Integer.MAX_VALUE;

for(int i=1;i<arr.length;i++) min=Math.min(min,arr[i]-arr[i-1]);

System.out.println("Min difference = "+min);

}
}

Program 236: Search in rotated sorted array

public class Program236 {

public static void main(String[] args) {

int[] arr = {4,5,6,7,0,1,2};

int target=0,l=0,r=arr.length-1;

while(l<=r){

int m=(l+r)/2;

if(arr[m]==target){System.out.println("Found at "+m);return;}

if(arr[l]<=arr[m]){

if(target>=arr[l] && target<arr[m]) r=m-1; else l=m+1;

}else{

if(target>arr[m] && target<=arr[r]) l=m+1; else r=m-1;

System.out.println("Not found");

Program 237: Median of two sorted arrays (merge method)

public class Program237 {

public static void main(String[] args) {

int[] a={1,3},b={2};

int m=a.length,n=b.length;

int[] merged=new int[m+n]; int i=0,j=0,k=0;

while(i<m&&j<n) merged[k++]=a[i]<b[j]?a[i++]:b[j++];

while(i<m) merged[k++]=a[i++];
while(j<n) merged[k++]=b[j++];

double median=(merged.length%2==0)?(merged[merged.length/2-
1]+merged[merged.length/2])/2.0:merged[merged.length/2];

System.out.println("Median = "+median);

Program 238: Rotate array right by k

import java.util.Arrays;

public class Program238 {

static void reverse(int[] arr,int l,int r){

while(l<r){int t=arr[l];arr[l++]=arr[r];arr[r--]=t;}

public static void main(String[] args) {

int[] arr={1,2,3,4,5,6,7}; int k=3,n=arr.length;

k%=n;

reverse(arr,0,n-1); reverse(arr,0,k-1); reverse(arr,k,n-1);

System.out.println("Rotated: "+Arrays.toString(arr));

Program 239: Subarray with given sum (sliding window)

public class Program239 {

public static void main(String[] args) {

int[] arr={1,4,20,3,10,5}; int sum=33;

int curr=arr[0],start=0;

for(int i=1;i<=arr.length;i++){

while(curr>sum && start<i-1) curr-=arr[start++];


if(curr==sum){System.out.println("Found between "+start+" and "+(i-1));return;}

if(i<arr.length) curr+=arr[i];

System.out.println("No subarray found");

Program 240: Find duplicates in O(n) with extra space

import java.util.HashSet;

public class Program240 {

public static void main(String[] args) {

int[] arr={1,2,3,1,3,6,6};

HashSet<Integer> seen=new HashSet<>();

for(int v:arr){

if(seen.contains(v)) System.out.println("Duplicate: "+v);

else seen.add(v);

You might also like