You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today.
R
162 lượt xem

Coding Interview: Problem #1 [Easy]

Learning Programming language With The ÂN

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

  1. Python code for the solution
  2. C code for the solution
  3. C++ code for the solution
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 return True.
  • 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:

  1. 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.
  2. 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 to k.
    • Otherwise, we store the current number in the hash table and move on to the next number.
  3. 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.
  4. 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;
	}
		
	
  1. 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.
  2. 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 return true.
    • If the complement is not in the set, we add the current number to the set and move to the next one.
  3. 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 an unordered_set are O(1) on average.
    • The space complexity is O(n) due to the space used by the unordered_set.

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.

Bài viết khác
Lợi ích của Phòng IT thuê ngoài?
Lợi ích của Phòng IT thuê ngoài?

Phòng IT thuê ngoài, hay còn gọi là dịch vụ IT dựa trên mô hình outsource, mang lại nhiều lợi ích cho các doanh nghiệp, nhất là đối với những công ty không chuyên về công nghệ thông tin. ...