Bird
Raised Fist0
Interview Prepknowing-what-to-trackmediumAmazonFacebookGoogle

Find All Anagrams in a String

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize result list and check input lengths

Create an empty list to store results. Check if pattern length is greater than string length; if so, return empty list immediately.

💡 This step ensures we don't waste time processing impossible cases and prepares the result container.
Line:res = [] if len(p) > len(s): return res
💡 Early termination avoids unnecessary work when pattern is longer than string.
📊
Find All Anagrams in a String - Watch the Algorithm Execute, Step by Step
Watching the algorithm step-by-step reveals how frequency tracking and match counting work together to efficiently find all anagrams without redundant checks.
Step 1/20
·Active fill★Answer cell
check
empty map
Result: []
insert
empty map
Result: []
insert
a→1
b→1
c→1
Result: []
insert
c→1
b→1
a→1
Result: []
check
a→1
b→1
c→1
Result: []
check
empty map
Result: [0]
increment
Lookup: e→ 1
e→1lookup
Result: [0]
decrement
Lookup: c→ 0
c→0lookup
Result: [0]
check
empty map
Result: [0]
increment
Lookup: b→ 2
b→2lookup
Result: [0]
decrement
Lookup: b→ 1
b→1lookup
Result: [0]
check
empty map
Result: [0]
increment
Lookup: a→ 2
a→2lookup
Result: [0]
decrement
Lookup: a→ 1
a→1lookup
Result: [0]
check
empty map
Result: [0]
increment
Lookup: b→ 2
b→2lookup
e→0
Result: [0]
check
empty map
Result: [0]
increment
Lookup: a→ 2
a→2lookup
Result: [0]
decrement
Lookup: b→ 1
b→1lookup
Result: [0]
check
empty map
Result: [0,6]

Key Takeaways

✓ Tracking frequency counts with fixed-size arrays allows constant-time updates and comparisons.

This insight is hard to see from code alone because the arrays abstract away character details, but visualization shows exact counts changing.

✓ The matches count efficiently summarizes how many characters currently match frequency, avoiding full array comparisons each step.

Understanding matches count is easier when watching it increment and decrement visually rather than reading conditional logic.

✓ Sliding the window by adding and removing characters updates frequencies and matches, enabling detection of anagrams without rechecking entire substrings.

Seeing each character enter and leave the window clarifies why the algorithm is efficient and how it maintains correctness.

Practice

(1/5)
1. Given the following Python code implementing the optimal approach for longest consecutive sequence, what is the value of max_len returned when the input is [1, 9, 3, 10, 4, 20, 2]?
def longestConsecutive(nums):
    num_set = set(nums)
    max_len = 0
    for num in num_set:
        if num - 1 not in num_set:
            current = num
            length = 1
            while current + 1 in num_set:
                current += 1
                length += 1
            max_len = max(max_len, length)
    return max_len
easy
A. 5
B. 4
C. 3
D. 2

Solution

  1. Step 1: Identify sequence starts

    Numbers without predecessor: 1 (0 not in set), 9 (8 not in set), 20 (19 not in set).
  2. Step 2: Trace sequences from starts

    From 1: sequence is 1,2,3,4 -> length 4; from 9: 9,10 -> length 2; from 20: 20 -> length 1. Max length is 4.
  3. Step 3: Re-examine carefully

    Check if 1,2,3,4 is the longest. Actually, 1,2,3,4 is length 4, but 1,2,3,4,5 is not present. So max length is 4.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Longest consecutive sequence length is 4 [OK]
Hint: Only count sequences starting at numbers without predecessor [OK]
Common Mistakes:
  • Counting sequences from every number
  • Off-by-one in length calculation
  • Ignoring duplicates
2. Given an integer array and a target sum, you need to find the number of continuous subarrays whose sum equals the target. Which approach guarantees an optimal solution with linear time complexity?
easy
A. Use dynamic programming to store the count of subarrays ending at each index with sum equal to the target.
B. Use a sliding window technique to expand and shrink the window until the sum matches the target.
C. Maintain a running prefix sum and use a hash map to count how many prefix sums have occurred that satisfy the sum condition.
D. Check all possible subarrays using nested loops and sum each subarray to check if it equals the target.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires counting subarrays with sum equal to k, including negative numbers, so sliding window (which requires non-negative numbers) is not reliable.
  2. Step 2: Identify the optimal approach

    Using prefix sums and a hash map allows constant-time lookups of how many prefix sums satisfy the condition, achieving O(n) time.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sliding window fails with negatives; brute force is O(n²); DP approach is not standard here. [OK]
Hint: Prefix sums + hash map handle negatives efficiently [OK]
Common Mistakes:
  • Assuming sliding window works with negative numbers
  • Thinking DP is needed for counting subarrays
  • Believing brute force is optimal
3. Consider the following code snippet for finding the longest subarray with equal number of 0s and 1s. What is the value of max_length after processing the input [0, 1, 0, 1]?
easy
A. 3
B. 4
C. 2
D. 1

Solution

  1. Step 1: Trace prefix sums and first_occurrence updates.

    For input [0,1,0,1], prefix sums are: -1, 0, -1, 0 with offset indexing.
  2. Step 2: Update max_length when prefix sum repeats.

    At i=1, prefix_sum=0 repeats at index -1 -> length=2; at i=3, prefix_sum=0 repeats again -> length=4.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Longest balanced subarray is entire array length 4 [OK]
Hint: Prefix sum repeats indicate balanced subarray [OK]
Common Mistakes:
  • Off-by-one in length calculation
  • Confusing prefix sum indexing
  • Ignoring initial prefix sum at -1
4. The following code attempts to find the longest subarray with equal number of 0s and 1s. What is the subtle bug causing incorrect results on some inputs?
medium
A. Missing initialization of first_occurrence[offset] = -1 before the loop
B. Incorrect prefix_sum update: should add 1 for 0 and -1 for 1
C. Updating max_length before checking if prefix_sum exists in first_occurrence
D. Using -2 as initial value in first_occurrence instead of -1

Solution

  1. Step 1: Check initialization of first_occurrence array.

    It must have first_occurrence[offset] = -1 to handle subarrays starting at index 0.
  2. Step 2: Without this initialization, subarrays starting at index 0 are missed.

    This causes off-by-one errors and underestimation of max_length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Bug causes failure on inputs where balanced subarray starts at index 0 [OK]
Hint: Initialize prefix sum 0 at index -1 to avoid off-by-one [OK]
Common Mistakes:
  • Not initializing prefix sum 0 index
  • Confusing prefix sum updates
  • Wrong initial values in array
5. Suppose the problem is modified so that the input array can contain duplicate numbers and you want to find the length of the longest consecutive sequence considering duplicates as separate elements (e.g., [1,2,2,3] counts as length 4). Which modification to the optimal hash set approach correctly handles this variant?
hard
A. Use a hash map to store counts of each number and sum counts for consecutive numbers to find the longest run.
B. Use the original hash set approach but multiply the length by the count of duplicates for each number.
C. Sort the array and count consecutive runs including duplicates by scanning linearly.
D. Ignore duplicates and apply the original hash set approach since duplicates don't affect sequence length.

Solution

  1. Step 1: Understand the variant

    Duplicates count as separate elements, so sequences can include repeated numbers increasing length.
  2. Step 2: Evaluate approaches

    Original hash set approach ignores duplicates; multiplying length by counts is incorrect because duplicates may be non-consecutive; sorting and scanning works but is O(n log n).
  3. Step 3: Correct approach

    Using a hash map to store counts allows summing counts of consecutive numbers to find the longest run including duplicates efficiently.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Hash map counting handles duplicates correctly and efficiently [OK]
Hint: Count duplicates explicitly using a hash map [OK]
Common Mistakes:
  • Ignoring duplicates
  • Multiplying length by counts incorrectly
  • Assuming sorting is always best
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard