www.iqmath.
in
TOP 25 JAVA DSA PROBLEM SOLVING PATTERNS - LEETCODE
1. Two Pointers Pattern
Used when iterating from both ends of a data structure like arrays or linked lists.
Efficient for finding pairs, checking palindromes, merging, etc.
Sample Java Algorithm:
public boolean hasPairWithSum(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) return true;
else if (sum < target) left++;
else right--;
return false;
LeetCode Problems:
• https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
• https://leetcode.com/problems/3sum/
• https://leetcode.com/problems/valid-palindrome/
• https://leetcode.com/problems/container-with-most-water/
• https://leetcode.com/problems/merge-sorted-array/
• https://leetcode.com/problems/remove-duplicates-from-sorted-array/
• https://leetcode.com/problems/valid-palindrome-ii/
• https://leetcode.com/problems/maximum-average-subarray-i/
• https://leetcode.com/problems/longest-substring-without-repeating-
characters/
www.iqmath.in
2. Sliding Window Pattern
Used for subarrays or substrings. Optimizes nested loop problems into O(n) time by
maintaining a window of elements.
Sample Java Algorithm:
public int maxSumSubarray(int[] arr, int k) {
int maxSum = 0, windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += arr[i];
maxSum = windowSum;
for (int i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
maxSum = Math.max(maxSum, windowSum);
return maxSum;
LeetCode Problems:
• https://leetcode.com/problems/maximum-average-subarray-i/
• https://leetcode.com/problems/longest-substring-without-repeating-
characters/
• https://leetcode.com/problems/minimum-size-subarray-sum/
• https://leetcode.com/problems/permutation-in-string/
• https://leetcode.com/problems/longest-repeating-character-replacement/
• https://leetcode.com/problems/sliding-window-maximum/
• https://leetcode.com/problems/grumpy-bookstore-owner/
• https://leetcode.com/problems/max-consecutive-ones-iii/
3. Fast & Slow Pointers (Floyd’s Cycle Detection)
www.iqmath.in
Used mainly in linked list and cycle detection problems. Two pointers move at different
speeds—used for loops, palindromes, mid-point detection.
Sample Java Algorithm:
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
return false;
LeetCode Problems:
• https://leetcode.com/problems/linked-list-cycle/
• https://leetcode.com/problems/linked-list-cycle-ii/
• https://leetcode.com/problems/happy-number/
• https://leetcode.com/problems/middle-of-the-linked-list/
• https://leetcode.com/problems/palindrome-linked-list/
• https://leetcode.com/problems/intersection-of-two-linked-lists/
• https://leetcode.com/problems/find-the-duplicate-number/
4. Merge Intervals Pattern
Used when working with overlapping intervals. Helps in combining or scheduling tasks
efficiently.
Sample Java Algorithm:
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
List<int[]> merged = new ArrayList<>();
for (int[] interval : intervals) {
www.iqmath.in
if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < interval[0]) {
merged.add(interval);
} else {
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1],
interval[1]);
return merged.toArray(new int[merged.size()][]);
LeetCode Problems:
• https://leetcode.com/problems/merge-intervals/
• https://leetcode.com/problems/insert-interval/
• https://leetcode.com/problems/interval-list-intersections/
• https://leetcode.com/problems/meeting-rooms/
• https://leetcode.com/problems/meeting-rooms-ii/
• https://leetcode.com/problems/non-overlapping-intervals/
• https://leetcode.com/problems/employee-free-time/
• https://leetcode.com/problems/merge-sorted-array/
5. Cyclic Sort Pattern
Used when working with arrays containing numbers in a fixed range (1 to n). Places each
number at its correct index.
Sample Java Algorithm:
public int findMissingNumber(int[] nums) {
int i = 0;
while (i < nums.length) {
int correct = nums[i];
if (nums[i] < nums.length && nums[i] != nums[correct]) {
int temp = nums[i];
www.iqmath.in
nums[i] = nums[correct];
nums[correct] = temp;
} else {
i++;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != j) return j;
return nums.length;
LeetCode Problems:
• https://leetcode.com/problems/missing-number/
• https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
• https://leetcode.com/problems/find-the-duplicate-number/
• https://leetcode.com/problems/first-missing-positive/
• https://leetcode.com/problems/set-mismatch/
• https://leetcode.com/problems/cyclically-rotating-a-grid/
• https://leetcode.com/problems/relative-ranks/
6. In-place Reversal of a Linked List
This pattern is used when reversing all or part of a linked list in-place. It’s especially
useful in palindrome check, reverse segments, or K-group reversal problems.
Sample Java Algorithm:
public ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
www.iqmath.in
head.next = prev;
prev = head;
head = next;
return prev;
LeetCode Problems:
• https://leetcode.com/problems/reverse-linked-list/
• https://leetcode.com/problems/reverse-linked-list-ii/
• https://leetcode.com/problems/palindrome-linked-list/
• https://leetcode.com/problems/reverse-nodes-in-k-group/
• https://leetcode.com/problems/rotate-list/
• https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
• https://leetcode.com/problems/remove-nth-node-from-end-of-list/
• https://leetcode.com/problems/swap-nodes-in-pairs/
7. Breadth-First Search (BFS)
BFS explores the nearest neighbors first, level by level. It is widely used in tree and graph
traversals, shortest paths in unweighted graphs, and grid problems.
Sample Java Algorithm (Tree Level Order):
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new ArrayList<>();
www.iqmath.in
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
result.add(level);
return result;
LeetCode Problems:
• https://leetcode.com/problems/binary-tree-level-order-traversal/
• https://leetcode.com/problems/minimum-depth-of-binary-tree/
• https://leetcode.com/problems/rotting-oranges/
• https://leetcode.com/problems/course-schedule/
• https://leetcode.com/problems/find-largest-value-in-each-tree-row/
• https://leetcode.com/problems/number-of-islands/
• https://leetcode.com/problems/open-the-lock/
• https://leetcode.com/problems/word-ladder/
8. Depth-First Search (DFS)
DFS explores as deep as possible before backtracking. Useful in graph traversal, tree
recursion, backtracking, islands, and component counting.
Sample Java Algorithm (Graph DFS):
public void dfs(int node, boolean[] visited, List<List<Integer>> graph) {
visited[node] = true;
for (int neighbor : graph.get(node)) {
if (!visited[neighbor]) {
www.iqmath.in
dfs(neighbor, visited, graph);
LeetCode Problems:
• https://leetcode.com/problems/number-of-islands/
• https://leetcode.com/problems/clone-graph/
• https://leetcode.com/problems/path-sum/
• https://leetcode.com/problems/combination-sum/
• https://leetcode.com/problems/pacific-atlantic-water-flow/
• https://leetcode.com/problems/word-search/
• https://leetcode.com/problems/max-area-of-island/
• https://leetcode.com/problems/course-schedule-ii/
9. Binary Search Pattern
Classic pattern used when input is sorted or when the answer space is monotonic. Can
be applied over arrays, search ranges, or even in custom problem spaces.
Sample Java Algorithm:
public int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
return -1;
}
www.iqmath.in
LeetCode Problems:
• https://leetcode.com/problems/binary-search/
• https://leetcode.com/problems/search-in-rotated-sorted-array/
• https://leetcode.com/problems/find-first-and-last-position-of-element-in-
sorted-array/
• https://leetcode.com/problems/peak-index-in-a-mountain-array/
• https://leetcode.com/problems/search-a-2d-matrix/
• https://leetcode.com/problems/koko-eating-bananas/
• https://leetcode.com/problems/sqrtx/
• https://leetcode.com/problems/guess-number-higher-or-lower/
• https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
10. Backtracking Pattern
Backtracking is used when you need to explore all possibilities, especially in
combinatorial problems like permutations, combinations, and constraints.
Sample Java Algorithm (N-Queens Style):
public void backtrack(List<List<Integer>> result, List<Integer> temp, int n) {
if (temp.size() == n) {
result.add(new ArrayList<>(temp));
return;
for (int i = 1; i <= n; i++) {
if (temp.contains(i)) continue;
temp.add(i);
backtrack(result, temp, n);
temp.remove(temp.size() - 1);
LeetCode Problems:
www.iqmath.in
• https://leetcode.com/problems/permutations/
• https://leetcode.com/problems/combinations/
• https://leetcode.com/problems/combination-sum/
• https://leetcode.com/problems/n-queens/
• https://leetcode.com/problems/letter-combinations-of-a-phone-number/
• https://leetcode.com/problems/subsets/
• https://leetcode.com/problems/restore-ip-addresses/
• https://leetcode.com/problems/palindrome-partitioning/
• https://leetcode.com/problems/generate-parentheses/
11. Bit Manipulation Pattern
This pattern involves using bitwise operations (AND, OR, XOR, shifts) to solve problems
efficiently, often reducing space/time usage. Particularly useful for finding unique
numbers, subsets, parity, and flags.
Sample Java Algorithm (Find Unique Element):
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
return result;
LeetCode Problems:
• https://leetcode.com/problems/single-number/
• https://leetcode.com/problems/single-number-ii/
• https://leetcode.com/problems/subsets/
• https://leetcode.com/problems/number-of-1-bits/
• https://leetcode.com/problems/counting-bits/
• https://leetcode.com/problems/reverse-bits/
www.iqmath.in
• https://leetcode.com/problems/hamming-distance/
• https://leetcode.com/problems/missing-number/
12. Top K Elements Pattern (Heap/PriorityQueue)
Used when you're asked to find the top or bottom K elements. Max heaps or min heaps
are used to track the most relevant elements efficiently.
Sample Java Algorithm (Top K Frequent Elements):
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
PriorityQueue<Map.Entry<Integer, Integer>> heap =
new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
heap.addAll(freqMap.entrySet());
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = heap.poll().getKey();
return result;
LeetCode Problems:
• https://leetcode.com/problems/top-k-frequent-elements/
• https://leetcode.com/problems/kth-largest-element-in-an-array/
• https://leetcode.com/problems/k-closest-points-to-origin/
• https://leetcode.com/problems/find-k-pairs-with-smallest-sums/
• https://leetcode.com/problems/reorganize-string/
www.iqmath.in
• https://leetcode.com/problems/task-scheduler/
• https://leetcode.com/problems/merge-k-sorted-lists/
13. Union-Find (Disjoint Set)
Used in problems involving groups, connectivity, cycles in undirected graphs, and
Kruskal’s algorithm. Union-Find helps keep track of connected components.
Sample Java Algorithm:
int[] parent;
public int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
public void union(int x, int y) {
parent[find(x)] = find(y);
LeetCode Problems:
• https://leetcode.com/problems/redundant-connection/
• https://leetcode.com/problems/number-of-provinces/
• https://leetcode.com/problems/graph-valid-tree/
• https://leetcode.com/problems/accounts-merge/
• https://leetcode.com/problems/friend-circles/
• https://leetcode.com/problems/satisfiability-of-equality-equations/
• https://leetcode.com/problems/most-stones-removed-with-same-row-or-
column/
14. Topological Sort (Graph with Prerequisites)
www.iqmath.in
Used when dealing with directed graphs that have dependencies. Topological sorting
gives an order of execution while honoring those dependencies.
Sample Java Algorithm (Kahn’s Algorithm):
public int[] findOrder(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
int[] indegree = new int[numCourses];
for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>());
for (int[] pair : prerequisites) {
graph.get(pair[1]).add(pair[0]);
indegree[pair[0]]++;
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) queue.add(i);
int[] order = new int[numCourses];
int index = 0;
while (!queue.isEmpty()) {
int course = queue.poll();
order[index++] = course;
for (int next : graph.get(course)) {
if (--indegree[next] == 0) queue.add(next);
}
www.iqmath.in
return index == numCourses ? order : new int[0];
LeetCode Problems:
• https://leetcode.com/problems/course-schedule/
• https://leetcode.com/problems/course-schedule-ii/
• https://leetcode.com/problems/alien-dictionary/
• https://leetcode.com/problems/sequence-reconstruction/
• https://leetcode.com/problems/sort-items-by-groups-respecting-
dependencies/
15. Trie Pattern
A trie is a tree-like data structure used to store strings in a way that allows fast lookup,
insert, and prefix matching.
Sample Java Algorithm (Basic Trie Insert/Search):
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEnd = false;
class Trie {
TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null)
node.children[c - 'a'] = new TrieNode();
node = node.children[c - 'a'];
}
www.iqmath.in
node.isEnd = true;
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null)
return false;
node = node.children[c - 'a'];
return node.isEnd;
LeetCode Problems:
• https://leetcode.com/problems/implement-trie-prefix-tree/
• https://leetcode.com/problems/add-and-search-word-data-structure-design/
• https://leetcode.com/problems/replace-words/
• https://leetcode.com/problems/longest-word-in-dictionary/
• https://leetcode.com/problems/design-search-autocomplete-system/
• https://leetcode.com/problems/word-search-ii/
• https://leetcode.com/problems/prefix-and-suffix-search/
16. Stack-Based Problems
Stacks are used in problems involving reversal, parentheses matching, monotonic
tracking, and more. They help simulate recursive behavior or maintain order.
Sample Java Algorithm (Valid Parentheses):
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
www.iqmath.in
for (char c : s.toCharArray()) {
if (c == '(') stack.push(')');
else if (c == '[') stack.push(']');
else if (c == '{') stack.push('}');
else if (stack.isEmpty() || stack.pop() != c) return false;
return stack.isEmpty();
LeetCode Problems:
• https://leetcode.com/problems/valid-parentheses/
• https://leetcode.com/problems/min-stack/
• https://leetcode.com/problems/largest-rectangle-in-histogram/
• https://leetcode.com/problems/daily-temperatures/
• https://leetcode.com/problems/next-greater-element-i/
• https://leetcode.com/problems/next-greater-element-ii/
• https://leetcode.com/problems/remove-k-digits/
• https://leetcode.com/problems/online-stock-span/
17. Monotonic Stack Pattern
A variation of stack used to keep elements in sorted (increasing or decreasing) order.
Useful for range queries, histogram area, and next/previous greater/smaller element
problems.
Sample Java Algorithm (Next Greater Element):
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 2 * n - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums[stack.peek()] <= nums[i % n]) {
www.iqmath.in
stack.pop();
res[i % n] = stack.isEmpty() ? -1 : nums[stack.peek()];
stack.push(i % n);
return res;
LeetCode Problems:
• https://leetcode.com/problems/next-greater-element-i/
• https://leetcode.com/problems/next-greater-element-ii/
• https://leetcode.com/problems/daily-temperatures/
• https://leetcode.com/problems/largest-rectangle-in-histogram/
• https://leetcode.com/problems/sum-of-subarray-minimums/
• https://leetcode.com/problems/132-pattern/
• https://leetcode.com/problems/sliding-window-maximum/
18. Greedy Algorithms
In greedy algorithms, you make the locally optimal choice at each step hoping it leads to
a globally optimal solution. Widely used in interval scheduling, coin change, and path
minimization.
Sample Java Algorithm (Jump Game):
public boolean canJump(int[] nums) {
int maxReach = 0;
for (int i = 0; i < nums.length; i++) {
if (i > maxReach) return false;
maxReach = Math.max(maxReach, i + nums[i]);
return true;
}
www.iqmath.in
LeetCode Problems:
• https://leetcode.com/problems/jump-game/
• https://leetcode.com/problems/jump-game-ii/
• https://leetcode.com/problems/merge-intervals/
• https://leetcode.com/problems/non-overlapping-intervals/
• https://leetcode.com/problems/partition-labels/
• https://leetcode.com/problems/task-scheduler/
• https://leetcode.com/problems/candy/
• https://leetcode.com/problems/gas-station/
19. Kadane’s Algorithm (Max Subarray)
Kadane’s algorithm is a dynamic programming technique to find the maximum sum
subarray in linear time. It’s useful for financial modeling and optimal segment problems.
Sample Java Algorithm:
public int maxSubArray(int[] nums) {
int maxSum = nums[0], currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
return maxSum;
LeetCode Problems:
• https://leetcode.com/problems/maximum-subarray/
• https://leetcode.com/problems/maximum-product-subarray/
• https://leetcode.com/problems/maximum-sum-circular-subarray/
• https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
• https://leetcode.com/problems/contiguous-array/
www.iqmath.in
• https://leetcode.com/problems/subarray-sum-equals-k/
• https://leetcode.com/problems/longest-well-performing-interval/
20. Prefix Sum Pattern
Prefix sums are useful when dealing with range sum queries. It transforms repeated
sum calculations into constant-time lookups using precomputed data.
Sample Java Algorithm:
public int[] buildPrefixSum(int[] nums) {
int[] prefix = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
prefix[i + 1] = prefix[i] + nums[i];
return prefix;
LeetCode Problems:
• https://leetcode.com/problems/range-sum-query-immutable/
• https://leetcode.com/problems/find-pivot-index/
• https://leetcode.com/problems/subarray-sum-equals-k/
• https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/
• https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-
operations/
• https://leetcode.com/problems/split-array-largest-sum/
• https://leetcode.com/problems/range-sum-of-bst/
21. Dynamic Programming (1D)
1D Dynamic Programming is used when the solution of a problem depends on only one
previous state (or a linear sequence of decisions). Used for problems like Fibonacci,
house robber, and jump game.
Sample Java Algorithm (Climbing Stairs):
www.iqmath.in
public int climbStairs(int n) {
if (n <= 2) return n;
int oneStep = 2, twoStep = 1;
for (int i = 3; i <= n; i++) {
int temp = oneStep;
oneStep = oneStep + twoStep;
twoStep = temp;
return oneStep;
LeetCode Problems:
• https://leetcode.com/problems/climbing-stairs/
• https://leetcode.com/problems/house-robber/
• https://leetcode.com/problems/fibonacci-number/
• https://leetcode.com/problems/jump-game/
• https://leetcode.com/problems/maximum-subarray/
• https://leetcode.com/problems/decode-ways/
• https://leetcode.com/problems/unique-paths/
• https://leetcode.com/problems/min-cost-climbing-stairs/
22. Dynamic Programming (2D / Grid)
2D DP is used when solving problems on matrices or grids, often involving path finding,
edit distances, or counting combinations.
Sample Java Algorithm (Unique Paths in Grid):
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) dp[i][0] = 1;
for (int j = 0; j < n; j++) dp[0][j] = 1;
www.iqmath.in
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
return dp[m - 1][n - 1];
LeetCode Problems:
• https://leetcode.com/problems/unique-paths/
• https://leetcode.com/problems/minimum-path-sum/
• https://leetcode.com/problems/longest-common-subsequence/
• https://leetcode.com/problems/edit-distance/
• https://leetcode.com/problems/0-1-knapsack/
• https://leetcode.com/problems/interleaving-string/
• https://leetcode.com/problems/distinct-subsequences/
• https://leetcode.com/problems/maximum-length-of-repeated-subarray/
23. Matrix Manipulation
This pattern involves rotating, flipping, traversing, or transforming matrices. Used in
games, image processing, and simulations.
Sample Java Algorithm (Rotate Matrix):
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
www.iqmath.in
matrix[j][i] = temp;
for (int[] row : matrix) {
for (int i = 0; i < n / 2; i++) {
int temp = row[i];
row[i] = row[n - 1 - i];
row[n - 1 - i] = temp;
LeetCode Problems:
• https://leetcode.com/problems/rotate-image/
• https://leetcode.com/problems/game-of-life/
• https://leetcode.com/problems/spiral-matrix/
• https://leetcode.com/problems/set-matrix-zeroes/
• https://leetcode.com/problems/search-a-2d-matrix/
• https://leetcode.com/problems/search-a-2d-matrix-ii/
• https://leetcode.com/problems/word-search/
24. Subsets and Bitmasking
When problems involve generating all possible subsets or combinations, bitmasking or
backtracking can help generate 2ⁿ subsets efficiently.
Sample Java Algorithm (Subsets using Bitmask):
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
int total = 1 << nums.length;
for (int i = 0; i < total; i++) {
www.iqmath.in
List<Integer> subset = new ArrayList<>();
for (int j = 0; j < nums.length; j++) {
if ((i & (1 << j)) != 0) {
subset.add(nums[j]);
result.add(subset);
return result;
LeetCode Problems:
• https://leetcode.com/problems/subsets/
• https://leetcode.com/problems/subsets-ii/
• https://leetcode.com/problems/letter-case-permutation/
• https://leetcode.com/problems/generate-parentheses/
• https://leetcode.com/problems/gray-code/
• https://leetcode.com/problems/count-the-number-of-consistent-strings/
• https://leetcode.com/problems/find-the-difference-of-two-arrays/
25. Recursion and Divide & Conquer
Recursion divides a problem into subproblems and solves them independently. Divide
and Conquer extends this by merging results, commonly used in merge sort, binary
search, etc.
Sample Java Algorithm (Merge Sort):
public int[] mergeSort(int[] arr) {
if (arr.length <= 1) return arr;
int mid = arr.length / 2;
int[] left = mergeSort(Arrays.copyOfRange(arr, 0, mid));
int[] right = mergeSort(Arrays.copyOfRange(arr, mid, arr.length));
www.iqmath.in
return merge(left, right);
private int[] merge(int[] left, int[] right) {
int[] merged = new int[left.length + right.length];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length)
merged[k++] = (left[i] < right[j]) ? left[i++] : right[j++];
while (i < left.length) merged[k++] = left[i++];
while (j < right.length) merged[k++] = right[j++];
return merged;
LeetCode Problems:
• https://leetcode.com/problems/merge-sorted-array/
• https://leetcode.com/problems/sort-an-array/
• https://leetcode.com/problems/kth-largest-element-in-an-array/
• https://leetcode.com/problems/maximum-subarray/
• https://leetcode.com/problems/construct-binary-tree-from-preorder-and-
inorder-traversal/
• https://leetcode.com/problems/count-of-smaller-numbers-after-self/