Let’s walk through both patterns properly, with clear problems, complete code, and sharper insights, especially the mistakes that actually cost marks in interviews.
Table of Contents
Binary Search Pattern
Binary Search is a technique used to find an element in a sorted array by repeatedly dividing the search space into halves.Key Idea
At every step, you eliminate half of the remaining elements based on comparison.
Features of Binary Search
- Works Only on Sorted Data: Binary search assumes the data is sorted; otherwise, the logic breaks completely.
- Logarithmic Efficiency: The time complexity is O(log n), making it extremely efficient for large inputs.
- Uses Two Pointers: It relies on left and right pointers to shrink the search space.
Problem 1: Search Element in Sorted Array
You are given a sorted array of integers and a target value. Return the index of the target if it exists, otherwise return -1.
// C++ program to search element in
// a sorted array
#include iostream
using namespace std;
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left = right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
// Main function
int main()
{
int arr[] = {1, 3, 5, 7, 9};
int n = 5;
int target = 7;
int result = binarySearch(arr, n, target);
if (result != -1)
cout "Element found at index: " result;
else
cout "Element not found";
return 0;
}
Output:
Explanation:Element found at index: 3
The algorithm compares the target with the middle element. If it’s smaller, it moves left; if larger, it moves right. This continues until the element is found or the range becomes empty.
Binary Search Variations Table
| Variation | Description |
|---|---|
| First Occurrence | This variation finds the first position where the target appears by continuing the search on the left side even after finding a match. |
| Last Occurrence | This variation finds the last position by continuing the search on the right side after a match. |
| Lower Bound | This variation returns the smallest index where the value is greater than or equal to the target. |
| Upper Bound | This variation returns the smallest index where the value is strictly greater than the target. |
| Search in Rotated Array | This variation handles partially sorted arrays by identifying which half is sorted before applying logic. |
Sliding Window Pattern
Sliding Window is a technique used to process a continuous range of elements efficiently.Key Idea
Instead of recalculating values for every subarray, you update results incrementally as the window moves.
Types of Sliding Window
- Fixed Size Window: The window size remains constant and slides forward.
- Variable Size Window: The window expands and shrinks based on conditions.
Problem 2: Maximum Sum Subarray of Size K
Given an array of integers and an integer k, find the maximum sum of any contiguous subarray of size k.
// C++ program to find maximum
// sum subarray of size K
#include iostream
using namespace std;
int maxSumSubarray(int arr[], int n, int k) {
int windowSum = 0;
int maxSum = 0;
for (int i = 0; i k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
for (int i = k; i n; i++) {
windowSum += arr[i];
windowSum -= arr[i - k];
maxSum = max(maxSum, windowSum);
}
return maxSum;
}
// Main function
int main()
{
int arr[] = {2, 1, 5, 1, 3, 2};
int n = 6;
int k = 3;
cout "Maximum sum: " maxSumSubarray(arr, n, k);
return 0;
}
Output:
Explanation:Maximum sum: 9
The first window is computed once. Then each step adds the next element and removes the previous one, making the computation efficient.
Problem 3: Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
// C++ program to find longest
// substring without repeating characters
#include iostream
#include unordered_set
using namespace std;
int longestSubstring(string s) {
unordered_setchar st;
int left = 0, maxLength = 0;
for (int right = 0; right s.length(); right++) {
while (st.find(s[right]) != st.end()) {
st.erase(s[left]);
left++;
}
st.insert(s[right]);
maxLength = max(maxLength, right - left + 1);
}
return maxLength;
}
// Main function
int main()
{
string s = "abcabcbb";
cout "Longest length: " longestSubstring(s);
return 0;
}
Output:
Explanation:Longest length: 3
The window expands until a duplicate appears. Then it shrinks from the left until the duplicate is removed, maintaining a valid substring.
When to Use Which Pattern
| Scenario | Technique |
|---|---|
| The data is sorted and you need fast searching | Binary Search is ideal because it reduces the search space efficiently. |
| The problem involves contiguous elements like subarrays or substrings | Sliding Window is preferred because it avoids redundant computations. |
| The input size is large and brute force is too slow | Both techniques help optimize performance significantly. |
| The problem involves maintaining a running condition | Sliding Window is useful because it dynamically adjusts the window. |
Common Mistakes
Here are some mistakes done while using binary search and slinding window:Binary Search Mistakes
- Using Binary Search on Unsorted Data: This completely breaks the logic because the assumption of ordering is violated.
- Incorrect Loop Condition: Using left right instead of left = right can skip valid elements and miss answers.
- Wrong Pointer Updates: Updating left = mid or right = mid instead of mid ± 1 can cause infinite loops.
- Overflow in Mid Calculation: Using (left + right) / 2 can overflow for large values, so always use left + (right - left) / 2.
- Stopping Too Early in Variations: In problems like first/last occurrence, returning immediately after finding the target gives wrong results.
- Not Understanding Window Type: Confusing fixed and variable window problems leads to incorrect logic.
- Forgetting to Shrink the Window: In variable window problems, not moving the left pointer properly causes invalid results.
- Incorrect Order of Operations: Adding before removing (or vice versa) in the wrong order can break the window logic.
- Using Extra Loops Unnecessarily: Sliding window should avoid nested loops; otherwise, it defeats the purpose.
- Not Maintaining Condition Properly: For example, in substring problems, failing to remove duplicates correctly leads to wrong answers.
- Off-by-One Errors in Window Size: Miscalculating right - left + 1 leads to incorrect lengths or sums.
Conclusion
What this really means is that you don’t need to master everything; you just need to master what matters. Binary search gives you speed when the data is structured. Sliding Window gives you efficiency when dealing with continuous segments.Once you start recognizing these patterns, problems stop feeling random and start feeling familiar. That’s when your preparation actually starts paying off.
Frequently Asked Questions
1. How do I know if binary search can be applied?2. Why is sliding window better than brute force?If the array is sorted or can be transformed into a monotonic condition, binary search is applicable.
3. Can sliding window be used for negative numbers?It avoids recomputing overlapping data, reducing time complexity significantly.
4. What is the most common binary search bug?Yes, but extra care is needed since sums may not behave predictably.
5. How can I master these patterns?Incorrect pointer updates that lead to infinite loops or skipped elements.
Practice multiple variations and focus on recognizing when to apply each pattern.
0 Comments