Skip to content

Article on subset sum? #836

Open
Open
@jxu

Description

@jxu

Important enough that it deserves its own article if it doesn't exist already (I didn't find it in a quick search)

I wrote a quick stackoverflow answer for the special case of two values https://stackoverflow.com/questions/11928091/linear-time-algorithm-for-2-sum. It uses a two-pointer method which is a good strategy in general for sorted arrays.

The classic linear time two-pointer solution does not require hashing so can solve related problems such as approximate sum (find closest pair sum to target).

First, a simple n log n solution: walk through array elements a[i], and use binary search to find the best a[j].

To get rid of the log factor, use the following observation: as the list is sorted, iterating through indices i gives a[i] is increasing, so any corresponding a[j] is decreasing in value and in index j. This gives the two-pointer solution: start with indices lo = 0, hi = N-1 (pointing to a[0] and a[N-1]). For a[0], find the best a[hi] by decreasing hi. Then increment lo and for each a[lo], decrease hi until a[lo] + a[hi] is the best. The algorithm can stop when it reaches lo == hi.

Do you guys have any objections if I write for that section "author: @jxu"? Well I need some reason to contribute here and not on my personal CF blog. #792

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions