Showing posts with label interview preparation. Show all posts
Showing posts with label interview preparation. Show all posts

16 DSA Patterns for Coding Interviews: Spot the Right One

Stop Memorizing LeetCode: Master These 16 DSA Patterns

If you are preparing for coding interviews, you have probably solved—or at least seen—hundreds of LeetCode and coding problems.

But here is the problem:

Knowing how to solve 200 problems does not necessarily mean you know how to solve the next problem.

In a coding interview, the interviewer may give you a problem you have never seen before. You cannot rely on remembering the exact solution.

What you need is the ability to recognize the underlying problem-solving pattern.

For example:

  • See "longest substring" → think Sliding Window

  • See "sorted array + pair" → think Two Pointers

  • See "cycle in a linked list" → think Fast & Slow Pointers

  • See "K largest elements" → think Top K / Heap

  • See "prerequisites and dependencies" → think Topological Sort

Once you learn to recognize these patterns, many unfamiliar coding problems become much easier to approach.

This guide covers 16 important DSA patterns for coding interviews, with a simple explanation of what each pattern means, how to identify it, and an easy way to remember it.


What Are DSA Patterns?

A DSA pattern is a general problem-solving technique that can be applied to many different coding problems.

Think of a pattern as a blueprint.

You do not memorize the answer to every house. You learn how to recognize when a particular blueprint fits the house you are trying to build.

For coding interviews, this means:

Problem → Recognize the clues → Identify the pattern → Apply the technique → Adapt the solution

The goal is not to memorize 16 solutions.

The goal is to train yourself to ask:

"What pattern does this problem look like?"


1. Sliding Window

What is it?

The Sliding Window pattern is commonly used when a problem asks about a contiguous subarray or substring.

Instead of repeatedly calculating every possible range, you maintain a window and move it through the data.

How to identify it

Look for phrases such as:

  • Subarray

  • Substring

  • Contiguous

  • Consecutive

  • Longest/shortest substring

  • Maximum/minimum sum of a window

  • Window of size K

Simple example

Suppose you are asked:

Find the maximum sum of any 3 consecutive numbers.

For:

[2, 1, 5, 1, 3, 2]

You can maintain a window of 3 elements:

[2, 1, 5]

Then slide it:

[1, 5, 1]

Then:

[5, 1, 3]

And so on.

You don't need to calculate the entire sum from scratch every time.

How to remember

"Contiguous + moving range = Sliding Window."

Common interview problems

  • Maximum sum subarray of size K

  • Longest substring without repeating characters

  • Minimum Window Substring

  • Longest substring with K distinct characters


2. Two Pointers

What is it?

The Two Pointers pattern uses two indexes to move through an array or string.

It is particularly useful with sorted arrays or when working from both ends.

How to identify it

Look for:

  • Sorted array

  • Find a pair

  • Two numbers

  • Compare elements from both ends

  • Remove duplicates

  • Reverse something

  • Left/right positions

Simple example

Given:

[1, 2, 3, 4, 6]

Find two numbers that add up to 6.

Start with:

left = 1

right = 6

Their sum is 7, which is too large, so move the right pointer.

Eventually:

2 + 4 = 6

How to remember

"Two positions moving through the data = Two Pointers."

Common interview problems

  • Two Sum in a sorted array

  • 3Sum

  • Container With Most Water

  • Remove duplicates from sorted array

  • Valid Palindrome


3. Fast & Slow Pointers

What is it?

This pattern uses two pointers moving at different speeds.

Typically:

  • Slow moves one step

  • Fast moves two steps

It is especially useful with linked lists.

How to identify it

Look for:

  • Linked list

  • Cycle

  • Middle of a linked list

  • Repeated movement

  • Detect whether something loops

Simple example

Imagine:

1 → 2 → 3 → 4 → 5

The slow pointer moves one node at a time, while the fast pointer moves two.

If the linked list contains a cycle, the fast pointer will eventually meet the slow pointer.

How to remember

"One runs, one walks = Fast & Slow."

Common interview problems

  • Linked List Cycle

  • Middle of Linked List

  • Happy Number

  • Start of Linked List Cycle

  • Palindrome Linked List


4. Merge Intervals

What is it?

The Merge Intervals pattern is used when a problem contains ranges that may overlap.

For example:

[1,3] and [2,6]

overlap, so they can be merged into:

[1,6]

How to identify it

Look for:

  • Intervals

  • Start and end times

  • Meetings

  • Overlapping ranges

  • Schedules

  • Time periods

Simple example

Suppose meetings are:

[9,11]

[10,12]

[14,16]

The first two overlap.

After merging:

[9,12]

[14,16]

How to remember

"Ranges that overlap = Merge Intervals."

Common interview problems

  • Merge Intervals

  • Insert Interval

  • Meeting Rooms

  • Meeting Rooms II

  • Employee Free Time


5. Cyclic Sort

What is it?

Cyclic Sort is useful when an array contains numbers within a known range, often from 1 to N.

Instead of sorting with a traditional sorting algorithm, you place each number directly into its correct position.

How to identify it

Look for:

  • Numbers from 1 to N

  • Missing number

  • Duplicate number

  • All missing numbers

  • One incorrect number

  • Array containing values in a limited range

Simple example

Consider:

[3, 1, 5, 4, 2]

The correct arrangement is:

[1, 2, 3, 4, 5]

Each number has a natural position.

For example, 1 belongs at index 0, 2 at index 1, and so on.

How to remember

"Numbers know where they belong = Cyclic Sort."

Common interview problems

  • Find Missing Number

  • Find All Missing Numbers

  • Find Duplicate Number

  • Find the Corrupt Pair

  • First Missing Positive


6. In-Place Linked List Reversal

What is it?

This pattern reverses a linked list without creating another linked list.

For example:

1 → 2 → 3 → 4

becomes:

4 → 3 → 2 → 1

How to identify it

Look for:

  • Reverse linked list

  • Reverse a portion of a list

  • Reverse every K elements

  • Reorder linked list

  • Linked-list palindrome

How to remember

Think:

"Change the arrows, not the nodes."

You normally work with pointers such as:

  • previous

  • current

  • next

Common interview problems

  • Reverse Linked List

  • Reverse Linked List II

  • Reverse Nodes in K-Group

  • Reorder List

  • Palindrome Linked List


7. Tree BFS

What is it?

BFS (Breadth-First Search) processes a tree level by level.

For example:

        1
       / \
      2   3
     / \ / \
    4  5 6  7

BFS visits:

1 → 2 → 3 → 4 → 5 → 6 → 7

How to identify it

Look for:

  • Level order

  • Level by level

  • Each tree level

  • Zigzag levels

  • Minimum depth

  • Right-side view

What data structure is usually used?

Queue

How to remember

"BFS = Broad First = Level by Level."

Common interview problems

  • Binary Tree Level Order Traversal

  • Zigzag Level Order Traversal

  • Minimum Depth of Binary Tree

  • Binary Tree Right Side View

  • Average of Levels


8. Tree DFS

What is it?

DFS (Depth-First Search) explores a tree by going as deep as possible before coming back.

It is commonly implemented using:

  • Recursion

  • Stack

How to identify it

Look for:

  • Root-to-leaf paths

  • Path sum

  • Tree depth

  • Tree diameter

  • Explore every branch

  • Validate tree structure

Simple idea

For:

        1
       / \
      2   3
     /
    4

DFS may explore:

1 → 2 → 4

before returning and exploring the other branch.

How to remember

"DFS = Dive into a branch."

Common interview problems

  • Maximum Depth of Binary Tree

  • Path Sum

  • Binary Tree Paths

  • Diameter of Binary Tree

  • Validate Binary Search Tree


9. Two Heaps

What is it?

The Two Heaps pattern uses two heaps to divide data into two parts.

Typically:

  • Max Heap → smaller half

  • Min Heap → larger half

This makes it possible to efficiently find the median.

How to identify it

Look for:

  • Median

  • Median of a stream

  • Numbers arriving continuously

  • Balance two groups

  • Scheduling based on two sides

How to remember

"Two halves need two heaps."

Common interview problems

  • Find Median from Data Stream

  • Sliding Window Median

  • IPO

  • Maximum Capital


10. Subsets & Backtracking

What is it?

This pattern is useful when you need to generate different possible choices.

For example, given:

[1, 2, 3]

you may need to generate:

[]

[1]

[2]

[3]

[1,2]

[1,3]

[2,3]

[1,2,3]

This is often solved using backtracking.

How to identify it

Look for:

  • All possible combinations

  • All subsets

  • All permutations

  • Combinations

  • Different ways to choose

  • Generate every possibility

How to remember

"If the question asks for ALL possibilities, think Backtracking."

Common interview problems

  • Subsets

  • Permutations

  • Combinations

  • Combination Sum

  • Letter Combinations of a Phone Number


11. Modified Binary Search

What is it?

Binary Search is normally used on sorted data.

But many interview problems modify the normal structure while keeping the underlying idea of eliminating half of the search space.

For example:

[4,5,6,7,0,1,2]

is a rotated sorted array.

You can still use binary-search logic to find the answer efficiently.

How to identify it

Look for:

  • Sorted array

  • Rotated sorted array

  • Search space

  • Find minimum/maximum

  • Search in an unknown-sized sorted array

  • Find a peak

How to remember

"Sorted or almost sorted + search = Think Binary Search."

Common interview problems

  • Search in Rotated Sorted Array

  • Find Minimum in Rotated Sorted Array

  • Find Peak Element

  • Search a 2D Matrix

  • Search in an Infinite Sorted Array


12. Bitwise XOR

What is it?

XOR is a bitwise operation represented by:

^

Two useful properties are:

x ^ x = 0

and:

x ^ 0 = x

This makes XOR extremely useful for problems involving pairs, duplicates, and missing values.

Simple example

Suppose:

[4, 1, 2, 1, 2]

XOR all numbers:

4 ^ 1 ^ 2 ^ 1 ^ 2

The matching pairs cancel each other, leaving:

4

How to identify it

Look for:

  • Every number appears twice except one

  • Find the unique number

  • Missing number

  • Duplicate pairs

  • Bit manipulation

How to remember

"Same numbers cancel with XOR."

Common interview problems

  • Single Number

  • Missing Number

  • Single Number III

  • Bitwise complement problems


13. Top K Elements

What is it?

Whenever a problem asks for the top K or bottom K, a Heap/Priority Queue should come to mind.

Examples:

  • K largest

  • K smallest

  • K most frequent

  • K closest

How to identify it

Look for the words:

K largest, K smallest, K closest, K frequent, Kth largest, Kth smallest

Simple example

Given:

[10, 5, 20, 8, 30]

Find the 2 largest numbers.

Answer:

30, 20

A heap can help solve such problems efficiently.

How to remember

"See K → Think Heap."

Common interview problems

  • Kth Largest Element

  • Top K Frequent Elements

  • K Closest Points to Origin

  • K Largest Elements


14. K-Way Merge

What is it?

Use K-Way Merge when you have multiple sorted lists or arrays and need to combine or compare them efficiently.

For example:

List 1: 1, 4, 7
List 2: 2, 5, 8
List 3: 3, 6, 9

You want:

1,2,3,4,5,6,7,8,9

A Min Heap is commonly used to keep track of the smallest available element from each list.

How to identify it

Look for:

  • K sorted arrays

  • K sorted linked lists

  • Merge multiple sorted lists

  • Kth smallest across sorted lists

  • Multiple sorted sources

How to remember

"Many sorted lists → Merge with a Heap."

Common interview problems

  • Merge K Sorted Lists

  • Kth Smallest Number in Sorted Lists

  • K Smallest Pairs

  • Smallest Range Covering Elements from K Lists


15. 0/1 Knapsack & Dynamic Programming

What is it?

Dynamic Programming (DP) is used when a problem can be broken into smaller subproblems and those results can be reused.

In 0/1 Knapsack, you generally have two choices for each item:

Take it or don't take it.

For example:

Item A → Take / Skip
Item B → Take / Skip
Item C → Take / Skip

The goal is usually to maximize value or determine whether a target can be reached.

How to identify it

Look for:

  • Choose or don't choose

  • Maximum/minimum possible result

  • Target sum

  • Capacity

  • Can we make a particular sum?

  • Count the number of ways

  • Repeated subproblems

How to remember

"Make a choice, remember the result."

Common interview problems

  • 0/1 Knapsack

  • Subset Sum

  • Equal Subset Partition

  • Target Sum

  • Coin Change

  • House Robber


16. Topological Sort

What is it?

Topological Sort is used when items have dependencies or prerequisites.

Imagine:

Learn Programming
       ↓
Learn DSA
       ↓
Learn Algorithms
       ↓
Coding Interview

You cannot complete a task before its prerequisite.

Topological sorting finds a valid order for these dependent tasks.

How to identify it

Look for:

  • Prerequisites

  • Dependencies

  • Course schedule

  • Task ordering

  • Build dependencies

  • "Must be completed before"

How to remember

"Dependencies → Find the correct order."

Common interview problems

  • Course Schedule

  • Course Schedule II

  • Alien Dictionary

  • Task Scheduling

  • Build Order


How to Identify the Right DSA Pattern

This is the most important skill.

When you receive a coding interview problem, don't immediately start coding.

First, look for clues.

Step 1: What type of data are you dealing with?

Ask:

  • Array?

  • String?

  • Linked List?

  • Tree?

  • Graph?

  • Numbers?

  • Intervals?

The data structure often gives you the first clue.


Step 2: Look for keywords

Certain words should trigger certain patterns.

Problem cluePattern to consider
Subarray / substringSliding Window
ContiguousSliding Window
Sorted + pairTwo Pointers
CycleFast & Slow Pointers
Linked list reversalIn-place Reversal
Overlapping rangesMerge Intervals
Numbers from 1 to NCyclic Sort
Level by levelTree BFS
Root-to-leafTree DFS
MedianTwo Heaps
All combinationsBacktracking / Subsets
Sorted search spaceBinary Search
One number appears onceXOR
K largest/smallestTop K / Heap
Multiple sorted listsK-Way Merge
Choose / skipDynamic Programming
PrerequisitesTopological Sort

A Simple Pattern Recognition Cheat Sheet

When you're stuck in an interview, ask yourself these questions:

Is it a contiguous range?

👉 Sliding Window

Is the array sorted and I'm looking for a pair?

👉 Two Pointers

Is there a cycle?

👉 Fast & Slow Pointers

Are there overlapping time ranges?

👉 Merge Intervals

Are the numbers from 1 to N?

👉 Cyclic Sort

Am I reversing a linked list?

👉 In-Place Reversal

Do I need to process a tree level by level?

👉 Tree BFS

Do I need to explore paths deeply?

👉 Tree DFS

Do I need to continuously find a median?

👉 Two Heaps

Do I need every possible combination?

👉 Backtracking / Subsets

Is the data sorted or nearly sorted?

👉 Binary Search

Do duplicate values cancel out?

👉 Bitwise XOR

Does the question say K largest/smallest/frequent?

👉 Top K / Heap

Do I have multiple sorted lists?

👉 K-Way Merge

Do I have a take-or-skip decision?

👉 Dynamic Programming

Are there prerequisites or dependencies?

👉 Topological Sort


Don't Memorize Solutions—Recognize Patterns

The biggest mistake many coding interview candidates make is trying to memorize solutions problem by problem.

For example:

"I solved this exact LeetCode problem last month, but I don't remember the code."

That doesn't help much when the interviewer changes the question slightly.

Instead, learn the underlying pattern.

Suppose you understand Sliding Window.

You can encounter:

  • Longest substring

  • Maximum sum subarray

  • Minimum window

  • K distinct characters

These problems may look different, but the underlying approach can be similar.

The same idea applies to the other patterns.

Learn the pattern, understand why it works, and then practice variations.


How to Study These 16 Patterns

Don't try to learn all 16 in one day.

A better approach is to study them in groups.

Group 1: Arrays & Strings

  • Sliding Window

  • Two Pointers

  • Cyclic Sort

  • Modified Binary Search

  • Bitwise XOR

Group 2: Linked Lists

  • Fast & Slow Pointers

  • In-Place Reversal

Group 3: Intervals & Heaps

  • Merge Intervals

  • Two Heaps

  • Top K Elements

  • K-Way Merge

Group 4: Trees

  • Tree BFS

  • Tree DFS

Group 5: Combinations & Graphs

  • Subsets / Backtracking

  • Dynamic Programming

  • Topological Sort

For each pattern, don't just solve one problem.

Try solving 3–5 problems that use the same pattern but look different.

That's when pattern recognition starts becoming natural.


Final Takeaway

You don't need to memorize every LeetCode problem.

You need to become good at recognizing why a particular approach fits a particular problem.

The 16 patterns in this guide give you a strong foundation:

  1. Sliding Window

  2. Two Pointers

  3. Fast & Slow Pointers

  4. Merge Intervals

  5. Cyclic Sort

  6. In-Place Reversal

  7. Tree BFS

  8. Tree DFS

  9. Two Heaps

  10. Subsets & Backtracking

  11. Modified Binary Search

  12. Bitwise XOR

  13. Top K Elements

  14. K-Way Merge

  15. 0/1 Knapsack & Dynamic Programming

  16. Topological Sort

The next time you see a coding problem, don't immediately ask:

"Have I seen this exact problem before?"

Ask:

"What clues does this problem give me, and which pattern matches those clues?"

That shift—from memorizing solutions to recognizing patterns—is one of the most valuable skills you can develop for coding interviews.

Learn the pattern. Recognize the clues. Then write the solution.

Advantages of VIEW? -DBA interview

Advantages of Views
Answer :- To protect some of the columns of a table from other users. - To hide complexity of a query. - To hide complexity of calculations.

How to prepare for a interview

Interview preparation is very crucial if you want to succeed in getting a job. A planned approach can give you an edge over your competitors in this ever increasing competitive world.
Make sure you follow some of these steps before going to an interview: -
1) Write down the necessary steps required to make the job interview successful.
2) Steps that should be followed for preparation to the interview.
3) Questions that might be asked during the process of interview most probably you will asked upon your experience, project report, behavior and personality judgment questions.
4) A note of things (checklist) which should be carried to the interview.
5) Does and don’ts in the interview process which can have a desired effect on the interview.
6) Positive and negative factors or strengths and weakness of you.
7) Closing lines or a note of thank you at the end of the interview.
First let’s examine the first point: -
Steps to be taken to make the interview successful: -
Many recruiters throughout the world are always baffled because of the candidate behavior or lack of his preparation. An interview is the most important part of the candidate because it determines a candidate’s future and many of them don’t know what to say to specific questions this clearly shows lack of preparation. Never be nervous or too casual. Make yourself comfortable in the interview these are some of the notes which can help you during the interview.
1) Preparation for the interview: -
(i) Know the date and venue of the interview including directions, landmark if any, full name of the interview including the title and correct pronunciation of his name.
(ii) Have a detailed view of the company and the demands of the job position at hand.
(iii) Get knowledge about the different products which the company has and its competitors, skills you have which can further develop the product or useful to invent new ones, strengths and weakness of the company and product literature.
(iv) Find out or research about the presence of the company in other markets. Talk to users, distributors, etc and try to read about the testimonials. This will help you gain sufficient knowledge about the market of the company and its products.
(v) Make notes about how you would handle the responsibilities of the job. New strategies, plans, business plans, etc which will help you to do the job in a new way or increase the efficiency of the job.
Attire: -
1) First impression can be obtained by the way you dress and present yourself. Wear professional dress and look professional because the job demands it, there exists a fine line between the company dress code and interview dress make sure that you understand it.
2) Suit preferably of dark grey or black will look better on you. They should have a solid color.
3) Well polished leather shoes with dark colored socks.
4) Professional hair style and neatly manicured nails.
5) Belt, lower aftershave, low perfume and minimal amount of body deo.
6) Have a briefcase in which you can keep all your documents also maintain an order by which you can produce to the interview as per request.
Have a list of questions which you want to ask the interviewer. Make sure that those questions are well framed and knowledgeable. An interviewer expects questions to be asked by you. It can be that you have a complete knowledge about the company, its rules and policies, products, etc.
Never chew during the interview process because it will have negative effects on your interview. Have a mint before you go the interview. Maintain eye contact while speaking to the interviewer and if it is a group discussion make sure that you maintain eye contact with every one in the group.
Some of the common questions which will be asked during the interview are as follows they are: -
1) Tell me about your self (This question is framed in many different ways but the answer to them is the same)?
Keep it short and simple don’t over do it. Try to cover all aspects because this gives a clear but concise introduction about you to the interviewer.
2) Explain about your project technicalities and requirements?
While answering this question make sure that you refresh your memory. Explain to him in detail about the project because it can give you an edge from other competitors he will be primarily giving higher weight to technicals.
In interview be honest and give your best.
3) It is always good to ask about the prospects of your job if he says that he cannot give you an answer as he has other candidates. Tell him that if you were the only candidate would he hire you if he has reservation about your question then you need to improve on selling yourself.

c faqs

C faqs

Question1: Difference between arrays and pointers?
 Answer: Pointers are used to manipulate data using the address. Pointers use * operator to access the data pointed to by them
 Arrays use subscripted variables to access and manipulate data. Array variables can be equivalently written using pointer expression.

Question2: What is the purpose of realloc ( )?
 Answer: The function realloc (ptr,n) uses two arguments. The first argument ptr is a pointer to a block of memory for which the size is to be altered. The second argument n specifies the
new size. The size may be increased or decreased. If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc ( )
may create a new region and all the old data are moved to the new region.

Question3: What is static memory allocation and dynamic memory allocation?
Answer: Static memory allocation: The compiler allocates the required memory space for a declared variable. By using the address of operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variable has static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.

Dynamic memory allocation: It uses functions such as malloc ( ) or calloc ( ) to get memory dynamically. If these functions are used to get memory dynamically and the values returned by these functions are assigned to pointer variables, such assignments are known as dynamic memory allocation. Memory is assigned during run time.

Question4: How are pointer variables initialized?
Answer: Pointer variable are initialized by one of the following two ways
              Ø Static memory allocation
              Ø Dynamic memory allocation

Question5: What is a pointer variable?
Answer: A pointer variable is a variable that may contain the address of another variable or any valid address in the memory.

Question6: What is a pointer value and address?
Answer: A pointer value is a data object that refers to a memory location. Each memory location is numbered in the memory. The number attached to a memory location is called the address of the location.
Keywords:
difference between arrays and pointers
purpose of realloc in c
static memory allocation and dynamic memory allocation in c
pointer variable initialization in c
pointer variable in c
what is a pointer value and address in c
difference between array and pointer in c in tabular form
differentiate between array of pointers and pointers to array
relation between array and pointer in c
difference between array and pointer in c in hindi
array of pointers in c
difference between array and pointer in hindi
which of arrays or pointers are faster
difference between array and structure
static memory allocation in c geeksforgeeks
difference between static and dynamic memory allocation? - quora
advantages and disadvantages of static and dynamic memory allocation
dynamic memory allocation in c++
static memory allocation in c++ with example program
when is memory allocated and deallocated in c? answer both static and dynamic memory.
static and dynamic memory in computer organization
dynamic memory allocation in c pdf
declaration and initialization in c
how to initialize a pointer c++
accessing a variable through its pointer
pointer arithmetic in c
pointer to pointer in c
pointer and array in c
pointer operator in c
pointer assignment in c
pointer in c example
pointers in c pdf
use of pointers in c
double pointers in c
types of pointers in c
pointers in c geeks for geeks
list of c programs on pointers
pointers and arrays in c
use of pointers in c
pointers in c geeks for geeks
list of c programs on pointers
what is pointer in c++
pointers in c pdf
pointer in c example
types of pointers in c
double pointers in c