Skip to content

Infinite recursion in combinationSum #308

Open
@dubzzz

Description

@dubzzz

Details:

combinationSum fails with Maximum call stack size exceeded.
It seems that there is an infinite recursion in it.

Step to reproduce: combinationSum([0], 1)

Bug 1: presence of 0 produces an infinite loop
Bug 2: presence of small entries compared to target produces a stack size exceeded - combinationSum([1], 100000)

Fix

I can issue a PR with the fix.

How did I find it?

Thanks to property based testing framework fast-check.
The property was the following:

import fc from 'fast-check';

fc.assert(
    fc.property(
        fc.set(fc.nat()),
        fc.nat(),
        (elements, target) => {
            const combinations = combinationSum(elements, target);
            const combinationsStr = combinations.map(arr => arr.join(','));
            // no duplicates
            expect([...new Set(combinationsStr)]).toEqual(combinationsStr);
            // right sum
            for (const comb of combinations)
                expect(comb.reduce((a,b) => a+b, 0)).toBe(target);
        }
    )
)

Or:

for any elements - array of unique positive integers, target - positive integer
the output of combinationSum(elements, target) does not contain any duplicates
and all its entries sum to target

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions