Master the fundamentals of arrays, from basic operations to advanced techniques and real-world applications.
An array is a collection of elements stored in contiguous memory locations. Each element can be directly accessed using its index, which represents its position in the array. Arrays are one of the most fundamental data structures in computer science.
Arrays store elements in contiguous memory locations. If an array starts at memory address 1000 and each element takes 4 bytes, then:
Address = Base_Address + (Index × Element_Size)
This formula enables O(1) random access to any element, making arrays highly efficient for scenarios requiring frequent element access.
// Array Declaration in Different Languages
// JavaScript
let numbers = [1, 2, 3, 4, 5];
let names = ["Alice", "Bob", "Charlie"];
// Python
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
// Java
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
// C++
int numbers[] = {1, 2, 3, 4, 5};
std::string names[] = {"Alice", "Bob", "Charlie"};
// Basic Array Operations
// Access - O(1)
let firstElement = arr[0];
let lastElement = arr[arr.length - 1];
// Update - O(1)
arr[2] = 100;
// Search - O(n)
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // Return index if found
}
}
return -1; // Not found
}
// Insertion at end - O(1) amortized
arr.push(newElement);
// Insertion at specific position - O(n)
function insertAt(arr, index, element) {
for (let i = arr.length; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = element;
}
Beyond basic operations, arrays are used in many sophisticated algorithms and techniques:
// Advanced Array Algorithms
// Binary Search (for sorted arrays) - O(log n)
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
// Two Pointer Technique
function twoSum(arr, target) {
let left = 0, right = arr.length - 1;
while (left < right) {
let sum = arr[left] + arr[right];
if (sum === target) return [left, right];
else if (sum < target) left++;
else right--;
}
return [];
}
// Sliding Window Technique
function maxSubarraySum(arr, k) {
let maxSum = 0, windowSum = 0;
// Calculate sum of first window
for (let i = 0; i < k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
// Slide the window
for (let i = k; i < arr.length; i++) {
windowSum = windowSum - arr[i - k] + arr[i];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
Use two pointers moving towards each other to solve problems efficiently
Maintain a window of elements and slide it to find optimal solutions
Efficiently search sorted arrays by eliminating half the search space