๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Easy Coding Patterns: Arrays, Strings, and Stacks

Python InterviewCoding Challengesโญ Premium
Python Interview ยท Difficulty: Easy-Medium

Easy problems test pattern recognition, not brilliance

The first coding round at most companies uses "easy" problems not to filter out weak programmers but to check communication, edge-case discipline, and whether you reach for the right pattern without prompting. Almost every easy array or string question is one of four moves: trade space for time with a hash map, walk inward with two pointers, maintain a window of constant size, or push and pop on a stack. This lesson turns those four moves into reflexes. You will see each pattern applied to the classic problems, note the exact complexity you should state before coding, and collect the follow-up variations interviewers use to extend a solved question.

Prerequisites

  • !Python lists, dicts, sets, and strings
  • !Basic Big-O vocabulary

What You'll Learn

  • 1Recognize which of the four core patterns a problem maps to
  • 2Implement two-sum, anagrams, parentheses validation, and sliding-window solutions cleanly
  • 3State time and space complexity before writing code, and revise it when constraints change
  • 4Handle edge cases โ€” empty input, duplicates, Unicode โ€” without prompting

The hash-map pattern: remember what you have seen

The hash map answers one question efficiently: have I seen the complement, the count, or the key before? Two Sum is the archetype โ€” walk the list once, and for each number check whether target - num is already in a dict mapping values to indices. One pass, O(n) time, O(n) space. The same skeleton powers ransom-note checks (count magazine characters, then consume them for the ransom note), valid anagrams (compare 26-slot count arrays or two Counters), and group-anagrams (sort each word or use a tuple of counts as the dict key).

State the trade-off explicitly: the dict costs memory to buy time. If the input is sorted, two pointers can solve Two Sum in O(1) space. Interviewers frequently offer that constraint as a follow-up, and candidates who immediately pivot score well. Also mention that Python dicts average O(1) but degrade under adversarial keys โ€” a fact worth knowing, rarely worth implementing a fix for in round one.

python
from collections import Counter, defaultdict


def two_sum(nums, target):
    """Value to index map; one pass, O(n) time and space."""
    seen = {}
    for index, value in enumerate(nums):
        if target - value in seen:
            return [seen[target - value], index]
        seen[value] = index
    return []


def group_anagrams(words):
    """Bucket words by their sorted signature."""
    buckets = defaultdict(list)
    for word in words:
        buckets["".join(sorted(word))].append(word)
    return list(buckets.values())


def is_anagram(a, b):
    """Counter comparison handles duplicates and length mismatch."""
    return len(a) == len(b) and Counter(a) == Counter(b)


print(two_sum([2, 7, 11, 15], 9))  # [0, 1]
print(is_anagram("anagram", "nagaram"))  # True

Two pointers: walk inward, or chase with a writer

Two pointers cover two related geometries. Inward pointers exploit sortedness: compare the ends, move the smaller or larger side, and eliminate a whole wedge of impossible pairs each step โ€” valid palindromes, containers with most water, three-sum variants. The other geometry uses a slow writer and a fast reader over the same array: because the input is sorted, duplicates cluster, so the writer only advances when the reader finds a genuinely new value. That in-place deduplication is O(n) time and O(1) extra space, and it is the canonical "modify the array in place" answer.

The follow-up to expect: what if the list is unsorted? Sorting first costs O(n log n) but often simplifies the rest; say that number out loud. Another variation asks for all pairs rather than the first โ€” collect results and skip duplicates at both pointers rather than returning immediately. Practice the skeleton until re-indexing mistakes disappear; off-by-one at the boundaries is the most common failure in live coding.

python
def is_palindrome(text):
    """Alphanumeric-only palindrome check with inward pointers."""
    left, right = 0, len(text) - 1
    while left < right:
        while left < right and not text[left].isalnum():
            left += 1
        while left < right and not text[right].isalnum():
            right -= 1
        if text[left].lower() != text[right].lower():
            return False
        left += 1
        right -= 1
    return True


def dedupe_sorted(nums):
    """In-place dedup for a sorted list; returns new length."""
    if not nums:
        return 0
    writer = 1
    for reader in range(1, len(nums)):
        if nums[reader] != nums[reader - 1]:
            nums[writer] = nums[reader]
            writer += 1
    return writer


print(is_palindrome("A man, a plan, a canal: Panama"))  # True

Sliding window: fixed and variable widths

The sliding window turns nested loops into one pass. For a fixed window of size k, initialize the sum of the first k elements, then slide: add the incoming element, subtract the outgoing one, track the maximum. Maximum average subarray is the textbook instance, and the incremental update is the whole trick โ€” recomputing each window from scratch is the mistake that turns an O(n) solution into O(nk).

Variable windows power the harder relatives. Longest substring with at most k distinct characters expands the right edge and shrinks the left edge while the constraint is violated, maintaining a character-count dict. Minimum window substring tracks how many required characters have been satisfied and shrinks aggressively once the window is complete, remembering the best answer. When you present these, describe the invariant โ€” what is guaranteed true about the window at each step โ€” because that is what the interviewer is listening for.

python
def max_average(nums, k):
    """Fixed window: O(n) time, O(1) space."""
    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 / k


def longest_k_distinct(text, k):
    """Variable window with a count dict: O(n) time."""
    if k == 0:
        return 0
    counts = {}
    start = best = 0
    for end, char in enumerate(text):
        counts[char] = counts.get(char, 0) + 1
        while len(counts) > k:
            head = text[start]
            counts[head] -= 1
            if counts[head] == 0:
                del counts[head]
            start += 1
        best = max(best, end - start + 1)
    return best


print(max_average([1, 12, -5, -6, 50, 3], 4))  # 12.75
print(longest_k_distinct("eceba", 2))  # 3

Stack: matching, nesting, and monotonic order

Stacks appear whenever structure nests or recent context matters. Valid parentheses is the introduction: push opening brackets, pop and compare on every closing bracket, and finish with an empty stack. The daily-temperatures problem upgrades the idea to a monotonic stack of indices: while the current temperature exceeds the temperature at the stack's top index, pop and record the gap. Each index is pushed and popped at most once, so the whole scan is O(n) โ€” the same engine behind next-greater-element and largest-rectangle variants. Name that amortized argument out loud; interviewers listen for the at-most-once charging.

The min-stack follow-up asks for O(1) retrieval of the minimum. Pair the main stack with a second stack of running minima, pushing a new minimum exactly when a value is less than or equal to the current one. Queue-using-two-stacks is the reverse exercise: amortized O(1) by draining the input stack into the output stack only when the output is empty. Both appear often enough to deserve muscle memory.

python
def valid_parentheses(text):
    """Classic matching with a stack: O(n) time and space."""
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for char in text:
        if char in pairs:
            if not stack or stack[-1] != pairs[char]:
                return False
            stack.pop()
        else:
            stack.append(char)
    return not stack


def daily_temperatures(temps):
    """Monotonic stack of indices: O(n)."""
    result = [0] * len(temps)
    stack = []
    for i, temp in enumerate(temps):
        while stack and temp > temps[stack[-1]]:
            prev = stack.pop()
            result[prev] = i - prev
        stack.append(i)
    return result


print(valid_parentheses("()[]{}"))  # True
print(daily_temperatures([73, 74, 75, 71, 69, 72, 76]))  # [1, 1, 4, 2, 1, 1, 0]

Complexity recap and the follow-up ladder

Before you submit, state the complexity and check it against the constraints โ€” an O(nยฒ) solution on 10โด elements is fine, on 10โต it is not. The table below is the quick reference to keep in your head during the round.

PatternSignature in the problem statementTimeSpace
Hash mapPairs, anagrams, frequencies, seen-beforeO(n)O(n)
Two pointersSorted input, pair sums, in-place editsO(n) or O(n log n) with sortO(1)
Sliding windowLongest/shortest substring with a constraintO(n)O(k)
StackNested structure, next greater, undo orderO(n)O(n)

Expect the ladder of extensions: from one pair to all pairs, from fixed window to variable window, from sorted input to unsorted, from returning indices to returning values, from ASCII to Unicode. Answer each by re-stating the complexity implication โ€” adding all pairs usually keeps O(n) time but requires careful duplicate skipping; switching to unsorted may add a sort. Candidates who treat follow-ups as part of the problem, not interruptions, are the ones who pass. If you blank on a variation, re-derive it from the base pattern rather than guessing; talking through the derivation is itself graded.

Common Mistakes

Writing nested loops before checking whether sorting plus pointers would be linear

Fix: Scan for the sorted-input hint first; mention the O(nยฒ) baseline, then optimize

Recomputing a window sum from scratch at every position

Fix: Slide incrementally: add the new element, subtract the old one

Forgetting to reset or delete zero-count entries in a window dict

Fix: Remove keys at zero so the distinct-count loop terminates correctly

Returning before verifying the empty stack or exhausted pointer conditions

Fix: Walk the edge cases โ€” empty input, single element, all duplicates โ€” before coding

Best Practices

  • Name the pattern out loud before writing a line of code
  • State time and space complexity up front, then check it against the constraint magnitude
  • Code the empty-input case first; it forces you to think about bounds
  • Ask whether the input is sorted, mutable, and ASCII-only โ€” the answers change your approach

Interview Questions

Q1: How would you modify Two Sum to return all unique pairs?

Sort the array, use two pointers, and on a match record the pair then advance both pointers past duplicates; skip repeated starting values to avoid duplicate pairs.

Q2: Explain the time complexity of Kadane's algorithm.

It maintains the best subarray ending at each index in one pass with two variables, giving O(n) time and O(1) space; the recurrence is current = max(x, current + x).

Q3: When is a hash map better than two pointers?

When the input is unsorted or when you need membership and counts rather than pair elimination. Two pointers win on sorted inputs when you want O(1) extra space.

Q4: How do you handle duplicates in top-k frequent elements?

Counter handles frequencies naturally; bucket sort by frequency into an array of lists gives O(n) without a custom heap, then take the top k buckets.

Q5: Trade-offs between sliding window and two pointers?

Sliding window is two pointers plus an aggregate state for constraint tracking. If the problem has no window constraint, plain two pointers is simpler; if it does, the window state is what makes the linear scan possible.

Key Takeaways

  • Most easy problems are hash map, two pointers, sliding window, or stack
  • State complexity before coding and revise it when constraints change
  • Fixed windows slide with incremental sums; variable windows shrink on violation
  • Monotonic stacks give next-greater logic in one O(n) pass
  • Edge cases and follow-up variants are part of the problem โ€” treat them that way
๐Ÿ”’

Premium Content

Easy Coding Patterns: Arrays, Strings, and Stacks

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement