Skip to main content

Arrays & Strings in Java Explained (DSA Guide for Beginners & Interviews)

Master Arrays & Strings Without Memorizing

A simple way to actually understand DSA instead of getting stuck.

You know arrays. You know strings. But can you solve this quickly?

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

Most developers struggle here — not because it’s hard, but because they don’t think the right way.

Understanding Arrays (The Right Way)

Think of an array like a row of boxes in memory.

[10] [20] [30] [40]
Index: 0   1   2   3

You can directly jump to any index. That’s why access is extremely fast.

  • Access → O(1)
  • Insert/Delete → O(n)

Add your array visualization image here

Where Arrays Become Slow

[10, 20, 30, 40]
Insert 15 at index 1
→ [10, 15, 20, 30, 40]

Everything shifts → that’s the cost.

Let’s Solve a Problem

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

The beginner approach is brute force — try all pairs.

It works… but it’s slow.

The real question is: Can we avoid repeating work?

Two Pointer Thinking

If the array is sorted, we can use two pointers.

  • Start from both ends
  • Compare sum
  • Move pointers accordingly
1 + 9 > 8 → move right
1 + 6 < 8 → move left
2 + 6 = 8 ✅

Add your two pointer illustration here

Where Sliding Window Fits

Sliding window is powerful — but not for every problem.

It only works when elements are continuous.

Example:

[2, 3, 5, 2, 8, 1]
Window size = 3

Instead of recalculating everything:

Remove left element → Add right element → Update result

Add your sliding window illustration here

Strings (Small but Tricky)

"hello" → ['h','e','l','l','o']

Strings look simple, but they are immutable.

Every change creates a new object.

Better Approach

StringBuilder sb = new StringBuilder("hello");
sb.append(" world");

This avoids unnecessary object creation.

String Constant Pool (Important)

String s1 = "hello";
String s2 = "hello";

Both point to the same object in memory.

String s3 = new String("hello");

This creates a new object.

👉 Always use .equals() instead of ==

Add SCP diagram here

Frequency Count (Very Useful)

"apple"
a → 1
p → 2

This pattern is used in:

  • Anagrams
  • Duplicates
  • Counting problems

Add frequency diagram here

What You Should Remember

  • Arrays → fast access, slow updates
  • Strings → immutable
  • Two pointer → compare from ends
  • Sliding window → subarrays
  • Frequency → counting

Final Thought

Don’t memorize problems. Understand patterns — everything becomes easier.

Try This

  • Reverse an array
  • Check palindrome
  • Find pair with sum
  • First non-repeating character

If this helped, share it with someone learning DSA 🚀

Comments