Skip to main content

๐Ÿ“ฆ Array

Conceptโ€‹

An array is a fixed-size, contiguous block of memory that stores elements of the same type. In Java, arrays are zero-indexed. ArrayList is the dynamic counterpart and is used when the size is unknown upfront.

Arrays are the foundation of almost every other data structure and algorithm pattern. Most interview problems that involve "traversal", "searching", or "in-place modification" are array problems at heart.


When to Useโ€‹

  • The input is a list of integers, characters, or objects
  • You need O(1) random access by index
  • The problem asks for in-place manipulation
  • You're building up patterns like two-pointers, sliding window, or prefix sum (all start from array basics)

Key Operations & Complexityโ€‹

OperationArrayArrayList
Access by indexO(1)O(1)
Search (unsorted)O(n)O(n)
Search (sorted)O(log n)O(log n)
Insert at endN/AO(1) amortized
Insert at indexN/AO(n)
DeleteN/AO(n)

Java Templateโ€‹

// Declare and initialize
int[] arr = new int[5];
int[] arr2 = {1, 2, 3, 4, 5};

// Iterate
for (int i = 0; i < arr.length; i++) { ... }
for (int num : arr) { ... } // enhanced for-loop

// 2D array
int[][] matrix = new int[3][4];
for (int[] row : matrix) Arrays.fill(row, 0);

// Sort
Arrays.sort(arr); // ascending
Arrays.sort(arr, 0, arr.length); // range sort

// Copy
int[] copy = Arrays.copyOf(arr, arr.length);
int[] rangeCopy = Arrays.copyOfRange(arr, 1, 4);

// Convert to List
List<Integer> list = new ArrayList<>();
for (int n : arr) list.add(n);

Common Patternsโ€‹

1. Two-Pass Techniqueโ€‹

Calculate something on the first pass, use it on the second.

// Example: Product of array except self
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];

// Left pass: result[i] = product of all elements left of i
result[0] = 1;
for (int i = 1; i < n; i++) {
result[i] = result[i - 1] * nums[i - 1];
}

// Right pass: multiply by product of all elements right of i
int right = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}
return result;
}

2. In-Place Modification (Swap)โ€‹

// Reverse an array in-place
public void reverse(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int temp = nums[left];
nums[left++] = nums[right];
nums[right--] = temp;
}
}

3. Counting with HashMapโ€‹

// Check if two arrays are anagrams
public boolean isAnagram(int[] a, int[] b) {
Map<Integer, Integer> count = new HashMap<>();
for (int n : a) count.merge(n, 1, Integer::sum);
for (int n : b) {
if (!count.containsKey(n)) return false;
count.merge(n, -1, Integer::sum);
if (count.get(n) == 0) count.remove(n);
}
return count.isEmpty();
}

Worked Example: Find Duplicate Numberโ€‹

Problem: Given an array of n+1 integers where each integer is in [1, n], find the duplicate.

Approach: Use Floyd's cycle detection (or mark visited using negative sign).

public int findDuplicate(int[] nums) {
// Mark visited: negate nums[nums[i]]
// If already negative, we've seen this index โ†’ it's the duplicate
for (int i = 0; i < nums.length; i++) {
int idx = Math.abs(nums[i]);
if (nums[idx] < 0) return idx;
nums[idx] = -nums[idx];
}
return -1; // should never reach here
}

Trace for [1, 3, 4, 2, 2]:

i=0: idx=1, nums[1]=3 โ†’ negate โ†’ [-,โˆ’3,4,2,2]
i=1: idx=3, nums[3]=2 โ†’ negate โ†’ [-,โˆ’3,4,โˆ’2,2]
i=2: idx=4, nums[4]=2 โ†’ negate โ†’ [-,โˆ’3,4,โˆ’2,โˆ’2]
i=3: idx=2, nums[2]=4 โ†’ negate โ†’ [-,โˆ’3,โˆ’4,โˆ’2,โˆ’2]
i=4: idx=2, nums[2]=-4 โ†’ NEGATIVE! Return 2 โœ“

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


LeetCode Problemsโ€‹

๐ŸŸข Easyโ€‹

#ProblemKey Idea
1Two SumHashMap complement lookup
26Remove Duplicates from Sorted ArrayTwo pointers, in-place
27Remove ElementOverwrite with valid elements
121Best Time to Buy and Sell StockTrack running min
217Contains DuplicateHashSet
238Product of Array Except SelfLeft/right pass
283Move ZeroesTwo pointers
448Find All Numbers Disappeared in an ArrayMark visited with negation

๐ŸŸก Mediumโ€‹

#ProblemKey Idea
153SumSort + two pointers
31Next PermutationFind dip, swap, reverse
48Rotate ImageTranspose + reverse
54Spiral MatrixLayer peeling
73Set Matrix ZeroesUse first row/col as flags
189Rotate ArrayReverse 3 times
287Find the Duplicate NumberFloyd's / negation
442Find All Duplicates in an ArrayNegation trick

๐Ÿ”ด Hardโ€‹

#ProblemKey Idea
41First Missing PositiveCyclic sort / swap to correct index
84Largest Rectangle in HistogramMonotonic stack
85Maximal RectangleBuild histogram row by row