Array
Array
8
coding interview
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
By Ashay Nayak
Hi Ashay! I am Hey Shrey! Thanks
Shrey. I am going for giving me this
to take your oppportunity.
ASHAY NAYAK
technical round.
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
By Ashay Nayak
I am going to ask
few Coding
ASHAY NAYAK
Questions. okay.
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
By Ashay Nayak
Given an array of integers
nums and an integer target,
ASHAY NAYAK
return indices of the two
numbers such that they add
ASHAY NAYAK
up to target.
hmm...
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
By Ashay Nayak
Examples
Example 1:
ASHAY NAYAK
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
ASHAY NAYAK
Explanation: Because nums[0] + nums[1] == 9,
we return [0, 1].
ASHAY NAYAK
Example 2:
ASHAY NAYAK
Input: nums = [3,2,4], target = 6
Output: [1,2]
ASHAY NAYAK
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
By Ashay Nayak
Approach 1
ASHAY NAYAK
ASHAY NAYAK
Two for loops: Here, you need to use two "for
loops" and take the sum of all possible
ASHAY NAYAK
combinations. If you find the sum equal to the
target value then return the results.
TC → ASHAY
→ NAYAK
O(n²) and SC O(1)
ASHAY NAYAK
By Ashay Nayak Source: My Medium Article
Approach 2
Sort the array and use two pointers. start=0,
end=n-1.
ASHAY NAYAK
ASHAY NAYAK
if(nums[start]+nums[end]==target) then
return answer,
ASHAY NAYAK
else if(nums[start]+nums[end]<target) then
start=start+1 as we need to increase the sum
ASHAY NAYAK
to reach the target value,
else if(nums[start]+nums[end]>target) then
ASHAY NAYAK
end=end-1 as we need to decrease the sum to
reach the target value.
ASHAY NAYAK
Approach 2 will not work for this question
ASHAY NAYAK
because here we have to return the indices of
the numbers whose sum equals to target. Due
ASHAY NAYAK
to sorting, indices got changed for each
element. However, this approach can be used
ASHAY NAYAK
when you need to “check the existence of a
pair in an array with sum as target value”
ASHAY NAYAK
By Ashay Nayak Source: My Medium Article
Approach 3
Using HashMap: Best solution
ASHAY NAYAK
This solution is based on the idea that a+b =
ASHAY NAYAK
target and if we know the value of a and
target then b = target-a.
ASHAY NAYAK
If you are looking to understand
algorithm with code for interviews,
this
ASHAY NAYAK
then check out my article link given in the
ASHAY NAYAK
comment below.
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
ASHAY NAYAK
By Ashay Nayak