Problem Statement
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Example:-
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Intuition
Complexity Analysis
- Time complexity : O(n^2). For each element, we try to find its complement by looping through the rest of array which takes O(n) time. Therefore, the time complexity is O(n^2).
- Space complexity : O(1)
Improvement
Complexity Analysis:
- Time complexity : O(n). We traverse the list containing n elements exactly twice. Since the hash table reduces the look up time to O(1), the time complexity is O(n).
- Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly n elements.
Explanation
An algorithm is a well defined list of steps for solving a particular problem. There are two major factors which govern the efficiency of an algorithm.
- Space : the data storage (RAM, HDD etc.)consumed in performing a given task.
- Time : time (computation time or response time)consumed in performing a given task.
Space-time trade-off in a general sense state that :
You can decrease the time complexity of your algorithm in exchange for greater space, or consume lesser space in exchange for slower executions. Time and space is usually calculated in terms of big O. big O notation is how an algorithm’s running time or space requirements grow as the input size grows.
Feel free to post queries.