Practice Data Structures & Algorithms in Java

Master essential DSA patterns including Two Pointers, Sliding Window, Dynamic Programming, Trees, Graphs, and more. Learn the patterns that will help you solve any coding problem.

Work through 60 exercises with starter code, expected output, test cases, and hints.

How to learn Data Structures & Algorithms

Data-structure and algorithm practice is most useful when you learn reusable decision patterns rather than memorize finished answers. A pattern connects clues in the constraints to a small set of tools: sorted input may suggest two pointers, contiguous ranges suggest a window or prefix sum, and shortest unweighted paths suggest breadth-first search.

For every problem, first write the input size, desired result, and acceptable complexity. Then produce a simple correct approach before optimizing. That baseline exposes the repeated work an improved structure or invariant needs to remove.

Recommended learning order

  1. Complexity and invariants: Count work and extra storage, and state what each loop variable or data structure means at any moment.
  2. Linear sequence patterns: Learn two pointers, fixed and variable sliding windows, prefix sums, frequency maps, stacks, and queues on arrays and strings.
  3. Recursive structures: Study recursion and backtracking, then trees and graphs with explicit visited-state and clear traversal order.
  4. Optimization patterns: Move to heaps, binary search on answers, greedy reasoning, and dynamic programming after the simpler state representations are familiar.

Tested example: Find a pair in a sorted array

If the sum is too small, moving the left pointer is the only move that can increase it; if too large, moving the right pointer can decrease it. That invariant replaces a quadratic pair search with one pass.

import java.util.Arrays;

public class Main {
    static int[] pairWithSum(int[] sorted, int target) {
        int left = 0;
        int right = sorted.length - 1;
        while (left < right) {
            int sum = sorted[left] + sorted[right];
            if (sum == target) return new int[] {left, right};
            if (sum < target) left++;
            else right--;
        }
        return new int[] {-1, -1};
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(pairWithSum(new int[] {1, 3, 4, 7, 9}, 11)));
    }
}

Expected output

[2, 3]

Change and run this example in the Java compiler

Common mistakes

  • Applying a remembered pattern without checking its precondition, such as using opposing pointers on unsorted data.
  • Optimizing before a correct baseline exists, making both the logic and the performance claim hard to verify.
  • Giving complexity only in terms of one variable when a graph or matrix has multiple relevant dimensions.
  • Testing only the happy path and missing empty input, duplicate values, disconnected graphs, or arithmetic overflow.

How to practice

Work through the hub in pattern groups rather than random order. After solving, explain the invariant without code, record time and space complexity, and revisit the problem later from a blank editor. The recursion tutorial and DSA study guide provide the conceptual bridge to trees, graphs, and dynamic programming.

Exercises to do first

Data Structures & Algorithms exercises

  1. Two Sum (Sorted Array) Java exercise — Find two numbers in a sorted array that add up to target
  2. Remove Duplicates from Sorted Array Java exercise — Remove duplicates in-place and return new length
  3. Container With Most Water Java exercise — Find two lines that form container with most water
  4. Three Sum Java exercise — Find all unique triplets that sum to zero
  5. Valid Palindrome Java exercise — Check if string is palindrome considering only alphanumeric
  6. Maximum Sum Subarray of Size K Java exercise — Find maximum sum of any contiguous subarray of size k
  7. Longest Substring with K Distinct Characters Java exercise — Find longest substring with at most k distinct characters
  8. Minimum Window Substring Java exercise — Find minimum window containing all characters of pattern
  9. Longest Repeating Character Replacement Java exercise — Longest substring with same letter after k replacements
  10. Fruit Into Baskets Java exercise — Maximum fruits you can collect with two baskets
  11. Fibonacci with DP Java exercise — Calculate nth Fibonacci number efficiently
  12. Climbing Stairs Java exercise — Count distinct ways to climb n stairs (1 or 2 steps)
  13. House Robber Java exercise — Maximum money without robbing adjacent houses
  14. Coin Change Java exercise — Minimum coins needed to make amount
  15. Longest Increasing Subsequence Java exercise — Find length of longest strictly increasing subsequence
  16. 0/1 Knapsack Java exercise — Maximum value with limited weight capacity
  17. Unique Paths in Grid Java exercise — Count paths from top-left to bottom-right
  18. Longest Common Subsequence Java exercise — Find length of longest common subsequence of two strings
  19. Edit Distance (Levenshtein) Java exercise — Minimum operations to convert one string to another
  20. Maximum Subarray (Kadane's Algorithm) Java exercise — Find contiguous subarray with largest sum
  21. Two Sum (Unsorted) Java exercise — Find two numbers that add up to target using HashMap
  22. Group Anagrams Java exercise — Group strings that are anagrams of each other
  23. Subarray Sum Equals K Java exercise — Count subarrays with sum equal to k
  24. Longest Consecutive Sequence Java exercise — Find length of longest consecutive elements sequence
  25. Valid Anagram Java exercise — Check if two strings are anagrams
  26. Valid Parentheses Java exercise — Check if parentheses string is valid
  27. Next Greater Element Java exercise — Find next greater element for each array element
  28. Daily Temperatures Java exercise — Days until warmer temperature
  29. Largest Rectangle in Histogram Java exercise — Find largest rectangular area in histogram
  30. Min Stack Java exercise — Design stack that supports getMin in O(1)
  31. Binary Tree Inorder Traversal Java exercise — Traverse tree in Left-Root-Right order
  32. Maximum Depth of Binary Tree Java exercise — Find the maximum depth (height) of a binary tree
  33. Binary Tree Level Order Traversal Java exercise — Traverse tree level by level (BFS)
  34. Validate Binary Search Tree Java exercise — Check if a binary tree is a valid BST
  35. Lowest Common Ancestor Java exercise — Find lowest common ancestor of two nodes
  36. Number of Islands Java exercise — Count number of islands in a 2D grid
  37. Clone Graph Java exercise — Create a deep copy of an undirected graph
  38. Course Schedule (Cycle Detection) Java exercise — Check if all courses can be finished
  39. Word Ladder (Shortest Path) Java exercise — Find shortest transformation sequence
  40. Rotting Oranges (Multi-source BFS) Java exercise — Minimum time for all oranges to rot
  41. Jump Game Java exercise — Can you reach the last index?
  42. Activity Selection (Interval Scheduling) Java exercise — Select maximum non-overlapping activities
  43. Gas Station Java exercise — Find starting station to complete circuit
  44. Partition Labels Java exercise — Partition string so each letter appears in at most one part
  45. Task Scheduler Java exercise — Minimum time to complete all tasks with cooldown
  46. Binary Search Java exercise — Find target in sorted array
  47. Search in Rotated Sorted Array Java exercise — Binary search in rotated array
  48. Find Minimum in Rotated Sorted Array Java exercise — Find the minimum element in rotated array
  49. Koko Eating Bananas Java exercise — Minimum eating speed to finish in h hours
  50. Capacity To Ship Packages Java exercise — Minimum ship capacity to ship all in D days
  51. Subsets (Power Set) Java exercise — Generate all subsets of a set
  52. Permutations Java exercise — Generate all permutations of an array
  53. Combination Sum Java exercise — Find combinations that sum to target
  54. N-Queens Java exercise — Place N queens on NxN board with no attacks
  55. Word Search Java exercise — Find if word exists in grid
  56. Kth Largest Element Java exercise — Find the kth largest element in array
  57. Merge K Sorted Lists Java exercise — Merge k sorted linked lists
  58. Top K Frequent Elements Java exercise — Find k most frequent elements
  59. Find Median from Data Stream Java exercise — Track median as numbers are added
  60. Meeting Rooms II Java exercise — Minimum number of conference rooms required

Browse the complete Java practice path · Open the online Java compiler