Leetcode 1 Solution

This article provides solution to leetcode question 1 (two-sum)


Thinking Process

This is a very easy question. To check if any of the two numbers can be added up to target, we just need to check if target - num exists in the array for each num in the array.

To check if an element is in a data set, we’ll leverage hashmap.

Time & Space Complexity

Assuming N is the size of the array, the time & space compelxities are:

  • Time complexity: O(N)
  • Space complexity: O(N)


class Solution {
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> p;

        for (int i = 0; i < nums.size(); i++)
            p[nums[i]] = i;

        for (int i = 0; i < nums.size(); i++)
            if (p.find(target - nums[i]) == p.end())

            int other = p[target - nums[i]];

            if (i == other)

            return {i, other};

        return {};