Rohit Kumar
•
19 April 2025
•
11 mins
Coding patterns are a set of techniques or strategies that can be applied to solve common problems in programming. They help you recognize the underlying structure of a problem and apply the appropriate solution.
Here is a simple implementation of Fenwick Tree in Java:
class FenwickTree {
private int[] tree;
private int size;
public FenwickTree(int size) {
this.size = size;
tree = new int[size + 1];
}
public void update(int index, int value) {
while (index <= size) {
tree[index] += value;
index += index & -index;
}
}
// lets understand this line with the help of binary representation
// 4 = 100
// 5 = 101
// 4 & -4 = 4
// 5 & -5 = 1
public int query(int index) {
int sum = 0;
while (index > 0) {
sum += tree[index];
index -= index & -index;
}
return sum;
}
}
public SegmentTree(int size) { this.size = size; tree = new int[4 * size]; // why 4 * size? // this is because the segment tree is a binary tree and in the worst case, we need 4 times the size of the array to store the segment tree }
public void build(int[] arr, int node, int start, int end) { if (start == end) { tree[node] = arr[start]; } else { int mid = (start + end) / 2; build(arr, 2 * node + 1, start, mid); build(arr, 2 * node + 2, mid + 1, end); tree[node] = Math.min(tree[2 * node + 1], tree[2 * node + 2]); } }
public void update(int index, int value, int node, int start, int end) { if (start == end) { tree[node] = value; } else { int mid = (start + end) / 2; if (index <= mid) { update(index, value, 2 * node + 1, start, mid); } else { update(index, value, 2 * node + 2, mid + 1, end); } tree[node] = Math.min(tree[2 * node + 1], tree[2 * node + 2]); } }
public int query(int L, int R, int node, int start, int end) { if (R < start || L > end) { return Integer.MAX_VALUE; // Return a large value for out of range } if (L <= start && R >= end) { return tree[node]; } int mid = (start + end) / 2; return Math.min(query(L, R, 2 * node + 1, start, mid), query(L, R, 2 * node + 2, mid + 1, end)); } } ```
This is not an exhaustive list of coding patterns, but it covers some of the most common ones. Also some problems can be solved using multiple patterns or combinations of patterns. The key is to practice and become familiar with these patterns so that you can recognize them when solving problems.