Array Programs

Naveen AnamaneniUpdated · 5 min read

These are the array programs that show up again and again in college labs, coding tests and fresher interviews. Each uses only what this chapter has taught. Try each one before reading the solution; the habit of working out indexes on paper is what the exercises are really for.

Minimum, Maximum, Sum and Average

Stats.java▶ Try it
public class Stats {
    public static void main(String[] args) {
        int[] temps = {31, 34, 29, 36, 33, 30, 35};
        int min = temps[0], max = temps[0], sum = 0;
        for (int t : temps) {
            if (t < min) min = t;
            if (t > max) max = t;
            sum += t;
        }
        double avg = (double) sum / temps.length;
        System.out.printf("Min %d, max %d, average %.1f%n", min, max, avg);
    }
}
Output
Min 29, max 36, average 32.6

Start min and max from the first element, not from 0, so the program also works for negative numbers.

Search.java▶ Try it
public class Search {
    public static void main(String[] args) {
        int[] pnrs = {4471, 4398, 4512, 4600, 4512};
        int wanted = 4512, count = 0, first = -1;
        for (int i = 0; i < pnrs.length; i++) {
            if (pnrs[i] == wanted) {
                count++;
                if (first == -1) {
                    first = i;
                }
            }
        }
        System.out.printf("%d found %d times, first at index %d%n",
                wanted, count, first);
    }
}
Output
4512 found 2 times, first at index 2

Remove Duplicates from a Sorted Array

In a sorted array, duplicates sit next to each other, so one pass is enough:

Unique.java▶ Try it
import java.util.Arrays;
 
public class Unique {
    public static void main(String[] args) {
        int[] a = {1, 1, 2, 3, 3, 3, 4};
        int k = 1;
        for (int i = 1; i < a.length; i++) {
            if (a[i] != a[k - 1]) {
                a[k++] = a[i];
            }
        }
        System.out.println(Arrays.toString(Arrays.copyOf(a, k)));
    }
}
Output
[1, 2, 3, 4]

k counts the unique values written so far at the front of the array. Each new value different from the last unique one is moved forward. a[k++] = a[i] stores at k, then adds 1 to k.

Merge Two Sorted Arrays

Merge.java▶ Try it
import java.util.Arrays;
 
public class Merge {
    public static void main(String[] args) {
        int[] x = {1, 4, 9}, y = {2, 3, 10, 12};
        int[] m = new int[x.length + y.length];
        int i = 0, j = 0, k = 0;
        while (i < x.length && j < y.length) {
            m[k++] = x[i] <= y[j] ? x[i++] : y[j++];
        }
        while (i < x.length) m[k++] = x[i++];
        while (j < y.length) m[k++] = y[j++];
        System.out.println(Arrays.toString(m));
    }
}
Output
[1, 2, 3, 4, 9, 10, 12]

Two pointers walk the two arrays, always taking the smaller front value; the last two loops copy whatever is left. This is the heart of merge sort, which the algorithms lessons build later.

Matrix Addition and Transpose

Matrix.java▶ Try it
import java.util.Arrays;
 
public class Matrix {
    public static void main(String[] args) {
        int[][] a = {{1, 2}, {3, 4}}, b = {{5, 6}, {7, 8}};
        int[][] sum = new int[2][2], t = new int[2][2];
        for (int r = 0; r < 2; r++) {
            for (int c = 0; c < 2; c++) {
                sum[r][c] = a[r][c] + b[r][c];
                t[c][r] = a[r][c];
            }
        }
        System.out.println("Sum: " + Arrays.deepToString(sum));
        System.out.println("Transpose of a: " + Arrays.deepToString(t));
    }
}
Output
Sum: [[6, 8], [10, 12]]
Transpose of a: [[1, 3], [2, 4]]

Addition adds matching cells; the transpose swaps rows and columns, so a[r][c] goes to t[c][r].

Interview Corner

How do you find the second-largest element in an array in one pass?

Keep two variables, largest and second, starting from the lowest possible value. For each element, if it's bigger than largest, move largest into second and store the element in largest; otherwise, if it's bigger than second and not equal to largest, store it in second.

Practice

  1. Easy: Count the even and odd numbers in an array.
  2. Harder: Find the missing number in an array containing every number from 1 to 10 except one. Hint: compare the expected sum, n * (n + 1) / 2, with the actual sum.
  3. Harder: Rotate an array left by k positions.

Quick check: Array programs

4 questions
1Why start min from temps[0] instead of 0?
2Why does removing duplicates in one pass need a sorted array?
3In matrix transpose, where does a[r][c] go?
4What does a[k++] = x; do?

Key Takeaways

Was this tutorial helpful?

Lesson 80 of 482