Array

Range sum(subarray/matrix)

Essentially, this kind of problem can be solved with prefix sum. But search prefix sum takes O(N), how can we accelerate? Use Binary Index Tree(BIT) which guarantee O(logN) for searching an accumulated sum.

So to find the sum of a range, these are typical solutions:

Typicall questions:

Interval problems

Interval problem typically cope with a range: a start point, a end point, and optionally some attributes of this interval, like 0218. The Skyline Problem. It almost always requires sorting. Since it's O(NlogN) anyway, always try TreeMap.

Typicall ideas:

Typical questions:

make use of index

match nums[i] with i

https://leetcode.com/problems/first-missing-positive/description/arrow-up-right https://leetcode.com/problems/missing-number/description/arrow-up-right https://leetcode.com/problems/find-the-duplicate-number/description/arrow-up-right https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/arrow-up-right https://leetcode.com/problems/find-all-duplicates-in-an-array/description/arrow-up-right https://leetcode.com/problems/couples-holding-hands/description/arrow-up-right

Peak and Valley

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/arrow-up-right

sliding to find peak or valley

K sum problem

2 pointers: https://leetcode.com/problems/two-sumarrow-up-right https://leetcode.com/problems/two-sum-ii-input-array-is-sortedarrow-up-right https://leetcode.com/problems/two-sum-iii-data-structure-designarrow-up-right https://leetcode.com/problems/two-sum-iv-input-is-a-bstarrow-up-right https://leetcode.com/problems/3sumarrow-up-right https://leetcode.com/problems/3sum-closestarrow-up-right https://leetcode.com/problems/3sum-smallerarrow-up-right https://leetcode.com/problems/valid-triangle-number/description/arrow-up-right https://leetcode.com/problems/4sumarrow-up-right https://leetcode.com/problems/4sum-iiarrow-up-right

hash map:

https://leetcode.com/problems/two-sumarrow-up-right https://leetcode.com/problems/subarray-sum-equals-k/description/arrow-up-right https://leetcode.com/problems/two-sum-iv-input-is-a-bstarrow-up-right https://leetcode.com/problems/4sum-iiarrow-up-right

Avoid duplicate

1) sort and skip same value, if (nums[i] == nums[i-1]) continue; https://leetcode.com/problems/combination-sum-ii/description/arrow-up-right 2) when it can't be sort, use array or set at this level; https://leetcode.com/problems/increasing-subsequences/description/arrow-up-right

Trap water

https://leetcode.com/problems/container-with-most-water/description/arrow-up-right https://leetcode.com/problems/trapping-rain-water/description/arrow-up-right https://leetcode.com/problems/trapping-rain-water-iiarrow-up-right

Two pass

1 from left and 1 from right:

Last updated

Was this helpful?