Coding Techniques
Arrays in Java · Study material
Classic array algorithms
Two-pointer reversal, rotation with three reversals (O(n) time, O(1) space) and Kadane's maximum-subarray algorithm are three of the most frequently asked array techniques.
import java.util.Arrays;
public class Main {
static void reverse(int[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}
static void rotateLeft(int[] a, int k) { // reversal algorithm: O(n) time, O(1) extra space
int n = a.length;
k %= n;
reverseRange(a, 0, k - 1);
reverseRange(a, k, n - 1);
reverseRange(a, 0, n - 1);
}
static void reverseRange(int[] a, int i, int j) {
for (; i < j; i++, j--) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}
static int maxSubarray(int[] a) { // Kadane's algorithm
int best = a[0], current = a[0];
for (int i = 1; i < a.length; i++) {
current = Math.max(a[i], current + a[i]);
best = Math.max(best, current);
}
return best;
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6, 7};
reverse(a);
System.out.println(Arrays.toString(a));
int[] b = {1, 2, 3, 4, 5, 6, 7};
rotateLeft(b, 3);
System.out.println(Arrays.toString(b));
System.out.println(maxSubarray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
}
}
[7, 6, 5, 4, 3, 2, 1] [4, 5, 6, 7, 1, 2, 3] 6
Copying arrays the right way
int[] src = {1, 2, 3, 4, 5};
int[] alias = src; // ✘ not a copy – same array
int[] a = src.clone(); // ✔ full copy
int[] b = Arrays.copyOf(src, 8); // ✔ copy and resize (pads with 0)
int[] c = Arrays.copyOfRange(src, 1, 4); // ✔ part: [2, 3, 4]
int[] d = new int[5];
System.arraycopy(src, 0, d, 0, src.length); // ✔ fastest, copies into an existing array
int[][] grid = {{1, 2}, {3, 4}};
int[][] shallow = grid.clone(); // ✘ rows are shared!
int[][] deep = new int[grid.length][];
for (int i = 0; i < grid.length; i++) deep[i] = grid[i].clone(); // ✔ deep copy Frequency counting with an array
// Counting values in a small known range: an int array beats a HashMap
int[] marks = {7, 3, 7, 9, 3, 7, 1};
int[] count = new int[11]; // marks are 0..10
for (int m : marks) count[m]++;
// count[7] == 3, count[3] == 2
// Counting letters
int[] letters = new int[26];
for (char ch : "banana".toCharArray()) letters[ch - 'a']++;
// letters['a' - 'a'] == 3, letters['n' - 'a'] == 2 Array checklist
- Loop with i < a.length.
- Use for-each when you do not need the index.
- Print with Arrays.toString / deepToString.
- Copy explicitly; deep-copy nested arrays.
- Compare with Arrays.equals / deepEquals.
- Sort before binarySearch.
- Prefer ArrayList when the size changes.
- Check for empty arrays before reading a[0].