> For the complete documentation index, see [llms.txt](https://grind75-notes.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://grind75-notes.gitbook.io/notes/week-1/two-sums.md).

# Two Sum

{% embed url="<https://leetcode.com/problems/two-sum/>" %}

### Problem

> Given an array of integers `nums` and an integer `target`, return *indices of the two numbers such that they add up to `target`*.
>
> You may assume that each input would have ***exactly***\*\* one solution\*\*, and you may not use the *same* element twice.
>
> You can return the answer in any order.

### Pseudocode

```
- loop thorugh the array of integers
- find the complement of the current integer
    - complement = target - nums
    - store complement in a Map as a key, with index with value
        - [k, v] = [complement, i]
- if the current integer is found in the complement
    - return current index and index of complement
```

### Solution

```javascript
var twoSum = function (nums, target) {
  let map = new Map();
  let result = [];

  for (let i = 0; i < nums.length; i++) {
    let complement = target - nums[i];

    // find complement for nums[i]
    if (map.has(nums[i])) {
      result.push(i, map.get(nums[i]));
      return result;
    } else {
      map.set(complement, i);
    }
  }
};
```

### Time and Space Complexity

#### Time

* Loops through the array once - O(N)
* Map operations are constant time
* Total - O(N)

#### Space

* Stores complement of each element in a Map
  * Worst case scenario is that complement is in the last position of the array
* Total - O(N)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://grind75-notes.gitbook.io/notes/week-1/two-sums.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
