Accepted C++ O(n) Solution - 6ms

  • 0

    At each point in our vector, we can take the difference of our target sum and the currently indexed value. We then check our map to see if we have found this difference before. If we have, then we know that there exists a solution to the problem. If not, we add the difference to our map with the key being the difference and the value being the index.

    vector<int> twoSum(vector<int>& nums, int target) {
            map<int, int> previous_sum;
            vector<int> indices;
            for(int i = 0; i < nums.size(); i++) {
                int difference = target - nums[i];
                auto found = previous_sum.find(difference);
                if(found != previous_sum.end()) {
                } else {
                    previous_sum[nums[i]] = i;
            return indices;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.