Skip to main content
Intermediate Practical Programming Example 10 min read DSA Pattern (Java 21 / Python 3.12)

Sliding Window & Two Pointers DSA Pattern Explained

Master fixed-size and dynamic shrinkable Sliding Window templates to solve substring and subarray OAs in O(N) linear time.

Written by MockAttempt Engineering Editorial Desk (Curriculum & Code Verification Review Panel) Reviewed by Ravi Shankar Mishra
Last updated: Verification Policy

Learning Objectives

  • Identify monotonic subarray/substring constraints suited for Sliding Window.
  • Maintain frequency/last-seen invariants accurately while advancing `left` and `right` pointers.

Prerequisites

  • Arrays, Strings, HashMap / Set lookup complexity

Why Two Pointers Collapse Nested Loops

Brute-force scanning every (i, j) pair across an array of size 100,000 executes ~5 billion steps and fails HackerRank OAs with Time Limit Exceeded. Whenever shrinking/expanding a contiguous window `[left, right]` preserves a monotonic invariant, each pointer moves forward at most `N` times total — yielding O(N) worst-case time complexity.

Practice more interview patterns with Java Collections or join our Java Backend 150-Problem Coding Lab (+ 3 Months OA/HackerRank Support).

Practical Programming Examples

Longest Substring Without Repeating Characters in O(N) (Java 21)

Given a string s, find the length of the longest contiguous substring containing all distinct characters in O(N) time.

JDK 21 LTS (javac / java)
import java.util.HashMap;
import java.util.Map;

public class SlidingWindowDemo {
    public static int longestUniqueLength(String s) {
        Map<Character, Integer> lastSeen = new HashMap<>();
        int left = 0, best = 0;

        for (int right = 0; right < s.length(); right++) {
            char ch = s.charAt(right);
            if (lastSeen.containsKey(ch)) {
                left = Math.max(left, lastSeen.get(ch) + 1);
            }
            lastSeen.put(ch, right);
            best = Math.max(best, right - left + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println("Longest unique length = " + longestUniqueLength("abcabcbb"));
    }
}
Expected Output
Longest unique length = 3
Step-by-Step Execution
  1. `right` advances across every character once, storing its latest index inside `lastSeen`.
  2. Using `Math.max(left, lastSeen.get(ch) + 1)` ensures `left` never moves backward past already excluded duplicates.
  3. Total iterations equal `s.length()` (O(N) time, O(min(N, alphabet)) space).

Common Mistakes to Avoid

  • Writing `left = lastSeen.get(ch) + 1` without `Math.max(left, ...)`, accidentally rewinding `left` backward on earlier duplicate chars.
  • Trying to apply standard Sliding Window when negative array values allow non-monotonic sum recovery.

Production Best Practices

  • Always state the exact window invariant in one sentence before coding (`window [left..right] contains zero duplicate chars`).

Technical Interview Relevance

Top 3 most repeated coding screen pattern across TCS Digital, Amazon, Flipkart, and product SDE-1 interviews.

Practice & Self-Check Questions

Why does a subarray sum target problem with BOTH positive and negative numbers fail two-pointer Sliding Window?

Negative integers mean expanding right can shrink the sum and shrinking left can raise it, breaking window monotonicity; solve with Prefix Sum + HashMap.

Optional Next Step

Have Questions About Learning Data Structures & Algorithms Structured Cohorts?

Request the JBCP syllabus & weekend batch schedule from an Academic Counselor.

View JBCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.