1- Find pair that sums up to k
Description
Given an array of integers arr and an integer k, create a boolean function that checks if there exists two elements in arr such that we get k when we add them together.
Example 1:
- Input: arr = [4, 5, 1, -3, 6], k = 11
- Output: true
- Explanation: 5 + 6 is equal to 11
Example 2:
- Input: arr = [4, 5, 1, -3, 6], k = -2
- Output: true
- Explanation: 1 + (-3) is equal to -2
Example 3:
- Input: arr = [4, 5, 1, -3, 6], k = 8
- Output: false
- Explanation: there is no pair that sums up to 8
Try some input:
Try to solve:
Select a language:
Solution:
Code:
Select a language:
Python code:
By checking all pairs (brute force solution):
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using a dictionary:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
Java code:
By checking all pairs (brute force solution):
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using a HashMap:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
C++ code:
By checking all pairs (brute force solution):
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using an unordered_map:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
JavaScript code:
By checking all pairs (brute force solution):
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using an Object as a hash table:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
Frequently asked questions:
No questions yet.
You can ask a question in comment section below.
1 comments