🎓 A1Learner
🔍
0 of 47 lessons completed

Practice: Array Problems

Practice with array problems is a set of array tasks that reuse the patterns from the earlier array lessons. The value is in recognizing the pattern fast, then applying its template.

Read the recognition signal

Each problem shape points at one pattern. A pair in a sorted list, a count, and a run of items each give a clear signal.

problems = [("find a pair in a sorted list", "two pointers"), ("count how often each number appears", "hash map"), ("largest sum of 3 in a row", "sliding window")]
for problem, signal in problems:
    print(problem, "->", signal)

Apply the two pointers template

The two pointers start at both ends of the sorted list. A small sum moves the left pointer, and a large sum moves the right pointer.

def pair_sum(nums, target):
    left = 0
    right = len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return [left, right]
        if total < target:
            left += 1
        else:
            right -= 1
    return []

print(pair_sum([1, 2, 4, 6, 8], 10))

Work a counting problem

A hash map counts each value in one pass. The value 2 appears three times, more than any other value here.

nums = [1, 2, 2, 3, 2, 1]
counts = {}
for num in nums:
    counts[num] = counts.get(num, 0) + 1
best = None
best_count = 0
for num in [1, 2, 3]:
    if counts[num] > best_count:
        best = num
        best_count = counts[num]
print("most common:", best, "count:", best_count)

Example

def max_window_sum(nums, k):
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]
        best = max(best, window)
    return best

print(max_window_sum([2, 1, 5, 1, 3, 2], 3))

Key points

  • Array practice: solving fresh array tasks with the patterns introduced earlier in the course.
  • Use the two pointers pattern for a pair search in a sorted list.
  • Use the sliding window pattern for a sum or count over consecutive items.
  • Use a hash map to count how often each value appears.

The code sums the first three numbers, then slides the window one step at a time. Each slide drops the oldest number and adds the newest one. The best window holds 5, 1, and 3, which sum to 9.

Note

recognition comes first, and the template comes second, on every problem.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A sorted list asks for two numbers that add to a target. Which pattern fits the problem?