Leetcode 167

Two Sum II - Input Array Is Sorted

Table of Contents

Questions

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

Solution

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        unordered_map<int, int> m;
        for(int i = 0; i < numbers.size(); i++){
            if(m.find(target - numbers[i]) != m.end()) {
                return {m[target - numbers[i]] + 1, i + 1};
            }
            
            m[numbers[i]] = i;
        }
        
        return {-1, -1};
    }
};

My solution is using unordered_map to store the index of the number. and check if the complement of the current number is in the map. If it is, then return the indices of the two numbers. If not, then add the current number to the map.

For example, if the numbers is [2, 7, 11, 15] and the target is 9, then the solution is [1, 2]. m[9-2] = 0, m[9-7] = 1, m[9-11] = 2, m[9-15] = 3. m[7] = 1, m[2] = 0, m[-2] = 2, m[-6] = 3. I stored required number in the first argument of the map. and as a value, I stored the index of the number.

This solution is O(n) in time complexity and O(n) in space complexity.

Leetcode 20

Valid Parentheses

Operating Systems - Overview

Week 1. Introduction to Operating Systems