Array Fundamentals

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/150 Known filtered set
Difficulty
Read Full Guide Question: 1 of 150

Java Logic Development · Chapter 09 Companion Article

Array Fundamentals

Fifteen foundational array problems — reading, printing, summing, ranking, copying, reversing, and comparing — each built around a single traversal and the state it needs to carry.

Overview

Java arrays store multiple values of the same data type under one variable name. Each value is accessed through an index.

Important array fundamentals:

  • Array indexing starts from 0.
  • The last valid index is array.length - 1.
  • Array size is fixed after creation.
  • All elements must have compatible data types.
  • Primitive arrays receive default values such as 0, 0.0, false, or ''.
  • Object arrays initially contain null.
  • Accessing an invalid index causes ArrayIndexOutOfBoundsException.
  • Most basic array problems use a single traversal, giving O(n) time complexity.

Example: int[] numbers = {10, 20, 30, 40};

Index mapping:

IndexValue
010
120
230
340

numbers.length is 4, while the last valid index is 3.

1. Read Array Elements

Problem

Read multiple integer values from the user and store them in an array.

Core Idea

Create an array of the required size and use the loop index as the storage position. For an array of size 5: first input goes to numbers[0], second input goes to numbers[1], continue until numbers[4].

If the number of inputs is known only at runtime, read the size first and then create the array.

Logic

  1. Read the required array size.
  2. Create an integer array with that size.
  3. Run a loop from 0 to size - 1.
  4. Read one number during every iteration.
  5. Store it at the current index.

Java Program

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter array size: ");
        int size = scanner.nextInt();
        int[] numbers = new int[size];

        System.out.println("Enter " + size + " elements:");
        for (int i = 0; i < size; i++) {
            numbers[i] = scanner.nextInt();
        }

        System.out.println("Array elements stored successfully.");
        scanner.close();
    }
}

Input

Input
5
12 25 8 41 19

Output

Output
Enter array size: Enter 5 elements:
Array elements stored successfully.

Dry Run

iInputStored At
012numbers[0]
125numbers[1]
28numbers[2]
341numbers[3]
419numbers[4]

Final array: [12, 25, 8, 41, 19]

Complexity

  • Time: O(n)
  • Space: O(n) for storing n elements.

Relevant Edge Case

A negative array size is invalid and causes NegativeArraySizeException.

Common Mistake

Writing i <= size instead of i < size. The last iteration would try to access an index outside the array.

Interview Tip

Be comfortable reading both fixed-size arrays and arrays whose size is entered at runtime.

2. Print Array Elements

Problem

Display every value stored in an array.

Core Idea

Traverse the array from the first index to the last and print each element.

When the index itself is not needed, an enhanced for loop gives cleaner code.

Logic

  1. Start with the first element.
  2. Read its value.
  3. Print it.
  4. Repeat for every remaining element.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {12, 25, 8, 41, 19};

        System.out.print("Array elements: ");
        for (int number : numbers) {
            System.out.print(number + " ");
        }
    }
}

Output

Output
Array elements: 12 25 8 41 19

Dry Run

The enhanced loop assigns each value to number:

Text
number = 12
number = 25
number = 8
number = 41
number = 19

Each value is printed once.

Why It Works

An enhanced for loop automatically visits every element from beginning to end without manually managing an index.

Complexity

  • Time: O(n)
  • Space: O(1)

When to Use a Normal for Loop

Use index-based traversal when you need the position of an element or want to modify array values.

Common Mistake

Trying to access numbers[numbers.length]. The final valid position is numbers.length - 1.

Interview Tip

Know the difference between index-based for, enhanced for, and Arrays.toString().

3. Sum of Array Elements

Problem

Calculate the total of all values in an integer array. Example: [10, 20, 30, 40], sum 10 + 20 + 30 + 40 = 100.

Maintain one accumulator variable and update it while traversing the array.

Logic

  1. Initialize sum to 0.
  2. Visit every element.
  3. Add the current value to sum.
  4. After traversal, sum contains the total.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 25, 15, 30, 20};
        int sum = 0;

        for (int number : numbers) {
            sum += number;
        }

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

Output

Output
Sum = 100

Dry Run

ElementPrevious SumNew Sum
10010
251035
153550
305080
2080100

Why It Works

Every array value contributes exactly once to the accumulator.

Complexity

  • Time: O(n)
  • Space: O(1)

Important Consideration

For very large integer values, an int sum may overflow. Use long when the possible total can exceed the int range.

Common Mistake

Resetting sum inside the loop. Incorrect idea:

Java
for (int number : numbers) {
    int sum = 0;
}

The accumulator must exist outside the loop so it retains the previous total.

Interview Tip

Summation is the foundation of many later problems such as averages, prefix sums, subarray sums, and cumulative statistics.

4. Average of Array Elements

Problem

Find the arithmetic mean of all array elements. Formula: Average = Sum of Elements / Number of Elements. For [10, 20, 30, 40], average is 100 / 4 = 25.0.

Use floating-point division. Integer division can remove the decimal part.

Logic

  1. Calculate the total sum.
  2. Divide it by the number of elements.
  3. Convert one side of the division to double.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {15, 22, 31, 18, 24};
        int sum = 0;

        for (int number : numbers) {
            sum += number;
        }

        double average = (double) sum / numbers.length;
        System.out.println("Average = " + average);
    }
}

Output

Output
Average = 22.0

Dry Run

Sum: 15 + 22 + 31 + 18 + 24 = 110. Length: 5. Calculation: 110.0 / 5 = 22.0.

Why the Cast Matters

Without the cast:

Java
int sum = 7;
int length = 2;
double average = sum / length;

sum / length performs integer division first: 7 / 2 = 3. The resulting double becomes 3.0, not 3.5. Using (double) sum / length produces the expected decimal result.

Complexity

  • Time: O(n)
  • Space: O(1)

Edge Case

An empty array has no mathematical average. Dividing by its length should therefore be avoided.

Interview Tip

When numerical results may contain fractions, always inspect the operand types before performing division.

5. Maximum Element

Problem

Find the largest value present in an array. Example: [14, 52, 7, 31, 26], maximum 52.

Instead of starting with 0, initialize the maximum with the first array element.

Logic

  1. Assume the first element is the maximum.
  2. Compare every remaining value with the current maximum.
  3. If a larger value is found, update the maximum.
  4. Continue until the array ends.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {-12, -5, -27, -3, -19};
        int max = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }

        System.out.println("Maximum = " + max);
    }
}

Output

Output
Maximum = -3

Dry Run

Current ValueCurrent MaximumAction
-12-12Initial value
-5-5Update
-27-5No change
-3-3Update
-19-3No change

Why Initializing with Zero Can Fail

For an array containing only negative values, 0 would incorrectly remain larger than every actual element.

Complexity

  • Time: O(n)
  • Space: O(1)

Edge Case

The array must contain at least one element before accessing numbers[0].

Interview Tip

A maximum can be found in one traversal. Sorting the entire array only to obtain the maximum is unnecessary and costs O(n log n).

6. Minimum Element

Problem

Find the smallest element in an array.

Keep the best minimum found so far and replace it whenever a smaller value appears.

Logic

  1. Store the first value in min.
  2. Traverse from index 1.
  3. Compare each value with min.
  4. Update min whenever a smaller element is found.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {42, 17, 63, 9, 28};
        int min = numbers[0];

        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < min) {
                min = numbers[i];
            }
        }

        System.out.println("Minimum = " + min);
    }
}

Output

Output
Minimum = 9

Dry Run

Valuemin After Comparison
4242
1717
6317
99
289

Why It Works

min always represents the smallest element encountered up to the current position.

Complexity

  • Time: O(n)
  • Space: O(1)

Common Mistake

Sorting an array when only the minimum value is required.

Interview Tip

Maximum and minimum can also be found together in one traversal when both values are required.

7. Second Largest Element

Problem

Find the second-largest distinct value without sorting the array. For [20, 45, 12, 45, 31], distinct values in descending order are 45, 31, 20, 12. Therefore Second Largest = 31.

Maintain two values: the largest and second largest found so far.

Logic

  • If the current element is greater than largest: move the old largest into secondLargest, then store the current value in largest.
  • Otherwise, if the value is smaller than largest but greater than secondLargest, update only secondLargest.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {20, 45, 12, 45, 31};
        Integer largest = null;
        Integer secondLargest = null;

        for (int number : numbers) {
            if (largest == null || number > largest) {
                secondLargest = largest;
                largest = number;
            } else if (number < largest && (secondLargest == null || number > secondLargest)) {
                secondLargest = number;
            }
        }

        if (secondLargest != null) {
            System.out.println("Second largest = " + secondLargest);
        } else {
            System.out.println("No second largest distinct element.");
        }
    }
}

Output

Output
Second largest = 31

Dry Run

NumberLargestSecond Largest
2020null
454520
124520
454520
314531

Why number < largest Is Required

It prevents another occurrence of the maximum value from becoming the second-largest distinct value. For [50, 50, 40], the second-largest distinct value is 40, not 50.

Complexity

  • Time: O(n)
  • Space: O(1)

Edge Cases

  • Empty array: no result.
  • One-element array: no second largest.
  • [7, 7, 7]: no second-largest distinct value.
  • Negative values are handled correctly.

Common Mistake

Sorting first when the interviewer specifically asks for an O(n) solution.

Interview Tip

Clarify whether "second largest" means the second array position after sorting or the second distinct largest value.

8. Second Smallest Element

Problem

Find the second-smallest distinct value in one traversal. For [8, 3, 5, 3, 11], distinct sorted values are 3, 5, 8, 11, so Second Smallest = 5.

Track the smallest two distinct values while scanning the array.

Logic

  • If the current value is less than smallest: move the old smallest to secondSmallest, then replace smallest.
  • Otherwise, update secondSmallest only when the value is greater than smallest and smaller than the existing second smallest.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {8, 3, 5, 3, 11};
        Integer smallest = null;
        Integer secondSmallest = null;

        for (int number : numbers) {
            if (smallest == null || number < smallest) {
                secondSmallest = smallest;
                smallest = number;
            } else if (number > smallest && (secondSmallest == null || number < secondSmallest)) {
                secondSmallest = number;
            }
        }

        if (secondSmallest != null) {
            System.out.println("Second smallest = " + secondSmallest);
        } else {
            System.out.println("No second smallest distinct element.");
        }
    }
}

Output

Output
Second smallest = 5

Dry Run

NumberSmallestSecond Smallest
88null
338
535
335
1135

Complexity

  • Time: O(n)
  • Space: O(1)

Why This Approach Is Useful

Sorting would reorganize the whole array even though only two values are required.

Common Mistake

Not excluding duplicates of the minimum value.

Interview Tip

The second-smallest problem tests whether you can maintain multiple state variables during a single traversal.

9. Count Even Elements

Problem

Count how many elements in an array are even. A number is even when number % 2 == 0.

Test every element independently and increment the counter only when the remainder is zero.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {12, 7, 18, 21, 30, 5};
        int evenCount = 0;

        for (int number : numbers) {
            if (number % 2 == 0) {
                evenCount++;
            }
        }

        System.out.println("Even elements = " + evenCount);
    }
}

Output

Output
Even elements = 3

Dry Run

ValueEven?Count
12Yes1
7No1
18Yes2
21No2
30Yes3
5No3

Important Detail

Zero is an even number because 0 % 2 == 0. Negative values also follow the same parity rule. Examples:

Text
-8 % 2 == 0
-7 % 2 != 0

Complexity

  • Time: O(n)
  • Space: O(1)

Interview Tip

The same traversal pattern can count numbers satisfying almost any condition.

10. Count Odd Elements

Problem

Count the elements that are not divisible by 2.

Use number % 2 != 0 rather than checking only for a remainder of 1.

This matters because Java can produce a negative remainder for negative odd numbers. Example: -7 % 2 = -1. Therefore number % 2 == 1 is not a reliable general odd check.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {-7, 4, 13, -9, 20, 11};
        int oddCount = 0;

        for (int number : numbers) {
            if (number % 2 != 0) {
                oddCount++;
            }
        }

        System.out.println("Odd elements = " + oddCount);
    }
}

Output

Output
Odd elements = 4

Dry Run

ValueRemainder by 2Odd?Count
-7-1Yes1
40No1
131Yes2
-9-1Yes3
200No3
111Yes4

Complexity

  • Time: O(n)
  • Space: O(1)

Common Mistake

Using number % 2 == 1, which can fail for negative odd integers.

Interview Tip

number % 2 != 0 is the safer general-purpose condition for odd integers in Java.

11. Count Positive and Negative Elements

Problem

Count positive, negative, and zero values separately. Classification:

Text
number > 0  -> Positive
number < 0  -> Negative
number == 0 -> Zero
Zero belongs to neither the positive nor negative group.

Logic

  1. Create three counters.
  2. Traverse the array once.
  3. Use an if-else if-else chain.
  4. Increment exactly one counter for each element.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] numbers = {-8, 12, 0, -3, 17, 6, 0};
        int positiveCount = 0;
        int negativeCount = 0;
        int zeroCount = 0;

        for (int number : numbers) {
            if (number > 0) {
                positiveCount++;
            } else if (number < 0) {
                negativeCount++;
            } else {
                zeroCount++;
            }
        }

        System.out.println("Positive elements = " + positiveCount);
        System.out.println("Negative elements = " + negativeCount);
        System.out.println("Zero elements = " + zeroCount);
    }
}

Output

Output
Positive elements = 3
Negative elements = 2
Zero elements = 2

Dry Run

ValueCategory
-8Negative
12Positive
0Zero
-3Negative
17Positive
6Positive
0Zero

Final counters:

Text
Positive = 3
Negative = 2
Zero = 2

Why if-else if-else Fits Well

The three conditions are mutually exclusive. One number cannot belong to more than one category.

Complexity

  • Time: O(n)
  • Space: O(1)

Common Mistake

Treating zero as positive because it is not negative.

Interview Tip

This problem demonstrates classification during traversal. The same technique is useful for partitioning and frequency analysis.

12. Copy an Array

Problem

Create a separate array containing the same values as an existing array.

Important Distinction

This does not create an independent copy: int[] copy = original; It only copies the reference. Both variables point to the same array object.

Create a new array and copy individual elements into it.

Java Program

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] original = {10, 20, 30, 40};
        int[] copy = new int[original.length];

        for (int i = 0; i < original.length; i++) {
            copy[i] = original[i];
        }

        copy[0] = 99;

        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Copy: " + Arrays.toString(copy));
    }
}

Output

Output
Original: [10, 20, 30, 40]
Copy: [99, 20, 30, 40]

Dry Run

After copying:

Text
original = [10, 20, 30, 40]
copy     = [10, 20, 30, 40]

Then copy[0] = 99. Result:

Text
original = [10, 20, 30, 40]
copy     = [99, 20, 30, 40]

The original remains unchanged because the arrays are separate objects.

Alternative Java Approaches

int[] copy = original.clone(); or int[] copy = Arrays.copyOf(original, original.length); or System.arraycopy(original, 0, copy, 0, original.length);

Complexity

  • Time: O(n)
  • Space: O(n)

Important Reference Concept

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

Here, a and b refer to the same array. Changing b[0] = 100; also changes what is observed through a.

Interview Tip

Be ready to explain the difference between copying an array reference and copying array contents.

13. Reverse an Array

Problem

Reverse the order of array elements. Before: [10, 20, 30, 40, 50]. After: [50, 40, 30, 20, 10].

Swap elements from opposite ends and move both positions toward the center.

Logic

Start with:

Text
left = 0
right = array.length - 1

While left < right, perform swap(array[left], array[right]), then:

Text
left++
right--

Java Program

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        int left = 0;
        int right = numbers.length - 1;

        while (left < right) {
            int temp = numbers[left];
            numbers[left] = numbers[right];
            numbers[right] = temp;

            left++;
            right--;
        }

        System.out.println("Reversed array: " + Arrays.toString(numbers));
    }
}

Output

Output
Reversed array: [50, 40, 30, 20, 10]

Dry Run

Initial: [10, 20, 30, 40, 50]. First swap (index 0 <-> index 4): [50, 20, 30, 40, 10]. Second swap (index 1 <-> index 3): [50, 40, 30, 20, 10]. Now:

Text
left = 2
right = 2

The condition left < right becomes false.

Why Only Half the Array Is Processed

Every swap places two elements in their final reversed positions.

Complexity

  • Time: O(n)
  • Space: O(1) because the reversal happens in place.

Alternative Approach

Create another array and copy elements from the original in reverse order. That approach also takes O(n) time but requires O(n) additional memory.

Common Mistake

Traversing the entire array while swapping opposite elements. Doing so can reverse the array once and then reverse it back.

Interview Tip

The two-pointer technique used here appears frequently in array, string, palindrome, and partitioning problems.

14. Compare Two Arrays

Problem

Compare two arrays element by element and identify where they differ. This is different from only returning a final true or false equality result. A comparison can explain mismatched values or lengths. Example:

Text
First  = [10, 20, 30, 40]
Second = [10, 25, 30, 50]

Differences exist at indexes 1 and 3.

Compare elements only up to the smaller array length, then separately check whether the lengths differ.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        int[] first = {10, 20, 30, 40};
        int[] second = {10, 25, 30, 50};
        int limit = Math.min(first.length, second.length);
        boolean differenceFound = false;

        for (int i = 0; i < limit; i++) {
            if (first[i] != second[i]) {
                System.out.println("Difference at index " + i + ": " + first[i] + " != " + second[i]);
                differenceFound = true;
            }
        }

        if (first.length != second.length) {
            System.out.println("Array lengths are different.");
            differenceFound = true;
        }

        if (!differenceFound) {
            System.out.println("No differences found.");
        }
    }
}

Output

Output
Difference at index 1: 20 != 25
Difference at index 3: 40 != 50

Dry Run

IndexFirstSecondResult
01010Same
12025Different
23030Same
34050Different

Why Math.min() Is Useful

If the arrays have different lengths, looping through the longer array could access a position that does not exist in the shorter one. For:

Text
first  = [1, 2, 3]
second = [1, 2]

only indexes 0 and 1 can safely be compared directly.

Complexity

  • Time: O(min(n, m)) where n and m are the two array lengths.
  • Space: O(1)

Comparison Can Mean Different Things in Interviews

  • Same length and same values in same order.
  • Find mismatching positions.
  • Lexicographical comparison.
  • Same elements regardless of order.
  • Same element frequencies.

Always clarify the required meaning.

Interview Tip

Do not assume "compare arrays" always means equality. Understand whether the interviewer wants mismatch detection, ordering, or content comparison.

15. Check Array Equality

Problem

Determine whether two arrays contain exactly the same values in exactly the same order. Arrays are equal when their lengths are equal and every corresponding element is equal. Example:

Text
[10, 20, 30]
[10, 20, 30]

Result: Equal. But:

Text
[10, 20, 30]
[30, 20, 10]

Result: Not Equal. The elements are the same, but their positions are different.

Check the lengths before comparing individual values.

Java Program – Manual Approach

Java
public class Main {
    public static void main(String[] args) {
        int[] first = {15, 25, 35, 45};
        int[] second = {15, 25, 35, 45};
        boolean equal = true;

        if (first.length != second.length) {
            equal = false;
        } else {
            for (int i = 0; i < first.length; i++) {
                if (first[i] != second[i]) {
                    equal = false;
                    break;
                }
            }
        }

        System.out.println("Arrays equal = " + equal);
    }
}

Output

Output
Arrays equal = true

Dry Run

Length check:

Text
first.length = 4
second.length = 4

Lengths match. Element comparisons:

Text
first[0] == second[0] -> 15 == 15
first[1] == second[1] -> 25 == 25
first[2] == second[2] -> 35 == 35
first[3] == second[3] -> 45 == 45

No mismatch occurs, so equal remains true.

Optimized Behavior

The break statement stops comparison immediately after the first mismatch. There is no need to inspect the remaining elements once inequality has been established.

Built-in Approach

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] first = {15, 25, 35, 45};
        int[] second = {15, 25, 35, 45};

        System.out.println("Arrays equal = " + Arrays.equals(first, second));
    }
}

Output

Output
Arrays equal = true

Why first == second Is Usually Wrong for Content Comparison

For arrays:

Java
int[] first = {1, 2, 3};
int[] second = {1, 2, 3};

The expression first == second checks whether both variables refer to the exact same array object. It does not compare their element values. Use Arrays.equals(first, second) for one-dimensional array content comparison.

Complexity

  • Time: O(n) in the worst case.
  • Space: O(1)

For Nested Arrays

Use Arrays.deepEquals() when comparing nested object-array structures where deep element comparison is required.

Interview Tip

A common Java interview question asks for the difference between ==, Arrays.equals(), and Arrays.deepEquals().

Core Array Traversal Patterns

Most fundamental array problems can be reduced to a small set of traversal patterns.

Problem TypeState Maintained
Print elementsCurrent element
SumRunning total
AverageSum and length
MaximumLargest value so far
MinimumSmallest value so far
Second largestLargest + second largest
Second smallestSmallest + second smallest
Count valuesCounter
ClassificationMultiple counters
CopySource and destination index
ReverseLeft and right pointers
EqualityEquality flag
ComparisonMismatch information

Recognizing the pattern is more valuable than memorizing individual programs.

Index-Based Loop vs Enhanced For Loop

Use an index-based loop when the position matters:

Java
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Index " + i + " = " + numbers[i]);
}

Useful for reversing an array, updating elements, comparing corresponding indexes, copying by position, finding an element's index, and accessing neighboring elements.

Use an enhanced for loop when only values matter:

Java
for (int number : numbers) {
    System.out.println(number);
}

Useful for sum, count, maximum, minimum, and simple printing. An enhanced loop does not directly expose the current array index.

Array Length and Valid Indexes

For int[] numbers = new int[5];, array length is numbers.length = 5. Valid indexes:

Text
0
1
2
3
4

Invalid index: 5. Therefore, the standard traversal condition is i < numbers.length, not i <= numbers.length.

Array Initialization

Direct Initialization

int[] numbers = {10, 20, 30, 40}; Java automatically determines the length.

Create First, Assign Later

Java
int[] numbers = new int[4];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;

Default Values

For int[] numbers = new int[3];, initial contents are [0, 0, 0]. Common primitive defaults:

TypeDefault Value
byte0
short0
int0
long0L
float0.0f
double0.0
char''
booleanfalse

Reference-type array elements default to null.

Important Array Edge Cases

Empty Array

int[] numbers = {}; Its length is 0. Traversal is safe:

Java
for (int number : numbers) {
    System.out.println(number);
}

The loop simply executes zero times. However, this is unsafe: int max = numbers[0]; There is no index 0. Problems such as maximum, minimum, second largest, and average therefore require meaningful handling for empty input.

Single-Element Array

[50]. Valid results: Sum = 50, Average = 50.0, Maximum = 50, Minimum = 50. But there is no second distinct largest or second distinct smallest value.

Duplicate Elements

For [10, 20, 20, 30, 30], duplicates do not affect basic sum or count logic, but they matter when finding distinct values such as second largest.

Negative Values

Algorithms should not assume values are positive. For example, [-20, -5, -12] has maximum -5. Initializing max = 0 would produce an incorrect result.

Common Array Logic Mistakes

Off-by-One Error

Incorrect: for (int i = 0; i <= numbers.length; i++). Correct: for (int i = 0; i < numbers.length; i++).

Assuming Arrays Start at Index 1

Incorrect: numbers[1] for accessing the first element. The first element is numbers[0].

Confusing Length with Last Index

If numbers.length == 5, the last index is 4.

Incorrect Maximum Initialization

Risky: int max = 0; Better: int max = numbers[0];

Integer Division While Calculating Average

Risky: double average = sum / numbers.length; Better: double average = (double) sum / numbers.length;

Comparing Array References Instead of Contents

Incorrect for content comparison: first == second. Correct: Arrays.equals(first, second).

Accidentally Sharing the Same Array

This does not make an independent copy: int[] copy = original; Use an actual copying operation when separate arrays are required.

Sorting Unnecessarily

Finding maximum, minimum, second maximum, or second minimum does not normally require sorting. A direct traversal usually gives O(n) time compared with O(n log n) sorting.

Complexity Summary

OperationTimeExtra Space
Read Array ElementsO(n)O(n)
Print Array ElementsO(n)O(1)
Sum ElementsO(n)O(1)
Average ElementsO(n)O(1)
Maximum ElementO(n)O(1)
Minimum ElementO(n)O(1)
Second LargestO(n)O(1)
Second SmallestO(n)O(1)
Count Even ElementsO(n)O(1)
Count Odd ElementsO(n)O(1)
Count Positive/NegativeO(n)O(1)
Copy ArrayO(n)O(n)
Reverse In PlaceO(n)O(1)
Compare ArraysO(min(n,m))O(1)
Check EqualityO(n)O(1)

The array itself requires O(n) storage. "Extra space" refers to additional working memory used by the algorithm.

Important Java Array APIs

The java.util.Arrays class provides useful array operations.

Arrays.toString(numbers)

Compare One-Dimensional Arrays

Arrays.equals(first, second)

Copy an Array

Arrays.copyOf(numbers, numbers.length)

Copy a Range

Arrays.copyOfRange(numbers, 1, 4)

Sort an Array

Arrays.sort(numbers)

Fill an Array

Arrays.fill(numbers, 10)

Search a Sorted Array

Arrays.binarySearch(numbers, target)

These methods are useful in production code, but manually implementing fundamental operations is valuable when learning logic or answering coding interview questions.

Interview-Focused Concepts

A learner should be able to explain these points without relying only on memorized code:

  • Why array indexes begin at 0.
  • Why the last valid index is length - 1.
  • Why most full-array traversals require O(n) time.
  • Why maximum should normally be initialized from an actual array element.
  • Why average calculations may require type casting.
  • Why duplicates require special handling in second-largest and second-smallest problems.
  • Why reversing can be performed using two pointers.
  • Why array assignment does not automatically create an independent copy.
  • Why == and Arrays.equals() behave differently.
  • Why sorting is unnecessary for many simple selection problems.
  • Why an empty array requires special handling for operations that need a first element.

Practice Variations

After understanding the fundamentals, useful extensions include:

  1. Find both maximum and minimum in one traversal.
  2. Find the index of the maximum element.
  3. Calculate the sum of only even elements.
  4. Calculate separate sums for positive and negative elements.
  5. Count occurrences of a particular value.
  6. Reverse only part of an array.
  7. Compare arrays without using Arrays.equals().
  8. Copy only a selected range of elements.
  9. Find the second largest value when duplicates are allowed.
  10. Find the difference between maximum and minimum.
  11. Find elements greater than the array average.
  12. Determine whether an array is already sorted.
  13. Check whether two arrays contain the same values regardless of order.
  14. Find the first mismatch between two arrays.
  15. Swap the first and last array elements.

These variations build directly on traversal, comparison, accumulation, counters, and two-pointer logic introduced in this chapter.

Chapter Takeaways

  • Array problems become easier when the required state is identified before writing the loop.
  • A single traversal is sufficient for most fundamental calculations.
  • Use numbers.length instead of hard-coding array bounds.
  • Initialize minimum and maximum values from actual array data.
  • Treat duplicates carefully when finding ranked elements.
  • Use two pointers for efficient in-place reversal.
  • Understand the difference between an array reference and the data stored inside the array.
  • Use Arrays.equals() for content equality rather than ==.
  • Prefer O(n) traversal over sorting when sorting is not necessary for the required result.
  • Always consider empty arrays, single-element arrays, negative numbers, duplicates, and numeric overflow when they affect the logic.

Question Hint