The two-sum problem is a classic algorithmic problem where, given an array of integers and a target sum, you need to find two numbers in the array that add up to the target sum. A naive solution involves using two nested loops to check every pair of numbers in the array.
Below is a Zig implementation of the naive two-sum solution:
zig
const std = @import("std");
// Function to find two numbers in the array that sum up to the target
fn twoSumNaive(arr: []i32, target: i32) ?[2]usize {
// Iterate through each element in the array
for (arr, 0..) |num1, i| {
// Compare it with every other element
for (arr[i + 1 ..], 0..) |num2, j| {
if (num1 + num2 == target) {
// Return the indices of the two numbers
return [2]usize{ i, i + 1 + j };
}
}
}
// If no such pair exists, return null
return null;
}
pub fn main() void {
const arr = [_]i32{ 2, 7, 11, 15 };
const target: i32 = 9;
// Call the twoSumNaive function
if (twoSumNaive(&arr, target)) |result| {
std.debug.print("Indices: [{d}, {d}]\n", .{ result[0], result[1] });
} else {
std.debug.print("No two numbers found that sum to the target.\n", .{});
}
}
Explanation of the Code:
Function twoSumNaive:
Takes an array of integers (arr) and a target sum (target) as input.
Uses two nested loops:
The outer loop iterates through each element in the array.
The inner loop checks every subsequent element to see if their sum equals the target.
If a valid pair is found, it returns the indices of the two numbers as an array [2]usize.
If no such pair exists, it returns null.
Main Function:
Defines a sample array and target value.
Calls the twoSumNaive function and prints the result if a valid pair is found. Otherwise, it prints a message indicating no solution was found.
Example Output:
For the input array [2, 7, 11, 15] and target 9, the output will be:
code
Indices: [0, 1]
Complexity:
Time Complexity: (O(n^2)), where (n) is the length of the array. This is because we are using two nested loops to check every pair of numbers.
Space Complexity: (O(1)), as no additional space is used apart from a few variables.
This naive approach is straightforward but not efficient for large arrays. For better performance, you can use a hash map to reduce the time complexity to (O(n)). Let me know if you'd like to see that optimized version!