DSA
Master Array/Matrix Manipulation Patterns: 7 templates for Coding Interviews
Master 7 array/matrix manipulation patterns techniques used in Google, Amazon, and Meta interviews.

You've spent hours brute-forcing array questions. You finally memorize the steps for "Rotate Image," only to freeze when the interviewer tweaks the input. Or maybe you ace "Set Matrix Zeroes" in isolation, but on interview day, you’re thrown by a spiral traversal variation you’ve never seen before.
Sound familiar? You’re not alone. Most engineers hit this wall—where memorization breaks down and every slight twist feels like a brand-new puzzle. The more you grind LeetCode, the more you realize that real interviews are about flexibility, not rote recall.
Here’s the secret: Top engineers don’t just memorize 200+ solutions. They master patterns. Once you see the underlying array/matrix manipulation patterns, you can deconstruct almost any FAANG question—no matter how it’s disguised. In fact, over 20% of Google, Amazon, and Meta array/matrix questions can be solved with just 7 core manipulation templates.
What You'll Learn
By the end of this guide, you'll master:
✅ The 7 array/matrix manipulation sub-patterns essential for interviews
✅ Pattern recognition skills to crack any array or matrix question
✅ 18 curated practice problems from Google, Amazon, Meta, and more
✅ When to use each pattern with mental models and triggers
✅ Common pitfalls (and how to avoid them)
✅ A step-by-step practice roadmap for 2-3 weeks
What is Array/Matrix Manipulation Patterns?
Imagine your data structure as a Rubik’s Cube. There are seemingly infinite moves you can make, but only a handful of algorithms that solve the puzzle efficiently, no matter how it’s scrambled. Array/Matrix Manipulation Patterns work the same way: they’re the “algorithms” that unlock any array or matrix transformation—rotation, rearrangement, marking, or traversal—no matter the question’s twist.
Core Insight
The power isn’t in memorizing how to “rotate a matrix” or “find a missing number.” It’s in recognizing which manipulation pattern is needed, then flexibly applying it—even when the problem’s surface details change.
Why This Pattern Matters
- Universality: These patterns appear in over 20% of FAANG array/matrix interviews.
- Optimization: They turn O(n²) brute-force solutions into O(n) or O(1) space-efficient algorithms.
- Signal: Mastery of these patterns signals to interviewers that you understand systems thinking—not just code.
- Real-World Utility: These are the same skills used in search engines (Google), newsfeeds (Meta), logistics (Amazon), and more.
Companies that frequently ask these: Google, Amazon, Meta, Microsoft, Apple, Facebook, Bloomberg, Uber, Citadel, Docusign, Oracle, ByteDance, Adobe, Spotify, Walmart Labs, Expedia, Intuit, Lyft, Paypal, Dropbox, Reddit.
The 7 Array/Matrix Manipulation Patterns Sub-Patterns
Let’s break down the seven essential sub-patterns, each with detailed insights, real interview problems, code templates, and pro tips.
1. Array - Cyclic Sort
What it is
Cyclic Sort is an in-place pattern for dealing with arrays where numbers are within a known range (typically 1 to n). The core idea is to “cycle” each number into its correct index, often revealing missing or duplicate values in the process.
Key insight
By ensuring that every value is placed at the index corresponding to its value (nums[i] == i + 1), discrepancies (missing, duplicate, or misplaced items) become instantly obvious. This avoids extra space and repeated scanning.
How it works
- Iterate through the array.
- For each index, while the value isn’t at its “home,” swap it with the value at its correct place.
- After this process, any mismatch between index and value marks an anomaly (e.g., missing number, duplicate).
When to use
- The array contains numbers in the range
[1, n]. - Asked to find missing or duplicate numbers without using extra space.
- Problems where “rearrange in-place” is possible and beneficial.
- Interviewers specify O(1) space or in-place constraints.
Recognition triggers
- “Find the missing/duplicate/first missing positive integer.”
- Input array is unsorted but contains a known range of values.
- Asked for O(n) time and O(1) space.
Essential Problems
Easy:
- Find All Numbers Disappeared in an Array — Amazon
Context: Identify all numbers missing from[1, n]in O(n) time.
Medium:
- Find All Duplicates in an Array — Amazon, Facebook, Microsoft, Bloomberg, Docusign ⭐
Context: Find all elements appearing twice, in-place.
Hard:
- First Missing Positive — Microsoft, Amazon, Facebook, Google, Oracle ⭐
Context: Return the smallest missing positive integer in O(n) time and O(1) space.
💡 Pro Tip
When numbers are in [1, n], use the value as an index. Cyclically swap until every value is in place—don’t increment the index after a swap, since the new value at i may also need to be moved.
⚠️ Common Mistake
Pitfall: Skipping the next index immediately after a swap.
Why: You might miss numbers that still need to be sorted.
How to avoid: Only increment the index when the correct value is in place.
Example Code Pattern
PYTHON
Time/Space Complexity
- Time: O(n)
- Space: O(1)
2. In-place Rotation
What it is
In-place rotation manipulates arrays or matrices (2D arrays) by shifting or rotating elements without using extra space. It includes both 1D rotations (like rotating a list to the right) and 2D matrix rotations (90 degrees, transpose, etc.).
Key insight
By reversing sections or swapping elements layer by layer, you can achieve the transformation with no additional memory. For matrices, the “transpose + reverse” trick is especially powerful.
How it works
- Array rotation: Reverse the whole array, then reverse each sub-section.
- Matrix rotation: Transpose (swap rows/columns), then reverse each row (or column).
When to use
- Need to rotate or transpose a matrix/array in-place.
- Constraints specify O(1) extra space.
- Interviewers mention “rotate,” “shift,” or “transpose.”
Recognition triggers
- “Rotate array by k steps to the right/left.”
- “Rotate image/matrix by 90 degrees.”
- “Transpose the matrix.”
Essential Problems
Easy:
- Transpose Matrix — Apple, Microsoft, Nvidia, Citadel
Context: Swap rows/columns of a matrix in-place.
Medium:
- Rotate Array — Microsoft, Apple, Amazon ⭐
Context: Rotate array right by k steps, O(1) space. - Rotate Image — Amazon, Microsoft, Apple, Uber, Cisco ⭐
Context: Rotate an n x n matrix by 90° in place.
💡 Pro Tip
For matrix rotation, always visualize the process as “layers” or “rings.” Process one layer at a time, swapping four elements in a cycle. For 1D array rotation, the triple-reverse technique is almost always optimal for O(1) space.
⚠️ Common Mistake
Pitfall: Re-using extra arrays for rotation.
Why: This violates the O(1) in-place constraint.
How to avoid: Master the reverse and transpose tricks; always check if you can swap in-place.
Example Code Pattern
PYTHON
Time/Space Complexity
- Time: O(n²) for matrix, O(n) for array
- Space: O(1)
3. Merge Sorted Array (In-place from End)
What it is
Given two sorted arrays (often A and B), merge them into one sorted array in-place, starting from the end to avoid overwriting useful data.
Key insight
By merging from the back, you can fill the larger array without needing extra space—since the end positions are guaranteed to be empty and safe to write into.
How it works
- Set pointers at the end of both arrays (and the end of the destination array).
- Compare elements, placing the larger value at the end.
- Move pointers backward, filling in-place until done.
When to use
- Merging two sorted arrays/lists, with extra space at the end of one.
- In-place constraints (no extra buffer).
- “Merge” appears in the question, with sorted data.
Recognition triggers
- “Given two sorted arrays... merge into one sorted array in-place.”
- “Do not use extra space.”
- “Modify nums1 in-place.”
Essential Problems
Easy:
- Merge Sorted Array — Facebook, Microsoft, Amazon, Bloomberg, Walmart Labs ⭐
Context: Classic test of in-place merging skills.
💡 Pro Tip
Work from the end of the array to avoid overwriting elements that haven’t been compared yet. Always check for edge cases where the second array is exhausted first.
⚠️ Common Mistake
Pitfall: Merging from the start and overwriting useful data.
Why: You lose elements that are not yet merged.
How to avoid: Always use backward pointers—start from the last index!
Example Code Pattern
PYTHON
Time/Space Complexity
- Time: O(m + n)
- Space: O(1)
4. Plus One (Handling Carry)
What it is
This pattern handles digit-wise operations on arrays, specifically when you need to simulate addition (with carry) as you would by hand.
Key insight
You process the array from the end (least significant digit), propagating the carry forward as needed. This avoids converting the entire array to an integer and back, ensuring O(n) time and O(1) space.
How it works
- Start from the end of the array.
- Add the target value (usually one) and handle the carry if the sum is 10 or more.
- If a carry remains after the loop, insert it at the front.
When to use
- Addition or subtraction on arrays of digits.
- “Plus one,” “add to array-form,” or “simulate addition.”
- No integer overflow—arrays can be very large.
Recognition triggers
- “Given an array representing a non-negative integer... add one.”
- “Array form of integer.”
- “Handle carry across digits.”
Essential Problems
Easy:
- Plus One — ByteDance, Facebook, Adobe, Amazon, Spotify ⭐
Context: Add one to an integer represented as an array. - Add to Array-Form of Integer — Facebook
Context: Add a number to an array-form integer.
💡 Pro Tip
Think like you’re adding by hand: right to left, digit by digit. For “Add to Array-Form,” keep carrying as long as there’s a carry or digits left.
⚠️ Common Mistake
Pitfall: Forgetting to insert a new digit if there’s a leftover carry (e.g., [9,9,9] → [1,0,0,0]).
How to avoid: After processing all digits, check if carry > 0 and prepend it.
Example Code Pattern
PYTHON
Time/Space Complexity
- Time: O(n)
- Space: O(1) or O(n) if a new digit is added
5. Product Except Self (Prefix/Suffix Products)
What it is
Given an array, return a new array such that each element at index i is the product of all numbers except nums[i], without using division. The trick is to use prefix (left) and suffix (right) products.
Key insight
You can compute all left products in one pass, then all right products in another, multiplying as you go. This avoids division and ensures O(n) time, O(1) space (if output array not counted).
How it works
- Build an output array with left products.
- Traverse from the end, keeping a running right product, and multiply as you go.
When to use
- Asked to compute products of all elements except self, no division allowed.
- O(n) time and constant space (not counting the output).
- Interviewer hints at “prefix/suffix products.”
Recognition triggers
- “Return an array where each element is the product except self.”
- “No division allowed.”
- “O(n) time, constant space.”
Essential Problems
Medium:
- Product of Array Except Self — Facebook, Amazon, Apple, Asana, Lyft ⭐
Context: Classic prefix/suffix product interview staple. - Longest Mountain in Array — Amazon, Paypal
Context: Uses similar prefix/suffix logic to identify increasing/decreasing sequences.
💡 Pro Tip
Don’t forget to initialize your “left” and “right” products to 1. For constant space, re-use the output array for one of the passes.
⚠️ Common Mistake
Pitfall: Forgetting to process both left and right passes.
Why: Only computing one direction misses the full product.
How to avoid: Always implement two passes—one left-to-right, one right-to-left.
Example Code Pattern
PYTHON
Time/Space Complexity
- Time: O(n)
- Space: O(1) extra (output array not counted)
6. Set Matrix Zeroes (In-place Marking)
What it is
When an element in a matrix is zero, set its entire row and column to zero—in-place. The challenge is to avoid using extra space while not corrupting original data during traversal.
Key insight
Use the first row and column as markers to record which rows/columns should be zeroed. Carefully process in two passes: first to mark, second to zero.
How it works
- Detect if first row/column should be zeroed.
- For each cell, if it’s zero, mark the corresponding row/column in the first row/column.
- In a second pass, zero out cells based on markers.
- Finally, zero the first row/column if needed.
When to use
- Set entire rows/columns to zero based on a single cell.
- In-place, constant space required.
- “Marking” or “flagging” constraints.
Recognition triggers
- “If an element is zero, set its entire row and column to zero, in-place.”
- “Constant space.”
- “No extra matrix allowed.”
Essential Problems
Medium:
- Set Matrix Zeroes — Facebook, Microsoft, Oracle, Amazon, Expedia ⭐
Context: Classic in-place marking interview question. - Game of Life — Dropbox, Amazon, Reddit, Opendoor, Microsoft
Context: Marking next state in-place with markers. - Diagonal Traverse — Facebook, Amazon
Context: Traverse matrix diagonally, sometimes marking visited.
💡 Pro Tip
Always check separately if the first row/column needs zeroing—since they’re used as markers, you don’t want to corrupt your flags.
⚠️ Common Mistake
Pitfall: Zeroing out cells on the first pass, corrupting your markers.
How to avoid: Always mark first, then zero in a separate pass.
Example Code Pattern
PYTHON
Time/Space Complexity
- Time: O(mn)
- Space: O(1)
7. Spiral Traversal
What it is
Spiral Traversal involves visiting all elements of a matrix in a spiral (layer-by-layer) order—starting from the outer layer and moving inward.
Key insight
By defining boundaries (top, bottom, left, right) and moving in four directions, you can traverse the entire matrix without repeating elements or using extra space.
How it works
- Define four boundaries: top, bottom, left, right.
- Move in four directions: left→right, top→bottom, right→left, bottom→top.
- After each direction, adjust the appropriate boundary.
- Continue while boundaries are valid.
When to use
- Asked for spiral order, spiral filling, or spiral traversal.
- Need to fill or read a matrix layer by layer.
- Interviewer wants O(mn) time, no extra matrix.
Recognition triggers
- “Traverse matrix in spiral order.”
- “Fill matrix in spiral order.”
- “Return elements in spiral path.”
Essential Problems
Medium:
- Spiral Matrix III — Facebook
- Spiral Matrix — Microsoft, Apple, Intuit, Facebook, Google ⭐
Context: Return elements in spiral traversal. - Spiral Matrix IV
- Spiral Matrix II — Microsoft ⭐
Context: Fill n x n matrix in spiral order with 1...n².
💡 Pro Tip
Think in terms of shrinking rectangles. After each layer, update your boundaries. Always check if your updated boundaries are still valid before continuing to the next loop.
⚠️ Common Mistake
Pitfall: Off-by-one errors on boundaries (e.g., skipping or repeating elements).
How to avoid: Carefully update and check all four boundaries after each direction.
Example Code Pattern
PYTHON
Time/Space Complexity
- Time: O(mn)
- Space: O(1) extra (output array not counted)
How to Master Array/Matrix Manipulation Patterns on Thita.ai
Ready to put these patterns into practice? Thita.ai is built to accelerate your mastery:
- Pattern-Based Problem Sets: Tackle the Array/Matrix Manipulation Patterns Sheet for focused, high-yield practice.
- AI Hints & Instant Feedback: Solve on Code Practice—get stepwise AI hints, error explanations, and code review instantly.
- Real Interview Simulation: Try AI Interview for realistic whiteboard rounds and behavioral coaching.
- Track Your Progress: Monitor strengths and weaknesses on your Dashboard.
- Technical Coaching: Get personalized feedback and next steps from your AI Coach.
Your Array/Matrix Manipulation Patterns Learning Roadmap
Estimated commitment: 10-12 hours over 2-3 weeks
Week 1: Foundations
Goal: Familiarize with core manipulation types using easy problems.
-
Day 1:
- Find All Numbers Disappeared in an Array
- Plus One
(Focus: cyclic sort basics, handling carries)
-
Day 2:
- Merge Sorted Array
- Transpose Matrix
(Focus: in-place merge, 2D array basics)
-
Day 3-4:
- Add to Array-Form of Integer
- Rotate Array
(Focus: array rotation, addition in array-form)
Week 2: Intermediate
Goal: Build proficiency on medium-difficulty and multi-step patterns.
-
Day 5-6 (Cyclic Sort & In-place Rotation):
-
Day 7-8 (Set Matrix Zeroes & Product Except Self):
-
Day 9 (Spiral & Diagonal Traversal):
Week 3: Mastery
Goal: Tackle the hardest variants, mixed practice, and timed challenges.
-
Day 10-12 (Hard + Advanced):
-
Day 13-14 (Mixed + Timed):
- 5 random mixed-problem sets from Pattern Sheet
- 1-2 rounds on AI Interview (timed, with feedback)
Recommended daily investment: ~40-60 minutes
Common Array/Matrix Manipulation Patterns Pitfalls
⚠️ 1. Forgetting to Check for Out-of-Bounds on Swaps
Problem: In cyclic sort or rotation, swapping without checking if index is valid can cause IndexError, especially with out-of-range values.
Solution: Always validate the swap index (e.g., 1 <= nums[i] <= n) before swapping.
PYTHON
⚠️ 2. Zeroing Rows/Columns Too Early in Set Matrix Zeroes
Problem: Setting cells to zero during the first pass corrupts your markers, causing incorrect results.
Solution: Use first row/column as markers, only zero in the second pass.
⚠️ 3. Off-by-One Errors in Spiral Traversal
Problem: Not updating boundaries (top, bottom, left, right) carefully, leading to elements being skipped or revisited.
Solution: After each direction, double-check the updated boundary. Use print-debugging if needed.
⚠️ 4. Overwriting Useful Data in In-Place Merge
Problem: Merging from the start overwrites elements that are not yet compared.
Solution: Always merge from end-to-start when working in-place.
⚠️ 5. Not Handling Carry at the Highest Digit
Problem: In “Plus One,” forgetting to add a new digit if there’s a leftover carry (e.g., [9,9,9] should become [1,0,0,0]).
Solution: After processing all digits, check if carry remains and insert as needed.
⚠️ 6. Skipping Index After Swap in Cyclic Sort
Problem: Incrementing the index after a swap can skip unsorted values.
Solution: Only increment if the current index holds the correct value.
⚠️ 7. Misusing Output Array in Product Except Self
Problem: Not initializing or incorrectly updating the output array during prefix/suffix passes.
Solution: Initialize to 1 and multiply in both passes.
Why Array/Matrix Manipulation Patterns Beat Brute Force
Let’s consider Set Matrix Zeroes:
Brute Force Approach
- For each zero, record all affected rows and columns in extra sets.
- Then zero all corresponding rows and columns.
- Time: O(mn)
- Space: O(m + n) extra
PYTHON
Optimized Pattern Approach (In-place Marking)
- Use first row/col as in-place markers.
- Only O(1) space.
- Time: O(mn)
- Space: O(1)
PYTHON
Key Insight:
By cleverly marking via the input matrix, you avoid extra storage and achieve true in-place O(1) space. This is critical for large datasets and is the level of optimization interviewers expect at top companies.
When This Matters Most:
- Large matrices where extra space is prohibitive.
- Interviewers specify in-place or O(1) space.
- Real production systems where memory is limited.
Beyond LeetCode: Real-World Applications
1. Image Processing (Google, Facebook, Instagram)
Matrix rotation and transpose are at the heart of image transformations—think rotating profile pictures, or fast image filtering. In-place operations save memory and speed up pipelines.
2. Database Row/Column Operations (Amazon, Microsoft, Oracle)
Setting entire rows/columns to zero (or null) is similar to marking invalid data in a table—essential for error correction and data cleansing.
3. Search Engines & Recommender Systems (Google, Netflix)
Spiral, diagonal, and other traversal patterns are used in ranking matrices, proximity searches, or filling recommendation grids—where layer-based access optimizes performance.
4. Financial Data Analysis (Bloomberg, Citadel)
Prefix/suffix products accelerate cumulative calculations in trading systems—like quickly recalculating portfolio values minus a given asset.
5. Distributed Systems (Amazon, Meta)
Efficiently merging sorted streams, or detecting missing/duplicate IDs in logs, uses cyclic sort and merge patterns at scale. For mastering these core data structure and algorithm patterns, consider following a comprehensive beginner to advanced DSA roadmap to build a strong foundation.
Conclusion: From Memorization to Mastery
Mastering Array/Matrix Manipulation Patterns is about unlocking a toolkit of flexible, reusable strategies. Don’t just memorize solutions—cultivate the ability to recognize and adapt the core patterns. This is what separates top-tier engineers from the rest.
Next steps:
- Practice with the Pattern Sheet—solidify every subpattern.
- Get AI-powered hints on Code Practice—never get stuck for long.
- Simulate real interviews on AI Interview—build confidence under pressure.
- Track progress and get feedback from your Dashboard and AI Coach.
For a broader perspective on how AI is revolutionizing interview preparation, explore How AI Is Changing Technical Interviews in 2026 to understand the future of coding interviews.
Final thought:
Patterns are the language of problem solving. Learn them, and you’ll never be lost—even when the question is brand new.
Related Articles
- Master Two Pointer Patterns: 7 templates for Coding Interviews
- Best AI Interview Prep Tools for 2026
- DSA Patterns Sheet
- Thita.ai AI Interview Platform
External Resources
Ready to Master Array/Matrix Patterns?
Thita.ai empowers you to go beyond memorization—offering AI-powered hints, instant code review, and real interview simulation. Join a community of engineers who are landing offers at Google, Amazon, Meta, and beyond.
Start your transformation today: Sign up for free →