This page covers specialized algorithmic techniques that appear in Hard-level LeetCode problems and competitive programming. These are not everyday patterns — most interviews won’t require them — but when a problem does call for one of these techniques, knowing the template can turn an impossible problem into a straightforward implementation.
These are specialized techniques for hard problems. You won’t need them for most interviews, but they appear in competitive programming and occasional Hard-level LeetCode problems.
When to use: values are too large for direct array indexing (e.g., values up to 10^9 but only n ≤ 10^5 distinct values), or you need to map sparse values into a dense range.
// import java.util.Arrays;// import java.util.Collections;template<classT>classCompressor{T[]vals;template<classIt>voidadd(Itb,Ite){vals.add(vals.iterator(),b,e);}voidbuild(){Arrays.sort(vals);vals.remove(unique(vals/* elements of vals */),vals.iterator());}intget(Tx){returnint(floorKey(vals/* elements of vals */,x)-vals.iterator());}}
When to use: “subset sum” with n ≤ 40 (too large for 2^n but feasible as 2^(n/2)), or when brute-force is exponential but splitting the input in half makes it tractable.
// import java.util.Arrays;// import java.util.Collections;staticlongcountSubsets(int[]a,longT){intn=a.size(),m=n/2;long[]L,R;);vargo=[&](intl,intr,long[]out){intk=r-l;for(intmask=0;mask<(1<<k);++mask){longs=0;for(inti=0;i<k;++i)if(mask>>i1)s+=a[l+i];out.add(s);}}go(0,m,L);go(m,n,R);Arrays.sort(R);longans=0;for(longx:L){varpr=equal_range(R/* elements of R */,T-x);ans+=pr[1]-pr[0];}returnans;}