Two Sum
Array, Hash Table
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.
Example 1:
Example 2:
Example 3:
Constraints and Statements:
Input: Array of integers
nums
and an integertarget
.Output: Indices of the two numbers that add up to target.
Assumptions:
Each input has exactly one solution.
The same element cannot be used twice.
The answer can be returned in any order.
Questions to Clarify:
Negative Numbers: Can the input array contain negative numbers? No.
Duplicate Numbers: Can the input array contain duplicate numbers? No.
Unique Solution: Is it guaranteed that there will always be exactly one solution? No.
Multiple Solutions: Should we return all possible solutions, or just one? No.
Indices Required: Do we need to return the actual indices of the solution numbers, or just the numbers themselves? Actual indices of the solution numbers.
Additional Considerations:
Array Size: What are the expected size limits for the input array?
Time and Space Complexity: Are there any specific time or space complexity requirements for the solution?
Algorithm Choice: Would a specific algorithm (e.g., hash table-based or sorting-based) be preferred?
Remember: It's crucial to fully understand the problem's constraints and requirements before attempting to solve it. By asking these clarifying questions, you'll ensure that your solution aligns with the interviewer's expectations and avoids potential misunderstandings.
Solutions
Check sum of two elements is equal to target
element.
Approach – Brute Force Technique
Run two nested loops to check sum of two elements is equal to target element.
Steps
Run a loop up to length of array element with nested loop.
Inside, nested loop check if sum of first loop current element and current element of second loop element are equal to target then indices of both both numbers.
Check till end of entire loop.
If target not found then return empty array.
Complexity
Time Complexity: O(n²)
Auxiliary Space: O(1)
Approach – Using Hash Table
Copy array elements into a hash table and loop over array to check reminder number from hash table.
Steps
Run a loop to copy all array elements and their indices into a hash table.
Run a loop to check reminder number exists in hash table and index of that number is not same as current number then return indices of both both numbers.
If target not found then return empty array.
Complexity
Time Complexity: O(n)
Auxiliary Space: O(n)
Last updated