DSA Arrays - Complete Guide
1. What is an Array?
An array is a data structure that stores elements of the same type in contiguous memory locations. Each element is
accessed by an index (starting from 0).
2. Why Use Arrays?
Arrays are used to efficiently store and access multiple items using indexing. Useful in looping, searching, sorting, and
forms the base for other data structures like stacks, queues, matrices.
3. Operations on Arrays
- Traversal: Access all elements one by one (O(n))
- Insertion: Add element (end: O(1), middle: O(n))
- Deletion: Remove element (O(n))
- Searching: Find an element (linear: O(n), binary: O(log n))
- Update: Change value at index (O(1))
4. Array Declaration in Java
int[] arr = {1, 2, 3}; // Declare and initialize
int[] arr = new int[5]; // Declare size
5. Types of Problems on Arrays
- Easy: Find max/min, reverse array, check sorted
- Medium: Move zeroes, remove duplicates, rotate array
- Hard: Kadane's Algo, Trapping Rain Water, Subarray with given sum
6. Common Patterns
- Two-pointer: For problems involving pairs or reversing
- Sliding Window: For subarray problems with size constraints
- Prefix Sum: For range-based sums
- Sorting + Binary Search: For optimization & faster searches
7. Template Code
- Max Element:
int max = arr[0]; for(int i=1;i<arr.length;i++){ if(arr[i]>max) max=arr[i]; }
- Reverse Array:
int i=0, j=arr.length-1; while(i<j){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; i++; j--; }
- Move Zeroes:
int index=0; for(int i=0;i<arr.length;i++){ if(arr[i]!=0) arr[index++]=arr[i]; } while(index<arr.length) arr[index++]=0;
DSA Arrays - Complete Guide
8. Practice Platforms
- LeetCode: https://leetcode.com/tag/array/
- GeeksForGeeks: https://www.geeksforgeeks.org/array-data-structure/
- Striver's Sheet: https://takeuforward.org/interviews/strivers-sde-sheet-top-coding-interview-problems/
9. Tips for Mastery
- Focus on edge cases (empty arrays, duplicates, all same values)
- Practice in a timed environment
- Understand brute force before optimizing
- Use dry runs to verify logic