🧩 Is it possible to optimize the runtime of a two-sum solution by receiving a pre-sorted input either in ascending or descending order?
🚀 Original Two-Sum
Determine whether there are two items whose individual capacity will perfectly equal the total capacity while ensuring the same item cannot be selected twice.
- Input: An Int representing the total capacity and an Array of Int's representing items' individual capacities.
- Output: A Boolean representing whether it is possible for two of the items to equal the total capacity.
- Time complexity: Linear growth, $O(n)$
- Space complexity: Linear growth, $O(n)$
Samples
Input: [4, 5, 2, 6]
- Total capacity:
10
- Expect:
true
Input: [4, 5, 2, 5]
- Total capacity:
10
- Expect:
true
Input: [4, 5, 2, 7]
- Total capacity:
10
- Expect:
false
Pseudocode
Create a Set
searchSet
to store the item's that have already been examined.Iterate through the input Array of item capacities.
2a. Find the
targetCapacity
for the current item:totalCapacity - itemCapacity
2b. If
searchSet
contains thetargetCapacity
, returntrue
.2c. Else, add the
itemCapacity
to thesearchSet
.Return
false
if the entire input is iterated through without finding a match.
🏗️ Pre-Sort
- Save a new var
lastTargetCapacity
- If the current
itemCapacity
<lastTargetCapacity
, there are no possible two-sums and returnfalse
.
i.e.
Input: [6,2,1,0]
- Total capacity:
9
Iterations
targetCapacity = 9 - 6
,lastTargetCapacity
= 3- Return false because the
itemCapacity
of2
<lastTargetCapacity
of3
.