Coding Interview: Problem #1 [Easy]
Coding Interview: Problem #1 [Easy]
Given a list of numbers and a number k
, return whether any two numbers from the list add up to k
.
For example, given [10, 15, 3, 7]
and k
of 17
, return true since 10 + 7
is 17
.
Bonus: Can you do this in one pass?
Here are some solutions that solves this problem
Here’s the Python code for the solution:
Here’s a solution that solves this problem in one pass using a set to track the numbers we’ve already encountered. The idea is that for each number in the list, we check if the complement (i.e., k - current number
) exists in the set. If it does, we return True
, because we’ve found two numbers that sum to k
. If not, we add the current number to the set and continue.
python learn code with The ÂN
def two_sum(nums, k):
seen = set()
for num in nums:
complement = k - num
if complement in seen:
return True
seen.add(num)
return False
Example: For the input:
python learn code with The ÂN
nums = [10, 15, 3, 7]
k = 17
Calling two_sum(nums, k)
will return True
, because 10 + 7 = 17
.
Explanation:
- We iterate through the list once.
- At each step, we check if the complement of the current number (i.e.,
k - current number
) is in the set. - If the complement exists, we know two numbers add up to
k
, and we returnTrue
. - Otherwise, we add the current number to the set and continue checking.
This approach runs in O(n) time, making it efficient since it only requires one pass through the list.
Here’s the C code for the solution:
Here’s a C implementation to solve the problem where you check if any two numbers from a given list add up to a target value k
. To achieve this in one pass, we can use a hash map (or an array in this case, since we're only dealing with integers) to keep track of the numbers we've seen so far and check if the complement (i.e., k - current number
) exists.
c learn code with The ÂN
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// Hash function to map numbers to a specific range
int hash(int num, int size) {
return abs(num) % size;
}
// Function to check if two numbers add up to k
bool two_sum(int *nums, int length, int k) {
// Creating a hash table with some arbitrary size larger than the input length
int size = 1000;
int *hashTable = (int *)calloc(size, sizeof(int));
for (int i = 0; i < length; i++) {
int complement = k - nums[i];
int hashIndex = hash(complement, size);
// Check if the complement is already in the hash table
if (hashTable[hashIndex] == 1) {
free(hashTable); // Clean up allocated memory
return true;
}
// Add the current number to the hash table
hashTable[hash(nums[i], size)] = 1;
}
free(hashTable); // Clean up allocated memory
return false;
}
int main() {
int nums[] = {10, 15, 3, 7};
int k = 17;
int length = sizeof(nums) / sizeof(nums[0]);
if (two_sum(nums, length, k)) {
printf("True\n");
} else {
printf("False\n");
}
return 0;
}
Explanation:
- Hash Table Simulation:
- We use a hash function to simulate a hash table by storing values in an array, and we only need to store the presence of numbers (
1
means the number is seen). - The hash function maps both positive and negative numbers to indices in the array. You can adjust the size of the array as needed based on the input range.
- We use a hash function to simulate a hash table by storing values in an array, and we only need to store the presence of numbers (
- One-Pass Logic:
- For each number in the array, we compute its complement (i.e.,
k - current number
). - We check if the complement is already in our hash table.
- If found, we return
true
because we've found two numbers that add up tok
. - Otherwise, we store the current number in the hash table and move on to the next number.
- For each number in the array, we compute its complement (i.e.,
- Time Complexity:
- The time complexity is O(n), where
n
is the length of the input list. We only loop through the list once, and hash lookups and insertions take constant time.
- The time complexity is O(n), where
- Space Complexity:
- The space complexity depends on the size of the hash table, which is linear with respect to the number of distinct numbers processed.
Here’s the C++ code for the solution:
Here is the C++ implementation to solve the problem where you need to check if any two numbers from a given list add up to a target value k
. We can use an unordered set in C++ to achieve this efficiently in one pass, similar to how we used a hash table in the C solution.
cpp learn code with The ÂN
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
// Function to check if two numbers add up to k
bool two_sum(const vector<int>& nums,int k) {
unordered_set<int> seen; // Set to store the numbers we've seen
for (int num : nums) {
int complement = k - num;
// Check if the complement is in the set
if (seen.find(complement) != seen.end()) {
return true; // We found two numbers that add up to k
}
// Add the current number to the set
seen.insert(num);
}
return false; // If no pair found, return false
}
int main() {
vector<int>& nums = {10, 15, 3, 7};
int k = 17;
if (two_sum(nums, k)) {
cout << "True" << endl;
} else {
cout << "False" << endl;
}
return 0;
}
unordered_set
:- We use an
unordered_set
from the C++ Standard Library, which allows us to check if a number (complement) is already seen in constant time.
- We use an
- Logic:
- We loop through the list once, and for each number, we calculate the complement as
k - num
. - We then check if the complement is already in the set. If it is, we know we've found two numbers that add up to
k
and returntrue
. - If the complement is not in the set, we add the current number to the set and move to the next one.
- We loop through the list once, and for each number, we calculate the complement as
- Efficiency:
- This solution is very efficient with a time complexity of O(n), where
n
is the length of the input array. It only requires one pass through the list, and both insertions and lookups in anunordered_set
are O(1) on average. - The space complexity is O(n) due to the space used by the
unordered_set
.
- This solution is very efficient with a time complexity of O(n), where
Example: For the input:
cpp learn code with The ÂN
vector<int> nums = {10, 15, 3, 7};
int k = 17;
The output will be:
graphql learn code with The ÂN
True
Since 10 + 7 = 17
, the function will return true
.
Quý anh/chị đang tìm kiếm một doanh nghiệp uy tín cung cấp dịch vụ Công Nghệ Thông Tin như Thiết kế và lập trình website, Digital Marketing, hoặc dịch vụ Bảo trì và chăm sóc hệ thống máy tính, ...? Đừng ngần ngại hãy liên hệ với The ÂN qua số điện thoại (+84).36217.9854 để được tư vấn cụ thể, hoặc liên hệ qua mẫu tin.
Các thông tin nổi bật khác:
- 🔥 ƯU ĐÃI CỰC LỚN: THIẾT KẾ WEBSITE DOANH NGHIỆP CHỈ VỚI 9 TRIỆU ĐỒNG! 🔥
- Các vấn đề khác liên quan đến phòng IT thuê ngoài?
- Các kỹ năng IT nội bộ cơ bản của một công ty bao gồm những gì?
- Những bất tiện khi sử dụng dịch vụ Phòng IT Thuê ngoài là gì?
- Tôi có cần một trang web không khi đã có phương tiện truyền thông xã hội?