Skip to content

1. Two Sum #32

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

Let's implement this solution in PHP: 1. Two Sum

<?php
// Test the function with example inputs
print_r(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1]
print_r(twoSum([3, 2, 4], 6)); // Output: [1, 2]
print_r(twoSum([3, 3], 6)); // Output: [0, 1]
?>

Explanation:

  1. Initialization:

    • Create an empty associative array $map to store the numbers and their indices.
  2. Iteration:

    • Loop through the array using a foreach loop.
    • For each number, calculate its complement ($target - $num).
  3. Check for Complement:

    • If the complement exists in the associative array (isset($map[$complement])), return the index of the complement and the current index.
    • If not…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
1 participant