Advertisement
Home Data Structure Arrays Sum of First and Last Element in an Array

Sum of First and Last Element in an Array

0
Advertisement

Title: Sum of First and Last Element in an Array

In this guide, you’ll learn how to compute the sum of the first and last elements of an integer array in Java. It is one of the first problems a beginner meets when learning arrays, and it is a surprisingly good lens on index arithmetic, boundary conditions, and defensive programming.

We’ll walk through the problem statement, build a clean algorithm, write a full compilable Java program, trace it on a concrete input, work through a few examples, and finish with the common mistakes, edge cases, and interview follow-ups that make this problem a reliable warm-up question.

Understanding the Problem

Given an integer array arr of length n, return the sum of its first element and its last element, that is arr[0] + arr[n - 1]. The problem looks trivial, and in terms of raw code it is, but the interesting part is what happens at the edges: an empty array has no first element, a single-element array makes the first and the last the same element, and a very large array can push the sum beyond Integer.MAX_VALUE.

Our contract is simple: for any valid input the method returns an int equal to arr[0] + arr[arr.length - 1]. For invalid input (null or empty) we throw IllegalArgumentException so the caller cannot silently propagate a sentinel value.

Approach

Because arrays in Java support constant-time random access, we never need to iterate. We read the two endpoint values directly and add them.

  1. Validate the input: reject null and reject an empty array.
  2. Read the first element with arr[0].
  3. Compute the last index as arr.length - 1.
  4. Read the last element with arr[arr.length - 1].
  5. Return the sum of the two values.

Step 3 is the one place where a beginner slips: writing arr.length instead of arr.length - 1 throws ArrayIndexOutOfBoundsException at runtime.

Java Program

Java
public class SumFirstLast {
    public static int sumFirstAndLast(int[] arr) {
        if (arr == null || arr.length == 0) {
            throw new IllegalArgumentException("Array must not be null or empty");
        }
        int first = arr[0];
        int last = arr[arr.length - 1];
        return first + last;
    }

    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        int result = sumFirstAndLast(numbers);
        System.out.println("First + Last = " + result);
    }
}

Explanation of the Program

The sumFirstAndLast method is the core of the program. It accepts an int[] parameter named arr and returns an int. Before doing any work it guards against bad input: if arr is null or has zero length, it throws IllegalArgumentException. Failing loudly here is better than returning 0 or Integer.MIN_VALUE, because callers would otherwise have no way to tell a legitimate zero sum from an error.

Once validation passes, the method reads arr[0] into first, computes the last index as arr.length - 1, reads that slot into last, and returns first + last. Each array access is O(1) because Java arrays are backed by a contiguous block of memory and support constant-time random access.

The main method is a small driver: it builds the array {10, 20, 30, 40, 50}, calls sumFirstAndLast, and prints the result. For this input the output is First + Last = 60, which is 10 + 50.

Step-by-Step Trace

Let’s run the algorithm on the input {7, 2, 9, 4, 11, 3, 8}. The expected return value is 7 + 8 = 15.

StepOperationfirstlastReturn
1Validate arr (length 7, not null)–––
2first = arr[0]7––
3lastIndex = arr.length – 1 = 67––
4last = arr[6]78–
5return first + last7815

The invariant is small but worth stating: after step 4, first holds arr[0] and last holds arr[arr.length - 1], so step 5 can commit to the final answer without re-reading the array.

Examples

Example 1: Positive Integers

Pass a five-element array of positive integers. The method reads 10 and 50 and returns 60.

Java
int[] arr = {10, 20, 30, 40, 50};
int result = sumFirstAndLast(arr);
// Output: First + Last = 60

Example 2: Mixed Positive and Negative Values

When the endpoints have opposite signs, the sum can be negative. Here -5 + (-10) = -15.

Java
int[] arr = {-5, 0, 15, 25, -10};
int result = sumFirstAndLast(arr);
// Output: First + Last = -15

Example 3: Single-Element Array

When the array has only one element, the first and the last are the same slot. The method still reads arr[0] twice and returns twice that value.

Java
int[] arr = {100};
int result = sumFirstAndLast(arr);
// Output: First + Last = 200

If your specification treats a single-element array as having only a first element and no distinct last element, you would return arr[0] once. The requirements document should make this choice explicit before you code.

Common Mistakes to Avoid

The algorithm is short, so most bugs here come from index arithmetic and from under-specified input handling. Watch out for the following.

  • Using arr.length as the last index – writing arr[arr.length] throws ArrayIndexOutOfBoundsException because valid indices run from 0 to arr.length - 1. Subtract one to get the last valid index.
  • Hard-coding the last index – writing arr[4] or similar works for one specific test input and silently returns the wrong value for every other length. Always derive the last index from arr.length - 1.
  • Returning zero for an empty array – callers cannot distinguish this zero from a legitimate sum of zero, so bugs propagate downstream. Throw IllegalArgumentException so the error surfaces at the call site.
  • Ignoring integer overflow – when both endpoints are near Integer.MAX_VALUE, the sum silently wraps into a large negative number. Promote the computation to long or use Math.addExact if correctness matters.

Edge Cases to Test

Walk through this checklist before you declare the method done. Each item is an input shape, not a scenario.

  • Null array reference
  • Empty array
  • Single-element array
  • Two-element array
  • All negative elements
  • Both endpoints at Integer.MAX_VALUE (overflow)
  • Both endpoints at Integer.MIN_VALUE (underflow)
  • Array of all zeros

Additional Considerations

The time complexity is O(1). We perform a constant number of operations: two bounds checks, two array reads, and one addition. The size of the array does not affect the running time.

The space complexity is also O(1). We allocate two local int variables, first and last, and return a single int. No auxiliary data structure is used, and the input array is never copied or mutated.

The overflow case deserves a second look. If arr[0] is 2_000_000_000 and arr[arr.length - 1] is 1_500_000_000, the mathematical sum is 3_500_000_000, which exceeds Integer.MAX_VALUE (about 2.147 billion). Java’s int addition wraps around, so the method silently returns a negative value. Replacing the return expression with Math.addExact(first, last) turns the silent wrap into a loud ArithmeticException, which is the right behavior for most real-world systems.

Interview Follow-up Questions

In a real interview, the base question is only the opening. Interviewers probe depth with variations like these.

  • How would you handle potential overflow? – widen the computation to long, or use Math.addExact to fail fast when the result would overflow int.
  • What if the input is a singly linked list instead of an array? – reaching the last node is O(n) because you must traverse from the head; a doubly linked list with a tail pointer restores O(1) access.
  • What if the array is streamed and the length is unknown? – capture the first element on the opening read and maintain a one-slot buffer for the running last; emit their sum when the stream closes.
  • What if you need the sum of the first K and last K elements? – keep two running sums with two pointers, guarding against the case where K exceeds half the array length so you don’t double-count the middle.
  • What if the input is a 2D matrix and you need the sum of its four corners? – index into m[0][0], m[0][n-1], m[rows-1][0], and m[rows-1][n-1]; still O(1), but you now need two independent empty-dimension checks.

Conclusion

Summing the first and last elements of an array is a one-line computation wrapped in two important habits: validate the input before you touch it, and derive the last index from arr.length - 1 rather than guessing. Once those two habits are automatic, the algorithm itself is just two reads and an addition.

Try adapting the code to also report the difference, the average, or the product of the two endpoints, and run it against the edge cases above to see how your version behaves on empty, single-element, and overflow inputs. You can learn more about similar problems in our Arrays category: Arrays.