Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

Two Sum Problem in C | Find Pair with Given Sum

LeetCode Two Sum C Solution with malloc and Pointer Return

✅ LeetCode Two Sum Problem in C (with malloc and Pointer Return)

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
    // ✅ LeetCode requires returning a malloc'ed array
    // (Even if we can do it with static, LeetCode tests will free the result)
    int* result = (int*)malloc(2 * sizeof(int));

    for (int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                result[0] = i;
                result[1] = j;
                *returnSize = 2;
                return result; // return the indices
            }
        }
    }

    // No valid pair found (shouldn’t happen as per LeetCode guarantee)
    *returnSize = 0;
    return NULL;
}
  

πŸ“˜ Explanation:

This is the official LeetCode-style Two Sum solution in C. It returns the indices of two numbers in an array whose sum equals a given target.

  • malloc() is used because LeetCode expects the array to be dynamically allocated.
  • The function returns int* — a pointer to an array of indices.
  • *returnSize is set to 2, indicating two elements in the result.
  • If no valid pair exists, it returns NULL.

🧾 Example Usage (Main Function):

#include <stdio.h>
#include <stdlib.h>

int main() {
    int nums[] = {2, 7, 11, 15};
    int target = 9;
    int returnSize;
    int* result = twoSum(nums, 4, target, &returnSize);

    if (result != NULL) {
        printf("Indices: [%d, %d]\\n", result[0], result[1]);
        free(result);
    } else {
        printf("No pair found!\\n");
    }
    return 0;
}
  

🧩 Sample Output:

Indices: [0, 1]
  

πŸ”‘ Keywords:

C two sum program, LeetCode C solution, dynamic memory in C, pointer return C, malloc free example, coding interview questions in C, #1printf, array index problem, DSA C programming

πŸ“Œ Hashtags:

#CProgramming #LeetCode #TwoSum #Pointers #DynamicMemory #LogicBuilding #DSA #1printf

πŸ” Search Description:

LeetCode Two Sum C solution using malloc and pointer return. Learn how to dynamically allocate memory, return arrays, and handle pointers correctly in C.

C Program for LeetCode Two Sum Problem (with malloc and Full main)

✅ C Program for LeetCode Two Sum Problem (with malloc and Full main)

#include <stdio.h>
#include <stdlib.h>

// πŸ”Ή LeetCode-style function
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
    // Must use malloc because LeetCode frees the result
    int* result = (int*)malloc(2 * sizeof(int));

    for (int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                result[0] = i;
                result[1] = j;
                *returnSize = 2;
                return result;
            }
        }
    }

    *returnSize = 0;
    return NULL;
}

// πŸ”Ή Normal main() for local testing
int main() {
    int n, target;

    // Step 1: Take size of array
    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Step 2: Take array input
    int nums[100]; // fixed max size (change if needed)
    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &nums[i]);
    }

    // Step 3: Take target
    printf("Enter target sum: ");
    scanf("%d", &target);

    // Step 4: Call function
    int returnSize;
    int* ans = twoSum(nums, n, target, &returnSize);

    // Step 5: Show output
    if (ans != NULL) {
        printf("\nIndices: [%d, %d]\n", ans[0], ans[1]);
        printf("Numbers: %d + %d = %d\n", nums[ans[0]], nums[ans[1]], target);
        free(ans); // free dynamically allocated memory
    } else {
        printf("\nNo two numbers add up to %d\n", target);
    }

    return 0;
}
  

πŸ“˜ Explanation:

This C program solves the popular LeetCode “Two Sum” problem. It finds two numbers in an array that add up to a given target sum and returns their indices.

  • malloc() dynamically allocates memory for the result array.
  • twoSum() iterates through the array using nested loops to find a valid pair.
  • The main() function handles input/output for local testing, unlike online judges.
  • Memory allocated using malloc is freed after use to prevent memory leaks.

🧾 Sample Output:

Enter number of elements: 4
Enter 4 elements:
2 7 11 15
Enter target sum: 9

Indices: [0, 1]
Numbers: 2 + 7 = 9
  

πŸ”‘ Keywords:

Two Sum in C, LeetCode C problem, dynamic memory allocation, pointer in C, malloc example, coding interview C, array sum program, logic building C, beginner C project, #1printf

πŸ“Œ Hashtags:

#CProgramming #LeetCode #TwoSum #Pointers #DynamicMemory #DSA #LogicBuilding #Coding #1printf

πŸ” Search Description:

Learn the LeetCode Two Sum solution in C with malloc, pointer handling, and full working main function for practice. Includes explanation and sample output.

C Program to Find Two Numbers with a Given Sum (Two Sum Problem)

✅ C Program to Find Two Numbers with a Given Sum (Two Sum Problem)

#include <stdio.h>
#include <stdlib.h>

int* twoSum(int* nums, int numsSize, int target, int* returnSize) 
{
    for (int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                int* result = (int*)malloc(2 * sizeof(int)); // allocate memory
                result[0] = i;
                result[1] = j;
                *returnSize = 2; // we are returning 2 elements
                return result;
            }
        }
    }

    // If no pair found
    *returnSize = 0;
    return NULL;
}

int main() {
    int nums[] = {2, 7, 11, 15};
    int target = 9;
    int returnSize;

    int* result = twoSum(nums, 4, target, &returnSize);

    if (result != NULL) {
        printf("[%d, %d]\\n", result[0], result[1]);
        free(result); // free allocated memory
    } else {
        printf("No pair found\\n");
    }

    return 0;
}
  

πŸ“˜ Explanation:

This C program finds the indices of two numbers in an array that add up to a given target value. It uses a nested loop to check every pair of elements. When a matching pair is found, it dynamically allocates memory to return their indices.

  • twoSum() — loops through the array and returns indices of the two numbers whose sum equals the target.
  • malloc() — dynamically allocates memory to store the result array.
  • free() — releases the allocated memory after use.

🧾 Sample Output:

Input:
nums = {2, 7, 11, 15}
target = 9

Output:
[0, 1]
  

πŸ”‘ Keywords:

C two sum problem, array pair sum in C, dynamic memory allocation, find indices in array, nested loop example, C coding interview, target sum in C

πŸ“Œ Hashtags:

#CProgramming #Array #TwoSum #CodingInterview #LogicBuilding #DSA #1printf

πŸ” Search Description:

Learn how to find two numbers in an array whose sum matches a given target in C. Includes explanation, sample output, and dark-themed code block with copy button.

C Program to Find Two Numbers with a Given Sum Using Dynamic Memory (Two Sum Problem)

✅ C Program to Find Two Numbers with a Given Sum Using Dynamic Memory (Two Sum Problem)

#include <stdio.h>
#include <stdlib.h>

int* twoSum(int* nums, int numsSize, int target, int* returnSize) 
{
    for (int i = 0; i < numsSize; i++) {
        for (int j = i + 1; j < numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                int* result = (int*)malloc(2 * sizeof(int)); // dynamically allocate array
                result[0] = i;
                result[1] = j;
                *returnSize = 2; // we return 2 indices
                return result;
            }
        }
    }
    *returnSize = 0;
    return NULL;
}

int main() {
    int n, target;

    // Step 1: Take array size
    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Step 2: Create array dynamically
    int* nums = (int*)malloc(n * sizeof(int));

    // Step 3: Take array elements
    printf("Enter %d elements:\\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &nums[i]);
    }

    // Step 4: Take target value
    printf("Enter target sum: ");
    scanf("%d", &target);

    int returnSize;
    int* ans = twoSum(nums, n, target, &returnSize);

    // Step 5: Display result
    if (ans != NULL) {
        printf("Indices: [%d, %d]\\n", ans[0], ans[1]);
        free(ans);
    } else {
        printf("No two numbers add up to %d\\n", target);
    }

    // Step 6: Free memory
    free(nums);

    return 0;
}
  

πŸ“˜ Explanation:

This program finds the indices of two numbers in an array whose sum equals a user-given target. It uses nested loops to check all pairs and dynamically allocates memory to store and return the pair of indices.

  • malloc() — used to dynamically allocate memory for arrays at runtime.
  • twoSum() — returns the indices of two numbers that add up to the given target.
  • free() — releases dynamically allocated memory to avoid memory leaks.

🧾 Sample Output:

Enter number of elements: 4
Enter 4 elements:
2 7 11 15
Enter target sum: 9
Indices: [0, 1]
  

πŸ”‘ Keywords:

C two sum program, find pair in array, target sum in C, malloc free C example, DSA C programs, array index sum, dynamic input in C, C logic practice, two number sum in C

πŸ“Œ Hashtags:

#CProgramming #Array #DynamicMemory #TwoSum #LogicBuilding #CodingInterview #DSA #1printf

πŸ” Search Description:

Learn how to find two numbers in an array whose sum matches a given target using dynamic memory in C. Includes detailed explanation, sample output, and a dark-themed Blogger code block with copy button.

Comments

Popular Posts

πŸŒ™