Jaconir

Arrays & Strings: The Building Blocks

Learn about the most fundamental data structures in programming and how to use them effectively.

What Are Arrays?

An array is the simplest and most widely used data structure. You can think of it as a list of items stored in a contiguous block of memory. Each item, or "element," has a numbered position, called an "index," starting from 0.

Imagine a street with a row of mailboxes. Each mailbox has a number (the index) and contains a piece of mail (the element). If you know the mailbox number, you can go directly to it without checking the others. This direct access is what makes arrays so fast for retrieving elements.

Interactive Array
Add, remove, and access elements to see how an array works.
0
Apple
1
Banana
2
Cherry
Visualizing Time Complexity
See why some array operations are slower than others. "Start" and "End" refer to the beginning and end of the array.

Access

Accessing an element by its index is instantaneous because its memory location is calculated directly.

O(1)
10
20
30
40

Common Array Patterns

Two Pointers
Using two pointers to iterate through an array from different ends until they meet. Ideal for problems involving sorted arrays or palindromes.

Problem: Two Sum

Given a sorted array, find if there is a pair of numbers that add up to a target. Here, the target is 22.

Analogy: Two friends start at opposite ends of a library aisle, walking towards each other to find two books whose page counts sum to a specific value.

2
L
7
11
15
23
31

R
Start with pointers at both ends of the sorted array.
Sliding Window
Creating a 'window' of a certain size that moves over the array. Used for finding the maximum/minimum subarray of a fixed size.

Problem: Maximum Sum Subarray

Given an array of integers, find the maximum sum of any contiguous subarray of size 'k'. Here, k is 3.

Analogy: Imagine a train with 3 windows. As it moves along the tracks (the array), you want to find the section of track where the sum of numbers seen through the windows is the highest.

2
1
5
1
3
2
9
1
Start with an empty window.
Window Sum:
0
| Max Sum Found:
0
Quick Quiz: Test Your Knowledge

What is the time complexity to get the first element of an array (`arr[0]`)?

What is the time complexity to add an element to the beginning of an array (`arr.unshift(newItem)`)?

You need to find if a value exists in an unsorted array. What is the worst-case time complexity?

Coding Challenge
Given an integer array `nums`, return an array `answer` such that `answer[i]` is equal to the product of all the elements of `nums` except `nums[i]`. You must write an algorithm that runs in O(n) time and without using the division operation.
Go Deeper with "Grokking Algorithms"

For a fantastically illustrated and easy-to-understand guide to algorithms and data structures like arrays, "Grokking Algorithms" by Aditya Bhargava is an unbeatable resource for visual learners.