Java Arrays: From Zero to Pro
A compact, practical guide to mastering array programming in Java — with patterns, snippets, and
practice tasks.
1) Array Basics
Declaration
int[] a; // preferred
int a[]; // also valid
Allocation
a = new int[5]; // default 0s
String[] names = new String[3]; // default nulls
Initialization (literal)
int[] nums = {1, 2, 3, 4};
String[] fruits = {"apple", "banana"};
Length
int n = [Link];
Access
int x = nums[0]; // first
int y = nums[n-1]; // last
For-each loop
for (int v : nums) {
[Link](v);
}
1
2) I/O Utilities (Console)
import [Link].*;
public class IOArrays {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = [Link]();
[Link]([Link](a));
}
}
3) Core Operations (Reusable Methods)
import [Link].*;
class ArrayOps {
// 3.1 clone/copy
static int[] copy(int[] a) { return [Link](a, [Link]); }
static int[] copyRange(int[] a, int l, int r) { return
[Link](a, l, r); }
// 3.2 reverse in-place
static void reverse(int[] a) {
for (int i = 0, j = [Link] - 1; i < j; i++, j--) {
int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
}
// 3.3 rotate (right by k)
static void rotateRight(int[] a, int k) {
int n = [Link]; k %= n;
reverseRange(a, 0, n - 1);
reverseRange(a, 0, k - 1);
reverseRange(a, k, n - 1);
}
static void reverseRange(int[] a, int l, int r) {
while (l < r) { int t = a[l]; a[l++] = a[r]; a[r--] = t; }
}
// 3.4 find min/max + index
static int min(int[] a) { int m = a[0]; for (int v : a) m = [Link](m,
v); return m; }
static int max(int[] a) { int m = a[0]; for (int v : a) m = [Link](m,
v); return m; }
2
static int indexOf(int[] a, int target) { for (int i = 0; i < [Link];
i++) if (a[i]==target) return i; return -1; }
// 3.5 count / frequency
static Map<Integer,Integer> freq(int[] a) {
Map<Integer,Integer> f = new HashMap<>();
for (int v : a) [Link](v, [Link](v, 0) + 1);
return f;
}
// 3.6 remove duplicates (keeping order)
static int[] uniqueStable(int[] a) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
for (int v : a) [Link](v);
int[] out = new int[[Link]()];
int i = 0; for (int v : set) out[i++] = v;
return out;
}
// 3.7 merge two sorted arrays
static int[] mergeSorted(int[] A, int[] B) {
int i=0, j=0, n=[Link], m=[Link];
int[] C = new int[n+m];
int k=0;
while (i<n && j<m) C[k++] = (A[i] <= B[j]) ? A[i++] : B[j++];
while (i<n) C[k++] = A[i++];
while (j<m) C[k++] = B[j++];
return C;
}
}
4) Algorithm Patterns on Arrays
4.1 Two Pointers
• When: sorted arrays, or when moving from both ends.
• Use cases: pair sum, remove duplicates in-place, partitioning.
// Is there a pair with sum = target? (sorted array)
static boolean twoSumSorted(int[] a, int target) {
int i = 0, j = [Link] - 1;
while (i < j) {
int s = a[i] + a[j];
if (s == target) return true;
if (s < target) i++; else j--;
}
return false;
}
3
4.2 Sliding Window
• When: subarray with constraints (sum/length/distinct chars), contiguous only.
// Max sum of any subarray of size k
static int maxSumWindow(int[] a, int k) {
int n = [Link], sum = 0, best = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
sum += a[i];
if (i >= k) sum -= a[i-k];
if (i >= k-1) best = [Link](best, sum);
}
return best;
}
4.3 Prefix Sum
• When: many range-sum queries, difference arrays, subarray sums.
// Prefix sums and range sum [l, r]
static int[] prefix(int[] a) {
int n = [Link]; int[] p = new int[n+1];
for (int i = 0; i < n; i++) p[i+1] = p[i] + a[i];
return p;
}
static int rangeSum(int[] p, int l, int r) { // inclusive l..r
return p[r+1] - p[l];
}
4.4 Kadane (Max Subarray Sum)
static int kadane(int[] a) {
int best = a[0], cur = a[0];
for (int i = 1; i < [Link]; i++) {
cur = [Link](a[i], cur + a[i]);
best = [Link](best, cur);
}
return best;
}
4.5 Binary Search (on values)
• When: monotonic predicate over an answer range (e.g., capacity, days, speed).
static int binarySearchFirstTrue(int lo, int hi,
[Link] ok) {
// finds the smallest x in [lo, hi] s.t. ok(x) is true
while (lo < hi) {
4
int mid = lo + (hi - lo) / 2;
if ([Link](mid)) hi = mid; else lo = mid + 1;
}
return lo;
}
4.6 Sorting
[Link](a); // primitive ascending
[Link](objs, comparator); // custom
4.7 Hashing (Counts/Indices)
Map<Integer,Integer> last = new HashMap<>();
for (int i = 0; i < [Link]; i++) [Link](a[i], i);
5) 2D Arrays (Matrices)
Create & Traverse
int[][] m = new int[3][4];
for (int i = 0; i < [Link]; i++)
for (int j = 0; j < m[0].length; j++)
m[i][j] = i + j;
Row/Column sums
static int rowSum(int[][] g, int r) { int s=0; for (int v: g[r]) s += v;
return s; }
static int colSum(int[][] g, int c) { int s=0; for (int i=0;i<[Link];i++)
s+=g[i][c]; return s; }
Transpose (square)
static void transposeInPlace(int[][] a) {
int n = [Link];
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
int t = a[i][j]; a[i][j] = a[j][i]; a[j][i] = t;
}
}
}
5
Spiral order (print)
static [Link]<Integer> spiral(int[][] g) {
int top=0, bottom=[Link]-1, left=0, right=g[0].length-1;
[Link]<Integer> out = new [Link]<>();
while (top<=bottom && left<=right) {
for (int j=left;j<=right;j++) [Link](g[top][j]); top++;
for (int i=top;i<=bottom;i++) [Link](g[i][right]); right--;
if (top<=bottom) { for (int j=right;j>=left;j--) [Link](g[bottom]
[j]); bottom--; }
if (left<=right) { for (int i=bottom;i>=top;i--) [Link](g[i]
[left]); left++; }
}
return out;
}
6) 20 Common Interview-Style Array Tasks (with templates)
1. Reverse an array – use reverse above.
2. Rotate array by k – use rotateRight above.
3. Find second largest
static int secondLargest(int[] a) {
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int v : a) {
if (v > max) { second = max; max = v; }
else if (v > second && v != max) second = v;
}
return second;
}
4. Check if array is sorted
static boolean isSorted(int[] a) {
for (int i = 1; i < [Link]; i++) if (a[i] < a[i-1]) return false;
return true;
}
5. Remove duplicates in sorted array (in-place, return new length)
static int dedupSorted(int[] a) {
if ([Link]==0) return 0;
int k=1;
for (int i=1;i<[Link];i++) if (a[i]!=a[i-1]) a[k++]=a[i];
6
return k;
}
6. Binary search
static int binarySearch(int[] a, int target) {
int l=0, r=[Link]-1;
while (l<=r) {
int m=l+(r-l)/2;
if (a[m]==target) return m;
if (a[m]<target) l=m+1; else r=m-1;
}
return -1;
}
7. Two-sum (unsorted)
static int[] twoSum(int[] a, int target) {
Map<Integer,Integer> pos = new HashMap<>();
for (int i=0;i<[Link];i++) {
int need = target - a[i];
if ([Link](need)) return new int[]{[Link](need), i};
[Link](a[i], i);
}
return new int[]{-1,-1};
}
8. Max subarray sum – use Kadane.
9. Longest equal 0/1 subarray (binary array)
static int longestZeroOne(int[] a) {
Map<Integer,Integer> first = new HashMap<>();
int pref=0, best=0; [Link](0, -1);
for (int i=0;i<[Link];i++) {
pref += (a[i]==1?1:-1);
if ([Link](pref)) best = [Link](best, i -
[Link](pref));
else [Link](pref, i);
}
return best;
}
10. Subarray sum equals k (count)
static int subarraySumCount(int[] a, int k) {
Map<Integer,Integer> cnt = new HashMap<>();
[Link](0,1);
int pref=0, ans=0;
7
for (int v : a) {
pref += v;
ans += [Link](pref - k, 0);
[Link](pref, [Link](pref, 0) + 1);
}
return ans;
}
11. Sort 0/1/2 (Dutch flag)
static void sort012(int[] a) {
int l=0, i=0, r=[Link]-1;
while (i<=r) {
if (a[i]==0) { int t=a[l]; a[l]=a[i]; a[i]=t; l++; i++; }
else if (a[i]==2) { int t=a[r]; a[r]=a[i]; a[i]=t; r--; }
else i++;
}
}
12. Product of array except self (no division)
static int[] productExceptSelf(int[] a) {
int n=[Link]; int[] L=new int[n], R=new int[n], ans=new int[n];
L[0]=1; for(int i=1;i<n;i++) L[i]=L[i-1]*a[i-1];
R[n-1]=1; for(int i=n-2;i>=0;i--) R[i]=R[i+1]*a[i+1];
for(int i=0;i<n;i++) ans[i]=L[i]*R[i];
return ans;
}
13. Intervals merge (if you model with 2D array int[][] )
static int[][] mergeIntervals(int[][] iv) {
[Link](iv, (x,y)->[Link](x[0], y[0]));
[Link]<int[]> res = new [Link]<>();
int[] cur = iv[0].clone();
for (int i=1;i<[Link];i++) {
if (iv[i][0] <= cur[1]) cur[1] = [Link](cur[1], iv[i][1]);
else { [Link](cur); cur = iv[i].clone(); }
}
[Link](cur);
return [Link](new int[0][]);
}
14. Missing number in 0..n (XOR)
static int missingNumber(int[] a) {
int n=[Link], x=n;
for (int i=0;i<n;i++) x ^= i ^ a[i];
8
return x;
}
15. Find duplicates (1..n) using sign marking
static [Link]<Integer> findDups(int[] a) {
[Link]<Integer> res = new [Link]<>();
for (int i=0;i<[Link];i++) {
int idx = [Link](a[i])-1;
if (a[idx] < 0) [Link](idx+1);
else a[idx] = -a[idx];
}
return res;
}
16. Kth largest (min-heap)
static int kthLargest(int[] a, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int v : a) { [Link](v); if ([Link]()>k) [Link](); }
return [Link]();
}
17. Top-K frequent
static int[] topKFrequent(int[] a, int k) {
Map<Integer,Integer> f = new HashMap<>();
for (int v: a) [Link](v, [Link](v,0)+1);
PriorityQueue<int[]> pq = new PriorityQueue<>((x,y)->x[1]-y[1]);
for (var e: [Link]()) { [Link](new int[]{[Link](),
[Link]()}); if ([Link]()>k) [Link](); }
int[] out = new int[[Link]()]; int i=0;
while(![Link]()) out[i++]=[Link]()[0];
return out;
}
18. Binary search in rotated sorted array
static int searchRotated(int[] a, int target) {
int l=0, r=[Link]-1;
while (l<=r) {
int m=l+(r-l)/2;
if (a[m]==target) return m;
if (a[l] <= a[m]) { // left sorted
if (a[l] <= target && target < a[m]) r=m-1; else l=m+1;
} else { // right sorted
if (a[m] < target && target <= a[r]) l=m+1; else r=m-1;
}
9
}
return -1;
}
19. Set matrix zeros (2D patterning)
static void setZeroes(int[][] g) {
int m=[Link], n=g[0].length;
boolean row0=false, col0=false;
for (int j=0;j<n;j++) if (g[0][j]==0) row0=true;
for (int i=0;i<m;i++) if (g[i][0]==0) col0=true;
for (int i=1;i<m;i++) for (int j=1;j<n;j++) if (g[i][j]==0) { g[i]
[0]=0; g[0][j]=0; }
for (int i=1;i<m;i++) if (g[i][0]==0) for (int j=1;j<n;j++) g[i]
[j]=0;
for (int j=1;j<n;j++) if (g[0][j]==0) for (int i=1;i<m;i++) g[i]
[j]=0;
if (row0) for (int j=0;j<n;j++) g[0][j]=0;
if (col0) for (int i=0;i<m;i++) g[i][0]=0;
}
20. Spiral matrix – see section 5.
7) Time & Space Complexity Cheats
• Traversal: O(n) time, O(1) extra space
• Two Pointers: O(n), O(1)
• Sliding Window: O(n), O(1)
• Prefix/HMap: O(n), O(n)
• Sorting: O(n log n), O(1)–O(n) depending on algo
• Binary Search: O(log n), O(1)
• Heaps: building O(n), each op O(log n)
8) Practice Ladder (do in order)
Level 0 – Warm-up - Print, sum, average, min/max, reverse, is-sorted.
Level 1 – Fundamentals - Rotate by k, second largest, count frequency, binary search, dedup sorted,
two-sum.
Level 2 – Windows & Prefix - Max sum window (fixed k), longest subarray with sum k (non-negatives),
subarray sum equals k (hash), Kadane.
Level 3 – Sorting & Heaps - Sort 0/1/2, kth largest, top-K frequent.
10
Level 4 – Mixed - Product except self, search in rotated array, merge intervals, missing number, find
duplicates.
Level 5 – 2D Arrays - Row/column sums, transpose, set matrix zeros, spiral order.
9) Tips & Pitfalls
• Use [Link](a) and [Link](m) for quick debug.
• Watch off-by-one errors on indices and ranges [l, r] vs [l, r) .
• Prefer immutable returns or document side-effects for in-place ops.
• For big inputs, avoid O(n^2) unless constraints allow it.
• For interview-style problems, state the approach, complexity, and edge cases first (empty arrays,
single element, negatives, duplicates).
10) Mini Template for Any Array Problem
1) Clarify input constraints: n range? values? sorted? distinct? multiple
queries?
2) Choose pattern: traverse | two pointers | window | prefix | hash | sort |
heap | BS on answer | DP | math.
3) Write tests: empty, size 1, typical, extremes, duplicates.
4) Implement + analyze complexity + edge cases.
If you want, we can turn any section into a full set of worked examples with unit tests (JUnit) or
practice sheets with solutions.
11