Home > Back-end >  Leetcode C program, two numbers in array that add to target
Leetcode C program, two numbers in array that add to target

Time:01-09

I am trying to solve a Leetcode problem using C, and for some reason the Output of my program is showing an empty array. The challenge is to write a function that returns an array consisting of the indices of two numbers in an array that sum to a target number. I solved it with Python, but now I am trying to solve it with C. What am I missing? Does it have something to do with returnSize?

Note: The constraints say there will be only one answer (two numbers that add up to the target) in each array for each target.

The solution I have tried is as follows:

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int* answer;
    answer = malloc(2*sizeof(int));

    // Success flag flips when two ints are identified
    bool success = false;

    // Look through every element of nums
    for(int first_number = 0; first_number < numsSize; first_number  )
    {
        // If index is at end of array, do not check further.
        if(first_number < numsSize)
        {
            // For each number in array, look at all of the numbers after it
            for(int second_number=(first_number   1); second_number < numsSize; second_number  )
            {
                if((nums[first_number]   nums[second_number] == target))
                {
                    answer[0] = first_number;
                    answer[1] = second_number;
                    // Flip success flag
                    success = true;
                }
            }
        }

        // Check success flag and break. No need to check further.
        if(success){
            break;
        }
    }

    return answer;
}

Update:
Per the advice of Fe2O3 and the explanation of WhozCraig, I added a line that solved the problem. From what I have gathered, when using malloc() it is not easy to determine the size of a dynamic array. Including the returnSize pointer is necessary as it stores the value of the length of the return array. That way, you can easily access every member of the final array. Thank you all for your help!!! The final code follows:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){

    // Generate dynamic array for return
    int* answer;
    answer = malloc(2*sizeof(int));

    // Store length of dynamic array in returnSize
    *returnSize = 2;

    // Success flag flips when two ints are identified
    bool success = false;

    // Look through every element of nums
    for(int first_number = 0; first_number < numsSize; first_number  )
    {
        // If index is at end of array, do not check further.
        if(first_number < numsSize)
        {
            // For each number in array, look at all of the numbers after it
            for(int second_number=(first_number   1); second_number < numsSize; second_number  )
            {
                if((nums[first_number]   nums[second_number] == target))
                {
                    answer[0] = first_number;
                    answer[1] = second_number;

                    // Flip success flag and break
                    success = true;
                    break;
                }
            }
        }

        // Check success flag and break. No need to check further.
        if(success){
            break;
        }
    }

    return answer;
}

CodePudding user response:

Having bitten into this apple, I feel compelled to demonstrate how this function might be written by one with more experience:

int *twoSum( int *nums, int numsSize, int target, int *returnSize ) {
    *returnSize = 0; // default

    for( int i = 0; i < numsSize; i   )
        for( int j = i   1; j < numsSize; j   )
            if( nums[ i ]   nums[ j ] == target ) {
                int *answer = malloc( 2 * sizeof *answer );
                /* Omitting verification of malloc success for brevity */
                answer[0] = i;
                answer[1] = j;
                *returnSize = 2;
                return answer;
            }

    return NULL;
}

It's a silly (Leetcode) problem.
The caller should provide the array (could be stack instead of heap allocation) for the two indices (if found). The function would "know" it can write two integer indices into that array IF a pair is located. Then the function merely returns true or false as to whether it had success or not...

EDIT
Longer response to OP question below:

A minor change to the Leetcode problem might take this form. Notice that the "return array" exists on the stack in the function main() (without needing the heap allocation.) The function needs 4 parameters and returns true/false if it was able to put the two desired values into the 2 element array.

int main(){
    const int arr[] = { 1, 2, 3, 4, 9 };
    const int arrSz = sizeof arr/sizeof arr[0];
    const int target = 4   9; // last two values
    int inds[2] = { 0 }; // ALWAYS initialise variables

    if( twoSum( arr, arrSz, target, inds ) )
        print( "[%d, %d]\n", inds[0], inds[1] );
    else
        print("Error\n");
    return 0;
}
  •  Tags:  
  • c
  • Related