Mastering Two Pointers & Sliding Window Techniques in Coding Interviews

if you’re prepping for coding interviews, you’ve likely come across problems like:
“Find two numbers in an array that add up to a target.”
“Find the longest substring without repeating characters.”
“Find the maximum sum of a subarray of size k.”
Guess what? Most of these can be solved using two powerful techniques: Two Pointers and Sliding Window.
Let’s break them down and see how they can save you from brute force nightmares
What is the Two Pointers Technique?
This technique involves using two indices (pointers) to iterate through a data structure. It’s especially useful for:
Sorted arrays
Linked lists
Comparing elements from both ends
Example 1: Two Sum (Sorted Array)
def two_sum_sorted(nums, target):
left, right = 0, len(nums) - 1
while left < right:
curr_sum = nums[left] + nums[right]
if curr_sum == target:
return [left, right]
elif curr_sum < target:
left += 1
else:
right -= 1
return []
Time Complexity: O(n)
What is the Sliding Window Technique?
Used for problems involving subarrays or substrings — you “slide” a window (range) over the data to keep track of a condition (e.g., sum, length, uniqueness).
Example 2: Maximum Sum of Subarray of Size k
def max_sum_subarray(nums, k):
max_sum = window_sum = sum(nums[:k])
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k]
max_sum = max(max_sum, window_sum)
return max_sum
Time Complexity: O(n)
Example 3: Longest Substring Without Repeating Characters
def length_of_longest_substring(s):
seen = set()
left = max_len = 0
for right in range(len(s)):
while s[right] in seen:
seen.remove(s[left])
left += 1
seen.add(s[right])
max_len = max(max_len, right - left + 1)
return max_len
This is both Two Pointers + Sliding Window magic
When to Use What?
Problem Type | Technique |
---|---|
Sorted array, find pair/triplet | Two Pointers |
Subarray of fixed size | Sliding Window |
Subarray/substring with condition | Sliding Window |
Reversing or merging sorted arrays | Two Pointers |
Final Tips
Sliding window is like an adjustable “view” into your array or string.
Two pointers are perfect when the data is sorted or needs comparing from both ends.
Practice makes patterns — soon you’ll spot these problems in seconds.
Practice Problems
Leetcode 3: Longest Substring Without Repeating Characters
Leetcode 209: Minimum Size Subarray Sum
Leetcode 167: Two Sum II – Input Array is Sorted
Hope this helps you in your coding journey!
Feel free to drop your thoughts or questions in the comments below.