|
| 1 | +<br> |
| 2 | +<detailsclass="hint-accordion"> |
| 3 | +<summary>Recommended Time & Space Complexity</summary> |
| 4 | +<p> |
| 5 | +You should aim for a solution with <code>O(n^2)</code> time and <code>O(1)</code> space, where <code>n</code> is the size of the input array. |
| 6 | +</p> |
| 7 | +</details> |
| 8 | + |
| 9 | +<br> |
| 10 | +<detailsclass="hint-accordion"> |
| 11 | +<summary>Hint 1</summary> |
| 12 | +<p> |
| 13 | +A brute force solution would be to check for every triplet in the array. This would be an <code>O(n^3)</code> solution. Can you think of a better way? |
| 14 | +</p> |
| 15 | +</details> |
| 16 | + |
| 17 | +<br> |
| 18 | +<detailsclass="hint-accordion"> |
| 19 | +<summary>Hint 2</summary> |
| 20 | +<p> |
| 21 | +Can you think of an algorithm after sorting the input array? What can we observe by rearranging the given equation in the problem? |
| 22 | +</p> |
| 23 | +</details> |
| 24 | + |
| 25 | +<br> |
| 26 | +<detailsclass="hint-accordion"> |
| 27 | +<summary>Hint 3</summary> |
| 28 | +<p> |
| 29 | + we can iterate through nums with index <code>i</code> and get <code>nums[i] = -(nums[j] + nums[k])</code> after rearranging the equation, making <code>-nums[i] = nums[j] + nums[k]</code>. For each index <code>i</code>, we should efficiently calculate the <code>j</code> and <code>k</code> pairs without duplicates. Which algorithm is suitable to find <code>j</code> and <code>k</code> pairs? |
| 30 | +</p> |
| 31 | +</details> |
| 32 | + |
| 33 | +<br> |
| 34 | +<detailsclass="hint-accordion"> |
| 35 | +<summary>Hint 4</summary> |
| 36 | +<p> |
| 37 | +To efficiently find the <code>j</code> and <code>k</code> pairs, we run the two pointer approach on the elements to the right of index <code>i</code> as the array is sorted. When we run two pointer algorithm, consider <code>j</code> and <code>k</code> as pointers (<code>j</code> is at left, <code>k</code> is at right) and <code>target = -nums[i]</code>, if the current sum <code>num[j] + nums[k] < target</code> then we need to increase the value of current sum by incrementing <code>j</code> pointer. Else if the current sum <code>num[j] + nums[k] > target</code> then we should decrease the value of current sum by decrementing <code>k</code> pointer. How do you deal with duplicates? |
| 38 | +</p> |
| 39 | +</details> |
| 40 | + |
| 41 | +<br> |
| 42 | +<detailsclass="hint-accordion"> |
| 43 | +<summary>Hint 5</summary> |
| 44 | +<p> |
| 45 | + When the current sum <code>nums[j] + nums[k] == target</code> add this pair to the result. We can move <code>j</code> or <code>k</code> pointer until <code>j < k</code> and the pairs are repeated. This ensures that no duplicate pairs are added to the result. |
| 46 | +</p> |
| 47 | +</details> |