Skip to main content
Albero Academy

Arrays, Strings & Hash Maps

The most-used structures in interviews — array operations, the hash-map superpower, and the two-pointer and sliding-window patterns.

Chapter 2DSA16 min readBeginner friendly
  • #DSA
  • #Arrays
  • #Hash Maps

Most interview problems are dressed-up array or string questions, and most efficient solutions lean on a hash map. This chapter covers those two structures plus the two patterns — two-pointer and sliding window — that turn brute-force O(n²) solutions into clean O(n) ones.

Arrays

An array stores elements contiguously, so indexing is O(1). But inserting/removing in the middle shifts everything after it:

OperationCost
Index / update by positionO(1)
Append at endO(1)
Insert / delete in the middleO(n)
Search (unsorted)O(n)

Hash maps

A hash map (dict in Python, object/Map in JS) stores key→value pairs with O(1) average lookup, insert and delete. Whenever a brute-force solution scans the array again and again, ask: "could a hash map remember what I've seen?"

the classic: two-sum in O(n)
def two_sum(nums, target):
seen = {} # value → index
for i, n in enumerate(nums):
need = target - n
if need in seen: # O(1) lookup
return [seen[need], i]
seen[n] = i
return None
# Brute force is O(n^2); the hash map makes it O(n).

Two-pointer

On a sorted array, two indices moving toward each other (or in the same direction) solve many problems in one pass with O(1) extra space:

two-pointer on sorted input
def pair_sums_to(nums, target): # nums is sorted
lo, hi = 0, len(nums) - 1
while lo < hi:
s = nums[lo] + nums[hi]
if s == target: return (lo, hi)
if s < target: lo += 1 # need a bigger sum
else: hi -= 1 # need a smaller sum
return None

Sliding window

For "longest/shortest subarray with property X", grow a window from the right and shrink from the left instead of re-checking every subarray:

longest substring without repeats
def longest_unique(s):
seen = set()
left = best = 0
for right, ch in enumerate(s):
while ch in seen: # shrink until valid
seen.remove(s[left]); left += 1
seen.add(ch)
best = max(best, right - left + 1)
return best

Practice

Solve: (1) Does an array contain any duplicate? (use a set) (2) Given a sorted array, find a pair summing to a target (two-pointer). (3) Find the length of the longest substring without repeating characters (sliding window).

Key takeaways

  1. 01Arrays index in O(1) but insert/delete in the middle is O(n).
  2. 02Hash maps give O(1) average lookup — the go-to for "have I seen this before?".
  3. 03Two-pointer solves many sorted-array problems in one pass with O(1) space.
  4. 04Sliding window handles longest/shortest-subarray problems in O(n).
  5. 05When you reach for a nested loop, check whether a map/pointer/window makes it linear.