Sitemap
Press enter or click to view image in full size
Arrays in DSA Explained Simply | Basic Traversal & Two Sum | Part 1

Arrays in DSA Explained Simply | Basic Traversal & Two Sum | Part 1

--

Learn Arrays in DSA for coding interviews with this beginner-friendly Part 1 guide. Understand array traversal, Two Sum, hashing patterns, complexity, interview strategies, and essential LeetCode practice problems.

Arrays are usually one of the first data structures you encounter in DSA.

But in coding interviews, the challenge is rarely:

“Do you know what an array is?”

The real question is:

Can you look at an array problem and quickly recognize the approach needed to solve it?

In this article, we will start with the most fundamental array technique: traversal.

Then we will move to one of the most important beginner interview problems:

Two Sum

Along the way, we will learn how to recognize the Hashing pattern behind Two Sum and build a reusable way of thinking about similar problems.

What You Will Learn

By the end of this article, you will understand:

  • What an array is
  • How array traversal works
  • Common types of array traversal questions
  • How to approach an array problem during an interview
  • The Two Sum problem
  • The brute-force thinking behind Two Sum
  • The Hashing pattern behind the optimized approach
  • How to recognize similar problems
  • Which LeetCode problems you should practice next

1. What Is an Array?

An array is a data structure used to store multiple values in a sequence.

For example:

[10, 20, 30, 40, 50]

Each value has a position called an index.

Value:    10   20   30   40   50
Index: 0 1 2 3 4

In most programming languages, array indexing starts from 0.

So:

arr[0] → 10
arr[1] → 20
arr[2] → 30
arr[3] → 40
arr[4] → 50

Real-World Analogy

Think of an array as a row of numbered lockers.

┌────┬────┬────┬────┬────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└────┴────┴────┴────┴────┘
0 1 2 3 4

If you know the position, you can directly access the value.

That is one of the reasons arrays are so useful.

2. The First Array Skill: Traversal

Before learning complicated patterns, you need to become comfortable with one basic operation:

Visiting every element of an array.

This is called array traversal.

For example:

[4, 7, 2, 9, 1]

A traversal visits:

4 → 7 → 2 → 9 → 1

A simple loop can do this:

for each element in the array:
process the element

In JavaScript:

const arr = [4, 7, 2, 9, 1];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

The important idea is not the syntax.

The important idea is:

Move through the array one element at a time and perform some operation on each element.

3. Basic Traversal Pattern

A large number of beginner array questions follow this structure:

Start
↓
Visit element
↓
Perform operation
↓
Move to next element
↓
Repeat until the array ends

Generic pseudocode:

for i = 0 to n - 1:
    process arr[i]

This simple pattern can solve many problems.

For example:

Find the maximum

[4, 8, 2, 10, 6]
Start with max = 4
Compare:
8 > 4 → max = 8
2 > 8 → no
10 > 8 → max = 10
6 > 10 → no
Answer = 10

Find the sum

[2, 4, 6, 8]
sum = 0
sum = 0 + 2
sum = 2 + 4
sum = 6 + 6
sum = 12 + 8
Answer = 20

Count something

Suppose we want to count even numbers:

[1, 4, 7, 8, 10]
1 → ignore
4 → count
7 → ignore
8 → count
10 → count
Answer = 3

The underlying pattern is still the same:

Traverse → inspect → update some state.

4. Common Basic Traversal Question Types

When you see a simple array problem, ask:

“Can I solve this by visiting each element once?”

Common examples include:

Question TypeWhat You Usually MaintainFind maximummaxFind minimumminCalculate sumsumCount elementscountFind an elementfound / indexCount occurrencesfrequency/countCheck a conditionbooleanModify elementsarray/index

These problems are important because they build your basic array intuition.

5. Complexity of Basic Traversal

Suppose an array contains n elements.

If you visit every element exactly once:

[1] → [2] → [3] → ... → [n]

You perform approximately n operations.

Therefore:

Time Complexity

O(n)

Space Complexity

Usually:

O(1)

if you only maintain variables such as:

sum
max
min
count

So the general pattern is:

ApproachTimeExtra SpaceSingle traversalO(n)O(1)

💡 Interview Insight: If a problem only asks you to inspect every element once, your first instinct should usually be a single traversal.

6. But Array Problems Become More Interesting

Now imagine the interviewer gives you:

nums = [2, 7, 11, 15]
target = 9

And asks:

Find two numbers whose sum equals the target.

Now simply traversing once isn’t enough.

You need to compare elements with other elements.

This brings us to one of the most famous array interview problems:

Two Sum

LeetCode — Two Sum

7. Two Sum: Understand the Problem

Suppose:

nums = [2, 7, 11, 15]
target = 9

We need to find two numbers whose sum is 9.

Look at:

2 + 7 = 9

So the answer is the indices of 2 and 7.

[2, 7, 11, 15]
↑ ↑
0 1

Answer:

[0, 1]

The important part is not memorizing the solution.

Instead, ask:

While looking at one number, what information do I need to find its partner?

8. Start With Brute Force Thinking

Suppose we are currently looking at:

2

The target is:

9

What number do we need?

9 - 2 = 7

So we need to find:

7

Now look at the next element.

7

Found it.

This gives us an important observation:

For every number x, the number we need is target - x.

This is called the complement.

complement = target - currentNumber

For:

target = 9
current = 2

we get:

complement = 9 - 2
= 7

9. Brute Force Approach

The simplest approach is:

Take one element
↓
Compare it with every element after it
↓
Check whether their sum equals target

For:

[2, 7, 11, 15]

we might check:

2 + 7
2 + 11
2 + 15
7 + 11
7 + 15
11 + 15

This works.

But there is a problem.

For an array of n elements, we may need to compare many pairs.

That results in:

O(n²)

time complexity.

For small inputs, that may be acceptable.

For large inputs, we want something better.

10. The Key Question

Let’s return to our observation:

current number → need target - current

Suppose:

target = 9

We see:

2

We need:

7

Instead of searching the entire array again, what if we could quickly answer:

“Have I already seen 7?”

This is where Hashing becomes useful.

11. The Hashing Pattern

A hash-based data structure allows us to store information so that we can quickly check whether something already exists.

Think of it like a lookup table.

Instead of repeatedly searching:

Have I seen 7?
Search...
Search...
Search...

we maintain a collection of values we have already encountered.

Conceptually:

Seen values
┌────┬────┬────┐
│ 2 │ 7 │ 11 │
└────┴────┴────┘

Now when we need 7, we can ask:

Have I seen 7?

If yes, we have found our pair.

12. The Two Sum Hashing Pattern

The reusable thought process is:

For every number:
1. Calculate the complement
complement = target - current
2. Check whether complement was seen before
3. If yes:
We found the answer
4. If no:
Store the current number
5. Continue

The pattern looks like this:

Current number
↓
Calculate complement
↓
target - current number
↓
Have we seen it before?
↙ ↘
YES NO
↓ ↓
Found pair Store current

This is the core idea you should remember.

Get Tuhin Kairi’s stories in your inbox

Join Medium for free to get updates from this writer.

Not:

“Two Sum uses a HashMap.”

Instead remember:

“I need a complementary value, so I can store previously seen values for fast lookup.”

That thought process is much more reusable.

13. Recognizing the Pattern

During an interview, watch for these clues:

Clue 1: You need two values

For example:

Find two numbers...

Clue 2: They must satisfy a relationship

For example:

sum = target
difference = target
product = target

Clue 3: You repeatedly ask whether a required value exists

For example:

Does the complement already exist?

Clue 4: Searching repeatedly would be expensive

If your brute-force solution looks like:

for every element:
search the remaining array

you should ask:

Can I store previously seen information for faster lookup?

This is the beginning of recognizing the Hashing pattern.

14. The General Hashing Pattern

The Two Sum idea can be generalized:

Input
↓
Traverse the data
↓
Calculate what information/value is required
↓
Check previously stored information
↓
If found → use it
↓
If not found → store current information
↓
Continue

This pattern appears in many interview problems.

The exact information stored may change.

You might store:

  • A value
  • An index
  • A frequency
  • A prefix sum
  • A previously seen state

But the core idea remains:

Store useful information so that future lookups become faster.

15. Two Sum: Complexity Thinking

There are two important approaches to understand.

ApproachTimeExtra SpaceMain IdeaBrute ForceO(n²)O(1)Check every pairHashingO(n) averageO(n)Store previously seen values

The optimized approach trades additional memory for faster lookup.

This is a very common interview trade-off:

Use more space to reduce time.

You will see this idea repeatedly throughout DSA.

16. Basic Traversal vs Two Sum

Notice how both problems start with an array traversal.

Basic Traversal

Visit each element
↓
Perform an operation

Two Sum

Visit each element
↓
Calculate required value
↓
Check previously seen data
↓
Update stored data

So Two Sum is not completely different from basic traversal.

It builds on it.

The traversal is still there.

We have simply added a data structure to make the traversal more powerful.

17. Common Mistakes

Mistake 1: Immediately writing nested loops

Nested loops are a valid starting point.

But in an interview, don’t stop there.

Ask:

Can I reduce repeated searching?

Mistake 2: Forgetting the complement

Instead of thinking:

What pairs can I try?

think:

current = x
required = target - x

This turns the problem into a lookup problem.

Mistake 3: Storing only values when the problem needs indices

Two Sum asks for indices.

So you need to think about what information must be preserved.

This is an important interview habit:

Before choosing a data structure, ask what information the final answer requires.

Mistake 4: Ignoring duplicate values

Consider:

[3, 3]
target = 6

Both values are the same.

Your approach must still allow two different positions to form the answer.

Always test:

  • Duplicate values
  • Negative numbers
  • Zero
  • Very small arrays
  • No valid answer

18. Interview Thought Process

When you see an array problem, don’t immediately code.

Use this sequence:

1. Understand the input
↓
2. Understand the expected output
↓
3. Try the simplest solution
↓
4. Identify repeated work
↓
5. Ask whether a data structure can reduce it
↓
6. Analyze time and space
↓
7. Handle edge cases
↓
8. Then code

This is more valuable than memorizing individual solutions.

19. Practice: Basic Traversal

Before moving deeper into patterns, practice implementing simple traversal problems yourself.

Practice 1 — Find Maximum

Given:

[3, 7, 2, 9, 4]

Find the largest element.

Goal: Implement a single traversal.

Practice 2 — Find Minimum

Given:

[8, 3, 6, 1, 9]

Find the smallest element.

Goal: Maintain a min value while traversing.

Practice 3 — Calculate Sum

Given:

[5, 10, 15, 20]

Calculate the total.

Goal: Maintain a running sum.

Practice 4 — Count Even Numbers

Given:

[1, 4, 7, 8, 10, 13]

Count how many numbers are even.

Goal: Combine traversal with a condition.

Practice 5 — Linear Search

Given:

[10, 20, 30, 40, 50]

Find whether 30 exists.

Goal: Traverse and maintain a found condition or index.

20. Practice: Two Sum

Now implement the Two Sum idea.

Level 1 — Understand the Brute Force

Given:

nums = [2, 7, 11, 15]
target = 9

Find the two indices whose values add up to 9.

First implement it using nested loops.

Focus on understanding:

i
j
nums[i] + nums[j]

Level 2 — Identify the Complement

For every number:

complement = target - current

Try manually calculating the complement for:

nums = [2, 7, 11, 15]
target = 9

Create a table:

CurrentComplement2?7?11?15?

Level 3 — Implement Hashing

Now implement Two Sum using a hash-based lookup.

Your goal is to achieve:

O(n)

average time.

Do not copy a solution.

Try to derive it from:

complement = target - current

21. LeetCode Practice Set

The roadmap intentionally progresses from basic array operations toward more pattern-oriented problems.

Easy — Start Here

1. Two Sum

Pattern: Hashing

What it teaches: Complement lookup and storing previously seen information.

Solve Two Sum on LeetCode

2. Remove Element

Pattern: Array Traversal / In-place Array Manipulation

What it teaches: Traversing an array while modifying its effective contents.

Solve Remove Element on LeetCode

3. Remove Duplicates from Sorted Array

Pattern: Array Traversal → Two Pointers

What it teaches: Using traversal to process a sorted array and prepare for the Two Pointer pattern.

Solve Remove Duplicates from Sorted Array on LeetCode

4. Contains Duplicate

Pattern: Hashing

What it teaches: Detecting whether previously seen information exists.

Solve Contains Duplicate on LeetCode

5. Majority Element

Pattern: Frequency Counting

What it teaches: Tracking information about repeated values.

Solve Majority Element on LeetCode

22. What You Should Implement Yourself

Before reading any solution walkthrough, make sure you can implement these from scratch:

✓ Array traversal
✓ Find maximum
✓ Find minimum
✓ Calculate sum
✓ Count elements satisfying a condition
✓ Linear search
✓ Two Sum — brute force
✓ Two Sum — hashing
✓ Remove Element
✓ Remove Duplicates from Sorted Array
✓ Contains Duplicate

The goal is not to solve these once.

The goal is to reach the point where you can look at the problem and immediately think:

"What information do I need?"
↓
"What pattern is this?"
↓
"What data structure helps?"
↓
"What is the time complexity?"

23. Pattern Connection

Two Sum is especially important because it introduces a pattern that will appear again later.

The roadmap maps:

Hashing
↓
Two Sum
Contains Duplicate
Happy Number
Longest Consecutive Sequence
...

It also identifies Two Sum under the HashMap topic and later introduces dedicated Two Pointer problems such as Two Sum II and 3Sum.

So don’t think of Two Sum as just one LeetCode question.

Think of it as your first introduction to a larger problem-solving pattern:

Can previously seen information help me avoid repeated searching?

24. Summary

Today we covered the foundation of array problem solving.

Arrays

  • Store multiple values in a sequence.
  • Elements are accessed using indices.
  • Traversal means visiting elements one by one.

Basic Traversal

The basic pattern is:

Traverse
↓
Inspect
↓
Update

Typical complexity:

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

Two Sum

The important observation is:

complement = target - current

Instead of repeatedly searching for the complement, we can store previously seen values.

This introduces the Hashing pattern:

Traverse
↓
Calculate required information
↓
Check previously seen data
↓
Store current information

The key interview lesson is:

Don’t just ask whether your solution works. Ask whether you are repeating work that a data structure could eliminate.

Homework

Before reading Part 2, solve these without looking at solutions:

  1. Two Sum — brute force
  2. Two Sum — hashing
  3. Remove Element
  4. Remove Duplicates from Sorted Array
  5. Contains Duplicate
  6. Majority Element

For each problem, write down:

1. Brute-force idea
2. Pattern
3. Optimal approach
4. Time complexity
5. Space complexity
6. Edge cases

Don’t worry about solving everything perfectly.

The objective is to train problem recognition.

What’s Next?

In Part 2, we will take the problems introduced here and walk through their solutions step by step.

For each problem, we will cover:

Problem
↓
Initial Thought Process
↓
Brute Force
↓
Better Approach
↓
Optimal Approach
↓
Code
↓
Dry Run
↓
Complexity
↓
Interview Tips

The goal is not simply to know the answer.

It is to understand how to arrive at the answer during an interview.

--

--

Full-Stack Developer | Custom Automation & Gen AI Solutions | WordPress Expert | Helping Businesses Scale with Smart Tech