
LeetCode #1: Two Sum Problem Solution in PHP
š Introduction
The Two Sum problem is one of the most popular coding interview questions and is often asked in companies like Google, Amazon, and Microsoft.
In this blog, we will solve the problem using PHP, starting from a basic approach to an optimized solution.
š§ Problem Statement
Given an array of integers nums and an integer target, return the indices of two numbers such that they add up to the target.
š Conditions:
- Each input has exactly one solution
- You cannot use the same element twice
- Return answer in any order
š„ Example
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
š Explanation:
nums[0] + nums[1] = 2 + 7 = 9š§© Approach 1: Brute Force (Simple Method)
š Logic
Check every pair of elements and see if they add up to the target.
š» PHP Code
function twoSum($nums, $target) {
$n = count($nums);
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if ($nums[$i] + $nums[$j] == $target) {
return [$i, $j];
}
}
}
return [];
}ā± Time Complexity
- O(n²) ā (Slow for large input)
ā” Approach 2: Optimized (Hash Map Method)
š Logic
- Store numbers in an array (map)
- Check if
target - currentalready exists
š This avoids nested loops!
š» PHP Code
function twoSum($nums, $target) {
$map = [];
foreach ($nums as $index => $num) {
$diff = $target - $num;
if (isset($map[$diff])) {
return [$map[$diff], $index];
} $map[$num] = $index;
}
return [];
}ā± Time Complexity
- O(n) ā (Efficient)
š Dry Run
Input: [2,7,11,15], target = 9
| Step | Num | Diff | Map | Result |
|---|---|---|---|---|
| 1 | 2 | 7 | {2:0} | – |
| 2 | 7 | 2 | Found ā | [0,1] |
š Why This Question is Important
- š§ Tests problem-solving skills
- š Introduces hash maps
- ā” Teaches optimization
- š¼ Common in interviews
ā ļø Common Mistakes
- ā Using same index twice
- ā Not returning indices
- ā Forgetting optimized approach
š Best Practices
- Always think of optimization
- Use associative arrays (maps) in PHP
- Practice dry runs
šÆ Conclusion
The Two Sum problem is a must-know for every developer.
Start with brute force, then move to optimized solutions using hash maps.
No comments yet! You be the first to comment.
