Interview Question

Software Development Engineer Interview(Student Candidate) Redmond, WA

given an unsigned char array, find if there is a subarray

  whose elements sum up to a given value
Answer

Interview Answer

3 Answers

0

public static bool SubArraySum(int[] array, int sum)
{
            int tempsum = 0;

            for(int i = 0; i < array.Length; i++)
            {
                            for(int j = i; j < array.Length; j++)
                            {
                                        tempsum += array[j];

                                        if (tempsum == sum) return true;
                                        else if (tempsum > sum)
                                        {
                                             tempsum = 0;
                                             break;
                                        }
                            }
            }

            return false;
}

(Note: this function operates on int instead of char)

dude on Apr 29, 2013
0

bug -
J < array.length-i
otherwise you go out of the array boundaries

Jennie on May 18, 2013
0

Total wrong answer. You are not finding the subarray at all. Must use recurison for simplified version

Wei on Sep 23, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.